id
stringlengths
25
30
content
stringlengths
14
942k
max_stars_repo_path
stringlengths
49
55
crossvul-cpp_data_bad_160_3
/* * 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/. * * ---------------------------------------------------------------------------- * Misc utils and cheapskate stdlib implementation * ---------------------------------------------------------------------------- */ #include "jsutils.h" #include "jslex.h" #include "jshardware.h" #include "jsinteractive.h" #include "jswrapper.h" #include "jswrap_error.h" #include "jswrap_json.h" /** Error flags for things that we don't really want to report on the console, * but which are good to know about */ volatile JsErrorFlags jsErrorFlags; bool isWhitespace(char ch) { return (ch==0x09) || // \t - tab (ch==0x0B) || // vertical tab (ch==0x0C) || // form feed (ch==0x20) || // space (ch=='\n') || (ch=='\r'); } bool isNumeric(char ch) { return (ch>='0') && (ch<='9'); } bool isHexadecimal(char ch) { return ((ch>='0') && (ch<='9')) || ((ch>='a') && (ch<='f')) || ((ch>='A') && (ch<='F')); } bool isAlpha(char ch) { return ((ch>='a') && (ch<='z')) || ((ch>='A') && (ch<='Z')) || ch=='_'; } bool isIDString(const char *s) { if (!isAlpha(*s)) return false; while (*s) { if (!(isAlpha(*s) || isNumeric(*s))) return false; s++; } return true; } /** escape a character - if it is required. This may return a reference to a static array, so you can't store the value it returns in a variable and call it again. */ const char *escapeCharacter(char ch) { if (ch=='\b') return "\\b"; if (ch=='\f') return "\\f"; if (ch=='\n') return "\\n"; if (ch=='\a') return "\\a"; if (ch=='\r') return "\\r"; if (ch=='\t') return "\\t"; if (ch=='\\') return "\\\\"; if (ch=='"') return "\\\""; static char buf[5]; if (ch<32 || ch>=127) { /** just encode as hex - it's more understandable * and doesn't have the issue of "\16"+"1" != "\161" */ buf[0]='\\'; buf[1]='x'; int n = (ch>>4)&15; buf[2] = (char)((n<10)?('0'+n):('A'+n-10)); n=ch&15; buf[3] = (char)((n<10)?('0'+n):('A'+n-10)); buf[4] = 0; return buf; } buf[1] = 0; buf[0] = ch; return buf; } /** Parse radix prefixes, or return 0 */ NO_INLINE int getRadix(const char **s, int forceRadix, bool *hasError) { int radix = 10; if (forceRadix > 36) { if (hasError) *hasError = true; return 0; } if (**s == '0') { radix = 8; (*s)++; // OctalIntegerLiteral: 0o01, 0O01 if (**s == 'o' || **s == 'O') { radix = 8; if (forceRadix && forceRadix!=8 && forceRadix<25) return 0; (*s)++; // HexIntegerLiteral: 0x01, 0X01 } else if (**s == 'x' || **s == 'X') { radix = 16; if (forceRadix && forceRadix!=16 && forceRadix<34) return 0; (*s)++; // BinaryIntegerLiteral: 0b01, 0B01 } else if (**s == 'b' || **s == 'B') { radix = 2; if (forceRadix && forceRadix!=2 && forceRadix<12) return 0; else (*s)++; } else if (!forceRadix) { // check for '.' or digits 8 or 9 - if so it's decimal const char *p; for (p=*s;*p;p++) if (*p=='.' || *p=='8' || *p=='9') radix = 10; else if (*p<'0' || *p>'9') break; } } if (forceRadix>0 && forceRadix<=36) radix = forceRadix; return radix; } // Convert a character to the hexadecimal equivalent (or -1) int chtod(char ch) { if (ch >= '0' && ch <= '9') return ch - '0'; else if (ch >= 'a' && ch <= 'z') return 10 + ch - 'a'; else if (ch >= 'A' && ch <= 'Z') return 10 + ch - 'A'; else return -1; } /* convert a number in the given radix to an int */ long long stringToIntWithRadix(const char *s, int forceRadix, //!< if radix=0, autodetect bool *hasError, //!< If nonzero, set to whether there was an error or not const char **endOfInteger //!< If nonzero, this is set to the point at which the integer finished in the string ) { // skip whitespace (strange parseInt behaviour) while (isWhitespace(*s)) s++; bool isNegated = false; long long v = 0; if (*s == '-') { isNegated = true; s++; } else if (*s == '+') { s++; } const char *numberStart = s; if (endOfInteger) (*endOfInteger)=s; int radix = getRadix(&s, forceRadix, hasError); if (!radix) return 0; while (*s) { int digit = chtod(*s); if (digit<0 || digit>=radix) break; v = v*radix + digit; s++; } if (hasError) *hasError = s==numberStart; // we had an error if we didn't manage to parse any chars at all if (endOfInteger) (*endOfInteger)=s; if (isNegated) return -v; return v; } /** * Convert hex, binary, octal or decimal string into an int. */ long long stringToInt(const char *s) { return stringToIntWithRadix(s,0,NULL,NULL); } #ifndef USE_FLASH_MEMORY // JsError, jsWarn, jsExceptionHere implementations that expect the format string to be in normal // RAM where is can be accessed normally. NO_INLINE void jsError(const char *fmt, ...) { jsiConsoleRemoveInputLine(); jsiConsolePrint("ERROR: "); va_list argp; va_start(argp, fmt); vcbprintf((vcbprintf_callback)jsiConsolePrintString,0, fmt, argp); va_end(argp); jsiConsolePrint("\n"); } NO_INLINE void jsWarn(const char *fmt, ...) { jsiConsoleRemoveInputLine(); jsiConsolePrint("WARNING: "); va_list argp; va_start(argp, fmt); vcbprintf((vcbprintf_callback)jsiConsolePrintString,0, fmt, argp); va_end(argp); jsiConsolePrint("\n"); } NO_INLINE void jsExceptionHere(JsExceptionType type, const char *fmt, ...) { // If we already had an exception, forget this if (jspHasError()) return; jsiConsoleRemoveInputLine(); JsVar *var = jsvNewFromEmptyString(); if (!var) { jspSetError(false); return; // out of memory } JsvStringIterator it; jsvStringIteratorNew(&it, var, 0); jsvStringIteratorGotoEnd(&it); vcbprintf_callback cb = (vcbprintf_callback)jsvStringIteratorPrintfCallback; va_list argp; va_start(argp, fmt); vcbprintf(cb,&it, fmt, argp); va_end(argp); jsvStringIteratorFree(&it); if (type != JSET_STRING) { JsVar *obj = 0; if (type == JSET_ERROR) obj = jswrap_error_constructor(var); else if (type == JSET_SYNTAXERROR) obj = jswrap_syntaxerror_constructor(var); else if (type == JSET_TYPEERROR) obj = jswrap_typeerror_constructor(var); else if (type == JSET_INTERNALERROR) obj = jswrap_internalerror_constructor(var); else if (type == JSET_REFERENCEERROR) obj = jswrap_referenceerror_constructor(var); jsvUnLock(var); var = obj; } jspSetException(var); jsvUnLock(var); } #else // JsError, jsWarn, jsExceptionHere implementations that expect the format string to be in FLASH // and first copy it into RAM in order to prevent issues with byte access, this is necessary on // platforms, like the esp8266, where data flash can only be accessed using word-aligned reads. NO_INLINE void jsError_flash(const char *fmt, ...) { size_t len = flash_strlen(fmt); char buff[len+1]; flash_strncpy(buff, fmt, len+1); jsiConsoleRemoveInputLine(); jsiConsolePrint("ERROR: "); va_list argp; va_start(argp, fmt); vcbprintf((vcbprintf_callback)jsiConsolePrintString,0, buff, argp); va_end(argp); jsiConsolePrint("\n"); } NO_INLINE void jsWarn_flash(const char *fmt, ...) { size_t len = flash_strlen(fmt); char buff[len+1]; flash_strncpy(buff, fmt, len+1); jsiConsoleRemoveInputLine(); jsiConsolePrint("WARNING: "); va_list argp; va_start(argp, fmt); vcbprintf((vcbprintf_callback)jsiConsolePrintString,0, buff, argp); va_end(argp); jsiConsolePrint("\n"); } NO_INLINE void jsExceptionHere_flash(JsExceptionType type, const char *ffmt, ...) { size_t len = flash_strlen(ffmt); char fmt[len+1]; flash_strncpy(fmt, ffmt, len+1); // If we already had an exception, forget this if (jspHasError()) return; jsiConsoleRemoveInputLine(); JsVar *var = jsvNewFromEmptyString(); if (!var) { jspSetError(false); return; // out of memory } JsvStringIterator it; jsvStringIteratorNew(&it, var, 0); jsvStringIteratorGotoEnd(&it); vcbprintf_callback cb = (vcbprintf_callback)jsvStringIteratorPrintfCallback; va_list argp; va_start(argp, ffmt); vcbprintf(cb,&it, fmt, argp); va_end(argp); jsvStringIteratorFree(&it); if (type != JSET_STRING) { JsVar *obj = 0; if (type == JSET_ERROR) obj = jswrap_error_constructor(var); else if (type == JSET_SYNTAXERROR) obj = jswrap_syntaxerror_constructor(var); else if (type == JSET_TYPEERROR) obj = jswrap_typeerror_constructor(var); else if (type == JSET_INTERNALERROR) obj = jswrap_internalerror_constructor(var); else if (type == JSET_REFERENCEERROR) obj = jswrap_referenceerror_constructor(var); jsvUnLock(var); var = obj; } jspSetException(var); jsvUnLock(var); } #endif NO_INLINE void jsAssertFail(const char *file, int line, const char *expr) { static bool inAssertFail = false; bool wasInAssertFail = inAssertFail; inAssertFail = true; jsiConsoleRemoveInputLine(); if (expr) { #ifndef USE_FLASH_MEMORY jsiConsolePrintf("ASSERT(%s) FAILED AT ", expr); #else jsiConsolePrintString("ASSERT("); // string is in flash and requires word access, thus copy it onto the stack size_t len = flash_strlen(expr); char buff[len+1]; flash_strncpy(buff, expr, len+1); jsiConsolePrintString(buff); jsiConsolePrintString(") FAILED AT "); #endif } else { jsiConsolePrint("ASSERT FAILED AT "); } jsiConsolePrintf("%s:%d\n",file,line); if (!wasInAssertFail) { jsvTrace(jsvFindOrCreateRoot(), 2); } #if defined(ARM) jsiConsolePrint("REBOOTING.\n"); jshTransmitFlush(); NVIC_SystemReset(); #elif defined(ESP8266) // typically the Espruino console is over telnet, in which case nothing we do here will ever // show up, so we instead jump through some hoops to print to UART int os_printf_plus(const char *format, ...) __attribute__((format(printf, 1, 2))); os_printf_plus("ASSERT FAILED AT %s:%d\n", file,line); jsiConsolePrint("---console end---\n"); int c, console = jsiGetConsoleDevice(); while ((c=jshGetCharToTransmit(console)) >= 0) os_printf_plus("%c", c); os_printf_plus("CRASHING.\n"); *(int*)0xdead = 0xbeef; extern void jswrap_ESP8266_reboot(void); jswrap_ESP8266_reboot(); while(1) ; #elif defined(LINUX) jsiConsolePrint("EXITING.\n"); exit(1); #else jsiConsolePrint("HALTING.\n"); while (1); #endif inAssertFail = false; } #ifdef USE_FLASH_MEMORY // Helpers to deal with constant strings stored in flash that have to be accessed using word-aligned // and word-sized reads // Get the length of a string in flash size_t flash_strlen(const char *str) { size_t len = 0; uint32_t *s = (uint32_t *)str; while (1) { uint32_t w = *s++; if ((w & 0xff) == 0) break; len++; w >>= 8; if ((w & 0xff) == 0) break; len++; w >>= 8; if ((w & 0xff) == 0) break; len++; w >>= 8; if ((w & 0xff) == 0) break; len++; } return len; } // Copy a string from flash char *flash_strncpy(char *dst, const char *src, size_t c) { char *d = dst; uint32_t *s = (uint32_t *)src; size_t slen = flash_strlen(src); size_t len = slen > c ? c : slen; // copy full words from source string while (len >= 4) { uint32_t w = *s++; *d++ = w & 0xff; w >>= 8; *d++ = w & 0xff; w >>= 8; *d++ = w & 0xff; w >>= 8; *d++ = w & 0xff; len -= 4; } // copy any remaining bytes if (len > 0) { uint32_t w = *s++; while (len-- > 0) { *d++ = w & 0xff; w >>= 8; } } // terminating null if (slen < c) *d = 0; return dst; } // Compare a string in memory with a string in flash int flash_strcmp(const char *mem, const char *flash) { while (1) { char m = *mem++; char c = READ_FLASH_UINT8(flash++); if (m == 0) return c != 0 ? -1 : 0; if (c == 0) return 1; if (c > m) return -1; if (m > c) return 1; } } // memcopy a string from flash unsigned char *flash_memcpy(unsigned char *dst, const unsigned char *src, size_t c) { unsigned char *d = dst; uint32_t *s = (uint32_t *)src; size_t len = c; // copy full words from source string while (len >= 4) { uint32_t w = *s++; *d++ = w & 0xff; w >>= 8; *d++ = w & 0xff; w >>= 8; *d++ = w & 0xff; w >>= 8; *d++ = w & 0xff; len -= 4; } // copy any remaining bytes if (len > 0) { uint32_t w = *s++; while (len-- > 0) { *d++ = w & 0xff; w >>= 8; } } return dst; } #endif /** Convert a string to a JS float variable where the string is of a specific radix. */ JsVarFloat stringToFloatWithRadix( const char *s, //!< The string to be converted to a float int forceRadix, //!< The radix of the string data, or 0 to guess const char **endOfFloat //!< If nonzero, this is set to the point at which the float finished in the string ) { // skip whitespace (strange parseFloat behaviour) while (isWhitespace(*s)) s++; bool isNegated = false; if (*s == '-') { isNegated = true; s++; } else if (*s == '+') { s++; } const char *numberStart = s; if (endOfFloat) (*endOfFloat)=s; int radix = getRadix(&s, forceRadix, 0); if (!radix) return NAN; JsVarFloat v = 0; JsVarFloat mul = 0.1; // handle integer part while (*s) { int digit = chtod(*s); if (digit<0 || digit>=radix) break; v = (v*radix) + digit; s++; } if (radix == 10) { // handle decimal point if (*s == '.') { s++; // skip . while (*s) { if (*s >= '0' && *s <= '9') v += mul*(*s - '0'); else break; mul /= 10; s++; } } // handle exponentials if (*s == 'e' || *s == 'E') { s++; // skip E bool isENegated = false; if (*s == '-' || *s == '+') { isENegated = *s=='-'; s++; } int e = 0; while (*s) { if (*s >= '0' && *s <= '9') e = (e*10) + (*s - '0'); else break; s++; } if (isENegated) e=-e; // TODO: faster INTEGER pow? Normal pow has floating point inaccuracies while (e>0) { v*=10; e--; } while (e<0) { v/=10; e++; } } } if (endOfFloat) (*endOfFloat)=s; // check that we managed to parse something at least if (numberStart==s || (numberStart[0]=='.' && numberStart[1]==0)) return NAN; if (isNegated) return -v; return v; } /** convert a string to a floating point JS variable. */ JsVarFloat stringToFloat(const char *s) { return stringToFloatWithRadix(s, 0, NULL); // don't force the radix to anything in particular } char itoch(int val) { if (val<10) return (char)('0'+val); return (char)('a'+val-10); } void itostr_extra(JsVarInt vals,char *str,bool signedVal, unsigned int base) { JsVarIntUnsigned val; // handle negative numbers if (signedVal && vals<0) { *(str++)='-'; val = (JsVarIntUnsigned)(-vals); } else { val = (JsVarIntUnsigned)vals; } // work out how many digits JsVarIntUnsigned tmp = val; int digits = 1; while (tmp>=base) { digits++; tmp /= base; } // for each digit... int i; for (i=digits-1;i>=0;i--) { str[i] = itoch((int)(val % base)); val /= base; } str[digits] = 0; } void ftoa_bounded_extra(JsVarFloat val,char *str, size_t len, int radix, int fractionalDigits) { const JsVarFloat stopAtError = 0.0000001; if (isnan(val)) strncpy(str,"NaN",len); else if (!isfinite(val)) { if (val<0) strncpy(str,"-Infinity",len); else strncpy(str,"Infinity",len); } else { if (val<0) { if (--len <= 0) { *str=0; return; } // bounds check *(str++) = '-'; val = -val; } // what if we're really close to an integer? Just use that... if (((JsVarInt)(val+stopAtError)) == (1+(JsVarInt)val)) val = (JsVarFloat)(1+(JsVarInt)val); JsVarFloat d = 1; while (d*radix <= val) d*=radix; while (d >= 1) { int v = (int)(val / d); val -= v*d; if (--len <= 0) { *str=0; return; } // bounds check *(str++) = itoch(v); d /= radix; } #ifndef USE_NO_FLOATS if (((fractionalDigits<0) && val>0) || fractionalDigits>0) { bool hasPt = false; val*=radix; while (((fractionalDigits<0) && (fractionalDigits>-12) && (val > stopAtError)) || (fractionalDigits > 0)) { int v = (int)(val+((fractionalDigits==1) ? 0.4 : 0.00000001) ); val = (val-v)*radix; if (v==radix) v=radix-1; if (!hasPt) { hasPt = true; if (--len <= 0) { *str=0; return; } // bounds check *(str++)='.'; } if (--len <= 0) { *str=0; return; } // bounds check *(str++)=itoch(v); fractionalDigits--; } } #endif *(str++)=0; } } void ftoa_bounded(JsVarFloat val,char *str, size_t len) { ftoa_bounded_extra(val, str, len, 10, -1); } /// Wrap a value so it is always between 0 and size (eg. wrapAround(angle, 360)) JsVarFloat wrapAround(JsVarFloat val, JsVarFloat size) { val = val / size; val = val - (int)val; return val * size; } /** * Espruino-special printf with a callback. * * The supported format specifiers are: * * `%d` = int * * `%0#d` or `%0#x` = int padded to length # with 0s * * `%x` = int as hex * * `%L` = JsVarInt * * `%Lx`= JsVarInt as hex * * `%f` = JsVarFloat * * `%s` = string (char *) * * `%c` = char * * `%v` = JsVar * (doesn't have to be a string - it'll be converted) * * `%q` = JsVar * (in quotes, and escaped) * * `%j` = Variable printed as JSON * * `%t` = Type of variable * * `%p` = Pin * * Anything else will assert */ void vcbprintf( vcbprintf_callback user_callback, //!< Unknown void *user_data, //!< Unknown const char *fmt, //!< The format specified va_list argp //!< List of parameter values ) { char buf[32]; while (*fmt) { if (*fmt == '%') { fmt++; char fmtChar = *fmt++; switch (fmtChar) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { const char *pad = " "; if (fmtChar=='0') { pad = "0"; fmtChar = *fmt++; } int digits = fmtChar - '0'; // of the form '%02d' int v = va_arg(argp, int); if (*fmt=='x') itostr_extra(v, buf, false, 16); else { assert('d' == *fmt); itostr(v, buf, 10); } fmt++; // skip over 'd' int len = (int)strlen(buf); while (len < digits) { user_callback(pad,user_data); len++; } user_callback(buf,user_data); break; } case 'd': itostr(va_arg(argp, int), buf, 10); user_callback(buf,user_data); break; case 'x': itostr_extra(va_arg(argp, int), buf, false, 16); user_callback(buf,user_data); break; case 'L': { unsigned int rad = 10; bool signedVal = true; if (*fmt=='x') { rad=16; fmt++; signedVal = false; } itostr_extra(va_arg(argp, JsVarInt), buf, signedVal, rad); user_callback(buf,user_data); } break; case 'f': ftoa_bounded(va_arg(argp, JsVarFloat), buf, sizeof(buf)); user_callback(buf,user_data); break; case 's': user_callback(va_arg(argp, char *), user_data); break; case 'c': buf[0]=(char)va_arg(argp, int/*char*/);buf[1]=0; user_callback(buf, user_data); break; case 'q': case 'v': { bool quoted = fmtChar=='q'; if (quoted) user_callback("\"",user_data); JsVar *v = jsvAsString(va_arg(argp, JsVar*), false/*no unlock*/); buf[1] = 0; if (jsvIsString(v)) { JsvStringIterator it; jsvStringIteratorNew(&it, v, 0); // OPT: this could be faster than it is (sending whole blocks at once) while (jsvStringIteratorHasChar(&it)) { buf[0] = jsvStringIteratorGetChar(&it); if (quoted) { user_callback(escapeCharacter(buf[0]), user_data); } else { user_callback(buf,user_data); } jsvStringIteratorNext(&it); } jsvStringIteratorFree(&it); jsvUnLock(v); } if (quoted) user_callback("\"",user_data); } break; case 'j': { JsVar *v = va_arg(argp, JsVar*); jsfGetJSONWithCallback(v, JSON_SOME_NEWLINES | JSON_PRETTY | JSON_SHOW_DEVICES, 0, user_callback, user_data); break; } case 't': { JsVar *v = va_arg(argp, JsVar*); const char *n = jsvIsNull(v)?"null":jswGetBasicObjectName(v); if (!n) n = jsvGetTypeOf(v); user_callback(n, user_data); break; } case 'p': jshGetPinString(buf, (Pin)va_arg(argp, int/*Pin*/)); user_callback(buf, user_data); break; default: assert(0); return; // eep } } else { buf[0] = *(fmt++); buf[1] = 0; user_callback(&buf[0], user_data); } } } void cbprintf(vcbprintf_callback user_callback, void *user_data, const char *fmt, ...) { va_list argp; va_start(argp, fmt); vcbprintf(user_callback,user_data, fmt, argp); va_end(argp); } typedef struct { char *outPtr; size_t idx; size_t len; } espruino_snprintf_data; void espruino_snprintf_cb(const char *str, void *userdata) { espruino_snprintf_data *d = (espruino_snprintf_data*)userdata; while (*str) { if (d->idx < d->len) d->outPtr[d->idx] = *str; d->idx++; str++; } } /// a snprintf replacement so mbedtls doesn't try and pull in the whole stdlib to cat two strings together int espruino_snprintf( char * s, size_t n, const char * fmt, ... ) { espruino_snprintf_data d; d.outPtr = s; d.idx = 0; d.len = n; va_list argp; va_start(argp, fmt); vcbprintf(espruino_snprintf_cb,&d, fmt, argp); va_end(argp); if (d.idx < d.len) d.outPtr[d.idx] = 0; else d.outPtr[d.len-1] = 0; return (int)d.idx; } #ifdef ARM extern int LINKER_END_VAR; // should be 'void', but 'int' avoids warnings #endif /** get the amount of free stack we have, in bytes */ size_t jsuGetFreeStack() { #ifdef ARM void *frame = __builtin_frame_address(0); size_t stackPos = (size_t)((char*)frame); size_t stackEnd = (size_t)((char*)&LINKER_END_VAR); if (stackPos < stackEnd) return 0; // should never happen, but just in case of overflow! return stackPos - stackEnd; #elif defined(LINUX) // On linux, we set STACK_BASE from `main`. char ptr; // this is on the stack extern void *STACK_BASE; uint32_t count = (uint32_t)((size_t)STACK_BASE - (size_t)&ptr); const uint32_t max_stack = 1000000; // give it 1 megabyte of stack if (count>max_stack) return 0; return max_stack - count; #else // stack depth seems pretty platform-specific :( Default to a value that disables it return 1000000; // no stack depth check on this platform #endif } unsigned int rand_m_w = 0xDEADBEEF; /* must not be zero */ unsigned int rand_m_z = 0xCAFEBABE; /* must not be zero */ int rand() { rand_m_z = 36969 * (rand_m_z & 65535) + (rand_m_z >> 16); rand_m_w = 18000 * (rand_m_w & 65535) + (rand_m_w >> 16); return (int)RAND_MAX & (int)((rand_m_z << 16) + rand_m_w); /* 32-bit result */ } void srand(unsigned int seed) { rand_m_w = (seed&0xFFFF) | (seed<<16); rand_m_z = (seed&0xFFFF0000) | (seed>>16); }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_160_3
crossvul-cpp_data_good_341_1
/* * Support for ePass2003 smart cards * * Copyright (C) 2008, Weitao Sun <weitao@ftsafe.com> * Copyright (C) 2011, Xiaoshuo Wu <xiaoshuo@ftsafe.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #ifdef ENABLE_SM /* empty file without SM enabled */ #ifdef ENABLE_OPENSSL /* empty file without openssl */ #include <ctype.h> #include <stdlib.h> #include <string.h> #include <openssl/evp.h> #include <openssl/sha.h> #include "internal.h" #include "asn1.h" #include <ctype.h> #include <stdlib.h> #include <string.h> #include <openssl/evp.h> #include <openssl/sha.h> #include "internal.h" #include "asn1.h" #include "cardctl.h" static struct sc_atr_table epass2003_atrs[] = { /* This is a FIPS certified card using SCP01 security messaging. */ {"3B:9F:95:81:31:FE:9F:00:66:46:53:05:10:00:11:71:df:00:00:00:6a:82:5e", "FF:FF:FF:FF:FF:00:FF:FF:FF:FF:FF:FF:00:00:00:ff:00:ff:ff:00:00:00:00", "FTCOS/ePass2003", SC_CARD_TYPE_ENTERSAFE_FTCOS_EPASS2003, 0, NULL }, {NULL, NULL, NULL, 0, 0, NULL} }; static struct sc_card_operations *iso_ops = NULL; static struct sc_card_operations epass2003_ops; static struct sc_card_driver epass2003_drv = { "epass2003", "epass2003", &epass2003_ops, NULL, 0, NULL }; #define KEY_TYPE_AES 0x01 /* FIPS mode */ #define KEY_TYPE_DES 0x02 /* Non-FIPS mode */ #define KEY_LEN_AES 16 #define KEY_LEN_DES 8 #define KEY_LEN_DES3 24 #define HASH_LEN 24 static unsigned char PIN_ID[2] = { ENTERSAFE_USER_PIN_ID, ENTERSAFE_SO_PIN_ID }; /*0x00:plain; 0x01:scp01 sm*/ #define SM_PLAIN 0x00 #define SM_SCP01 0x01 static unsigned char g_init_key_enc[16] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10 }; static unsigned char g_init_key_mac[16] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10 }; static unsigned char g_random[8] = { 0xBF, 0xC3, 0x29, 0x11, 0xC7, 0x18, 0xC3, 0x40 }; typedef struct epass2003_exdata_st { unsigned char sm; /* SM_PLAIN or SM_SCP01 */ unsigned char smtype; /* KEY_TYPE_AES or KEY_TYPE_DES */ unsigned char sk_enc[16]; /* encrypt session key */ unsigned char sk_mac[16]; /* mac session key */ unsigned char icv_mac[16]; /* instruction counter vector(for sm) */ unsigned char currAlg; /* current Alg */ unsigned int ecAlgFlags; /* Ec Alg mechanism type*/ } epass2003_exdata; #define REVERSE_ORDER4(x) ( \ ((unsigned long)x & 0xFF000000)>> 24 | \ ((unsigned long)x & 0x00FF0000)>> 8 | \ ((unsigned long)x & 0x0000FF00)<< 8 | \ ((unsigned long)x & 0x000000FF)<< 24) static const struct sc_card_error epass2003_errors[] = { { 0x6200, SC_ERROR_CARD_CMD_FAILED, "Warning: no information given, non-volatile memory is unchanged" }, { 0x6281, SC_ERROR_CORRUPTED_DATA, "Part of returned data may be corrupted" }, { 0x6282, SC_ERROR_FILE_END_REACHED, "End of file/record reached before reading Le bytes" }, { 0x6283, SC_ERROR_CARD_CMD_FAILED, "Selected file invalidated" }, { 0x6284, SC_ERROR_CARD_CMD_FAILED, "FCI not formatted according to ISO 7816-4" }, { 0x6300, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C1, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed. One tries left"}, { 0x63C2, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed. Two tries left"}, { 0x63C3, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C4, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C5, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C6, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C7, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C8, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C9, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63CA, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x6381, SC_ERROR_CARD_CMD_FAILED, "Warning: file filled up by last write" }, { 0x6581, SC_ERROR_MEMORY_FAILURE, "Memory failure" }, { 0x6700, SC_ERROR_WRONG_LENGTH, "Wrong length" }, { 0x6800, SC_ERROR_NO_CARD_SUPPORT, "Functions in CLA not supported" }, { 0x6881, SC_ERROR_NO_CARD_SUPPORT, "Logical channel not supported" }, { 0x6882, SC_ERROR_NO_CARD_SUPPORT, "Secure messaging not supported" }, { 0x6900, SC_ERROR_NOT_ALLOWED, "Command not allowed" }, { 0x6981, SC_ERROR_CARD_CMD_FAILED, "Command incompatible with file structure" }, { 0x6982, SC_ERROR_SECURITY_STATUS_NOT_SATISFIED, "Security status not satisfied" }, { 0x6983, SC_ERROR_AUTH_METHOD_BLOCKED, "Authentication method blocked" }, { 0x6984, SC_ERROR_REF_DATA_NOT_USABLE, "Referenced data not usable" }, { 0x6985, SC_ERROR_NOT_ALLOWED, "Conditions of use not satisfied" }, { 0x6986, SC_ERROR_NOT_ALLOWED, "Command not allowed (no current EF)" }, { 0x6987, SC_ERROR_INCORRECT_PARAMETERS,"Expected SM data objects missing" }, { 0x6988, SC_ERROR_INCORRECT_PARAMETERS,"SM data objects incorrect" }, { 0x6A00, SC_ERROR_INCORRECT_PARAMETERS,"Wrong parameter(s) P1-P2" }, { 0x6A80, SC_ERROR_INCORRECT_PARAMETERS,"Incorrect parameters in the data field" }, { 0x6A81, SC_ERROR_NO_CARD_SUPPORT, "Function not supported" }, { 0x6A82, SC_ERROR_FILE_NOT_FOUND, "File not found" }, { 0x6A83, SC_ERROR_RECORD_NOT_FOUND, "Record not found" }, { 0x6A84, SC_ERROR_NOT_ENOUGH_MEMORY, "Not enough memory space in the file" }, { 0x6A85, SC_ERROR_INCORRECT_PARAMETERS,"Lc inconsistent with TLV structure" }, { 0x6A86, SC_ERROR_INCORRECT_PARAMETERS,"Incorrect parameters P1-P2" }, { 0x6A87, SC_ERROR_INCORRECT_PARAMETERS,"Lc inconsistent with P1-P2" }, { 0x6A88, SC_ERROR_DATA_OBJECT_NOT_FOUND,"Referenced data not found" }, { 0x6A89, SC_ERROR_FILE_ALREADY_EXISTS, "File already exists"}, { 0x6A8A, SC_ERROR_FILE_ALREADY_EXISTS, "DF name already exists"}, { 0x6B00, SC_ERROR_INCORRECT_PARAMETERS,"Wrong parameter(s) P1-P2" }, { 0x6D00, SC_ERROR_INS_NOT_SUPPORTED, "Instruction code not supported or invalid" }, { 0x6E00, SC_ERROR_CLASS_NOT_SUPPORTED, "Class not supported" }, { 0x6F00, SC_ERROR_CARD_CMD_FAILED, "No precise diagnosis" }, { 0x9000,SC_SUCCESS, NULL } }; static int epass2003_transmit_apdu(struct sc_card *card, struct sc_apdu *apdu); static int epass2003_select_file(struct sc_card *card, const sc_path_t * in_path, sc_file_t ** file_out); int epass2003_refresh(struct sc_card *card); static int hash_data(const unsigned char *data, size_t datalen, unsigned char *hash, unsigned int mechanismType); static int epass2003_check_sw(struct sc_card *card, unsigned int sw1, unsigned int sw2) { const int err_count = sizeof(epass2003_errors)/sizeof(epass2003_errors[0]); int i; /* Handle special cases here */ if (sw1 == 0x6C) { sc_log(card->ctx, "Wrong length; correct length is %d", sw2); return SC_ERROR_WRONG_LENGTH; } for (i = 0; i < err_count; i++) { if (epass2003_errors[i].SWs == ((sw1 << 8) | sw2)) { sc_log(card->ctx, "%s", epass2003_errors[i].errorstr); return epass2003_errors[i].errorno; } } sc_log(card->ctx, "Unknown SWs; SW1=%02X, SW2=%02X", sw1, sw2); return SC_ERROR_CARD_CMD_FAILED; } static int sc_transmit_apdu_t(sc_card_t *card, sc_apdu_t *apdu) { int r = sc_transmit_apdu(card, apdu); if ( ((0x69 == apdu->sw1) && (0x85 == apdu->sw2)) || ((0x69 == apdu->sw1) && (0x88 == apdu->sw2))) { epass2003_refresh(card); r = sc_transmit_apdu(card, apdu); } return r; } static int openssl_enc(const EVP_CIPHER * cipher, const unsigned char *key, const unsigned char *iv, const unsigned char *input, size_t length, unsigned char *output) { int r = SC_ERROR_INTERNAL; EVP_CIPHER_CTX * ctx = NULL; int outl = 0; int outl_tmp = 0; unsigned char iv_tmp[EVP_MAX_IV_LENGTH] = { 0 }; memcpy(iv_tmp, iv, EVP_MAX_IV_LENGTH); ctx = EVP_CIPHER_CTX_new(); if (ctx == NULL) goto out; EVP_EncryptInit_ex(ctx, cipher, NULL, key, iv_tmp); EVP_CIPHER_CTX_set_padding(ctx, 0); if (!EVP_EncryptUpdate(ctx, output, &outl, input, length)) goto out; if (!EVP_EncryptFinal_ex(ctx, output + outl, &outl_tmp)) goto out; r = SC_SUCCESS; out: if (ctx) EVP_CIPHER_CTX_free(ctx); return r; } static int openssl_dec(const EVP_CIPHER * cipher, const unsigned char *key, const unsigned char *iv, const unsigned char *input, size_t length, unsigned char *output) { int r = SC_ERROR_INTERNAL; EVP_CIPHER_CTX * ctx = NULL; int outl = 0; int outl_tmp = 0; unsigned char iv_tmp[EVP_MAX_IV_LENGTH] = { 0 }; memcpy(iv_tmp, iv, EVP_MAX_IV_LENGTH); ctx = EVP_CIPHER_CTX_new(); if (ctx == NULL) goto out; EVP_DecryptInit_ex(ctx, cipher, NULL, key, iv_tmp); EVP_CIPHER_CTX_set_padding(ctx, 0); if (!EVP_DecryptUpdate(ctx, output, &outl, input, length)) goto out; if (!EVP_DecryptFinal_ex(ctx, output + outl, &outl_tmp)) goto out; r = SC_SUCCESS; out: if (ctx) EVP_CIPHER_CTX_free(ctx); return r; } static int aes128_encrypt_ecb(const unsigned char *key, int keysize, const unsigned char *input, size_t length, unsigned char *output) { unsigned char iv[EVP_MAX_IV_LENGTH] = { 0 }; return openssl_enc(EVP_aes_128_ecb(), key, iv, input, length, output); } static int aes128_encrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[16], const unsigned char *input, size_t length, unsigned char *output) { return openssl_enc(EVP_aes_128_cbc(), key, iv, input, length, output); } static int aes128_decrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[16], const unsigned char *input, size_t length, unsigned char *output) { return openssl_dec(EVP_aes_128_cbc(), key, iv, input, length, output); } static int des3_encrypt_ecb(const unsigned char *key, int keysize, const unsigned char *input, int length, unsigned char *output) { unsigned char iv[EVP_MAX_IV_LENGTH] = { 0 }; unsigned char bKey[24] = { 0 }; if (keysize == 16) { memcpy(&bKey[0], key, 16); memcpy(&bKey[16], key, 8); } else { memcpy(&bKey[0], key, 24); } return openssl_enc(EVP_des_ede3(), bKey, iv, input, length, output); } static int des3_encrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH], const unsigned char *input, size_t length, unsigned char *output) { unsigned char bKey[24] = { 0 }; if (keysize == 16) { memcpy(&bKey[0], key, 16); memcpy(&bKey[16], key, 8); } else { memcpy(&bKey[0], key, 24); } return openssl_enc(EVP_des_ede3_cbc(), bKey, iv, input, length, output); } static int des3_decrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH], const unsigned char *input, size_t length, unsigned char *output) { unsigned char bKey[24] = { 0 }; if (keysize == 16) { memcpy(&bKey[0], key, 16); memcpy(&bKey[16], key, 8); } else { memcpy(&bKey[0], key, 24); } return openssl_dec(EVP_des_ede3_cbc(), bKey, iv, input, length, output); } static int des_encrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH], const unsigned char *input, size_t length, unsigned char *output) { return openssl_enc(EVP_des_cbc(), key, iv, input, length, output); } static int des_decrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH], const unsigned char *input, size_t length, unsigned char *output) { return openssl_dec(EVP_des_cbc(), key, iv, input, length, output); } static int openssl_dig(const EVP_MD * digest, const unsigned char *input, size_t length, unsigned char *output) { int r = 0; EVP_MD_CTX *ctx = NULL; unsigned outl = 0; ctx = EVP_MD_CTX_create(); if (ctx == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto err; } EVP_MD_CTX_init(ctx); EVP_DigestInit_ex(ctx, digest, NULL); if (!EVP_DigestUpdate(ctx, input, length)) { r = SC_ERROR_INTERNAL; goto err; } if (!EVP_DigestFinal_ex(ctx, output, &outl)) { r = SC_ERROR_INTERNAL; goto err; } r = SC_SUCCESS; err: if (ctx) EVP_MD_CTX_destroy(ctx); return r; } static int sha1_digest(const unsigned char *input, size_t length, unsigned char *output) { return openssl_dig(EVP_sha1(), input, length, output); } static int sha256_digest(const unsigned char *input, size_t length, unsigned char *output) { return openssl_dig(EVP_sha256(), input, length, output); } static int gen_init_key(struct sc_card *card, unsigned char *key_enc, unsigned char *key_mac, unsigned char *result, unsigned char key_type) { int r; struct sc_apdu apdu; unsigned char data[256] = { 0 }; unsigned char tmp_sm; unsigned long blocksize = 0; unsigned char cryptogram[256] = { 0 }; /* host cryptogram */ unsigned char iv[16] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x50, 0x00, 0x00); apdu.cla = 0x80; apdu.lc = apdu.datalen = sizeof(g_random); apdu.data = g_random; /* host random */ apdu.le = apdu.resplen = 28; apdu.resp = result; /* card random is result[12~19] */ tmp_sm = exdata->sm; exdata->sm = SM_PLAIN; r = epass2003_transmit_apdu(card, &apdu); exdata->sm = tmp_sm; LOG_TEST_RET(card->ctx, r, "APDU gen_init_key failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "gen_init_key failed"); /* Step 1 - Generate Derivation data */ memcpy(data, &result[16], 4); memcpy(&data[4], g_random, 4); memcpy(&data[8], &result[12], 4); memcpy(&data[12], &g_random[4], 4); /* Step 2,3 - Create S-ENC/S-MAC Session Key */ if (KEY_TYPE_AES == key_type) { aes128_encrypt_ecb(key_enc, 16, data, 16, exdata->sk_enc); aes128_encrypt_ecb(key_mac, 16, data, 16, exdata->sk_mac); } else { des3_encrypt_ecb(key_enc, 16, data, 16, exdata->sk_enc); des3_encrypt_ecb(key_mac, 16, data, 16, exdata->sk_mac); } memcpy(data, g_random, 8); memcpy(&data[8], &result[12], 8); data[16] = 0x80; blocksize = (key_type == KEY_TYPE_AES ? 16 : 8); memset(&data[17], 0x00, blocksize - 1); /* calculate host cryptogram */ if (KEY_TYPE_AES == key_type) aes128_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize, cryptogram); else des3_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize, cryptogram); /* verify card cryptogram */ if (0 != memcmp(&cryptogram[16], &result[20], 8)) LOG_FUNC_RETURN(card->ctx, SC_ERROR_CARD_CMD_FAILED); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int verify_init_key(struct sc_card *card, unsigned char *ran_key, unsigned char key_type) { int r; struct sc_apdu apdu; unsigned long blocksize = (key_type == KEY_TYPE_AES ? 16 : 8); unsigned char data[256] = { 0 }; unsigned char cryptogram[256] = { 0 }; /* host cryptogram */ unsigned char iv[16] = { 0 }; unsigned char mac[256] = { 0 }; unsigned long i; unsigned char tmp_sm; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); memcpy(data, ran_key, 8); memcpy(&data[8], g_random, 8); data[16] = 0x80; memset(&data[17], 0x00, blocksize - 1); memset(iv, 0, 16); /* calculate host cryptogram */ if (KEY_TYPE_AES == key_type) { aes128_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize, cryptogram); } else { des3_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize, cryptogram); } memset(data, 0, sizeof(data)); memcpy(data, "\x84\x82\x03\x00\x10", 5); memcpy(&data[5], &cryptogram[16], 8); memcpy(&data[13], "\x80\x00\x00", 3); /* calculate mac icv */ memset(iv, 0x00, 16); if (KEY_TYPE_AES == key_type) { aes128_encrypt_cbc(exdata->sk_mac, 16, iv, data, 16, mac); i = 0; } else { des3_encrypt_cbc(exdata->sk_mac, 16, iv, data, 16, mac); i = 8; } /* save mac icv */ memset(exdata->icv_mac, 0x00, 16); memcpy(exdata->icv_mac, &mac[i], 8); /* verify host cryptogram */ memcpy(data, &cryptogram[16], 8); memcpy(&data[8], &mac[i], 8); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x82, 0x03, 0x00); apdu.cla = 0x84; apdu.lc = apdu.datalen = 16; apdu.data = data; tmp_sm = exdata->sm; exdata->sm = SM_PLAIN; r = epass2003_transmit_apdu(card, &apdu); exdata->sm = tmp_sm; LOG_TEST_RET(card->ctx, r, "APDU verify_init_key failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "verify_init_key failed"); return r; } static int mutual_auth(struct sc_card *card, unsigned char *key_enc, unsigned char *key_mac) { struct sc_context *ctx = card->ctx; int r; unsigned char result[256] = { 0 }; unsigned char ran_key[8] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(ctx); r = gen_init_key(card, key_enc, key_mac, result, exdata->smtype); LOG_TEST_RET(ctx, r, "gen_init_key failed"); memcpy(ran_key, &result[12], 8); r = verify_init_key(card, ran_key, exdata->smtype); LOG_TEST_RET(ctx, r, "verify_init_key failed"); LOG_FUNC_RETURN(ctx, r); } int epass2003_refresh(struct sc_card *card) { int r = SC_SUCCESS; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; if (exdata->sm) { card->sm_ctx.sm_mode = 0; r = mutual_auth(card, g_init_key_enc, g_init_key_mac); card->sm_ctx.sm_mode = SM_MODE_TRANSMIT; LOG_TEST_RET(card->ctx, r, "mutual_auth failed"); } return r; } /* Data(TLV)=0x87|L|0x01+Cipher */ static int construct_data_tlv(struct sc_card *card, struct sc_apdu *apdu, unsigned char *apdu_buf, unsigned char *data_tlv, size_t * data_tlv_len, const unsigned char key_type) { size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8); unsigned char pad[4096] = { 0 }; size_t pad_len; size_t tlv_more; /* increased tlv length */ unsigned char iv[16] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; /* padding */ apdu_buf[block_size] = 0x87; memcpy(pad, apdu->data, apdu->lc); pad[apdu->lc] = 0x80; if ((apdu->lc + 1) % block_size) pad_len = ((apdu->lc + 1) / block_size + 1) * block_size; else pad_len = apdu->lc + 1; /* encode Lc' */ if (pad_len > 0x7E) { /* Lc' > 0x7E, use extended APDU */ apdu_buf[block_size + 1] = 0x82; apdu_buf[block_size + 2] = (unsigned char)((pad_len + 1) / 0x100); apdu_buf[block_size + 3] = (unsigned char)((pad_len + 1) % 0x100); apdu_buf[block_size + 4] = 0x01; tlv_more = 5; } else { apdu_buf[block_size + 1] = (unsigned char)pad_len + 1; apdu_buf[block_size + 2] = 0x01; tlv_more = 3; } memcpy(data_tlv, &apdu_buf[block_size], tlv_more); /* encrypt Data */ if (KEY_TYPE_AES == key_type) aes128_encrypt_cbc(exdata->sk_enc, 16, iv, pad, pad_len, apdu_buf + block_size + tlv_more); else des3_encrypt_cbc(exdata->sk_enc, 16, iv, pad, pad_len, apdu_buf + block_size + tlv_more); memcpy(data_tlv + tlv_more, apdu_buf + block_size + tlv_more, pad_len); *data_tlv_len = tlv_more + pad_len; return 0; } /* Le(TLV)=0x97|L|Le */ static int construct_le_tlv(struct sc_apdu *apdu, unsigned char *apdu_buf, size_t data_tlv_len, unsigned char *le_tlv, size_t * le_tlv_len, const unsigned char key_type) { size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8); *(apdu_buf + block_size + data_tlv_len) = 0x97; if (apdu->le > 0x7F) { /* Le' > 0x7E, use extended APDU */ *(apdu_buf + block_size + data_tlv_len + 1) = 2; *(apdu_buf + block_size + data_tlv_len + 2) = (unsigned char)(apdu->le / 0x100); *(apdu_buf + block_size + data_tlv_len + 3) = (unsigned char)(apdu->le % 0x100); memcpy(le_tlv, apdu_buf + block_size + data_tlv_len, 4); *le_tlv_len = 4; } else { *(apdu_buf + block_size + data_tlv_len + 1) = 1; *(apdu_buf + block_size + data_tlv_len + 2) = (unsigned char)apdu->le; memcpy(le_tlv, apdu_buf + block_size + data_tlv_len, 3); *le_tlv_len = 3; } return 0; } /* MAC(TLV)=0x8e|0x08|MAC */ static int construct_mac_tlv(struct sc_card *card, unsigned char *apdu_buf, size_t data_tlv_len, size_t le_tlv_len, unsigned char *mac_tlv, size_t * mac_tlv_len, const unsigned char key_type) { size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8); unsigned char mac[4096] = { 0 }; size_t mac_len; unsigned char icv[16] = { 0 }; int i = (KEY_TYPE_AES == key_type ? 15 : 7); epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; if (0 == data_tlv_len && 0 == le_tlv_len) { mac_len = block_size; } else { /* padding */ *(apdu_buf + block_size + data_tlv_len + le_tlv_len) = 0x80; if ((data_tlv_len + le_tlv_len + 1) % block_size) mac_len = (((data_tlv_len + le_tlv_len + 1) / block_size) + 1) * block_size + block_size; else mac_len = data_tlv_len + le_tlv_len + 1 + block_size; memset((apdu_buf + block_size + data_tlv_len + le_tlv_len + 1), 0, (mac_len - (data_tlv_len + le_tlv_len + 1))); } /* increase icv */ for (; i >= 0; i--) { if (exdata->icv_mac[i] == 0xff) { exdata->icv_mac[i] = 0; } else { exdata->icv_mac[i]++; break; } } /* calculate MAC */ memset(icv, 0, sizeof(icv)); memcpy(icv, exdata->icv_mac, 16); if (KEY_TYPE_AES == key_type) { aes128_encrypt_cbc(exdata->sk_mac, 16, icv, apdu_buf, mac_len, mac); memcpy(mac_tlv + 2, &mac[mac_len - 16], 8); } else { unsigned char iv[EVP_MAX_IV_LENGTH] = { 0 }; unsigned char tmp[8] = { 0 }; des_encrypt_cbc(exdata->sk_mac, 8, icv, apdu_buf, mac_len, mac); des_decrypt_cbc(&exdata->sk_mac[8], 8, iv, &mac[mac_len - 8], 8, tmp); memset(iv, 0x00, sizeof iv); des_encrypt_cbc(exdata->sk_mac, 8, iv, tmp, 8, mac_tlv + 2); } *mac_tlv_len = 2 + 8; return 0; } /* According to GlobalPlatform Card Specification's SCP01 * encode APDU from * CLA INS P1 P2 [Lc] Data [Le] * to * CLA INS P1 P2 Lc' Data' [Le] * where * Data'=Data(TLV)+Le(TLV)+MAC(TLV) */ static int encode_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu *sm, unsigned char *apdu_buf, size_t * apdu_buf_len) { size_t block_size = 0; unsigned char dataTLV[4096] = { 0 }; size_t data_tlv_len = 0; unsigned char le_tlv[256] = { 0 }; size_t le_tlv_len = 0; size_t mac_tlv_len = 10; size_t tmp_lc = 0; size_t tmp_le = 0; unsigned char mac_tlv[256] = { 0 }; epass2003_exdata *exdata = NULL; mac_tlv[0] = 0x8E; mac_tlv[1] = 8; /* size_t plain_le = 0; */ if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata*)card->drv_data; block_size = (KEY_TYPE_DES == exdata->smtype ? 16 : 8); sm->cse = SC_APDU_CASE_4_SHORT; apdu_buf[0] = (unsigned char)plain->cla; apdu_buf[1] = (unsigned char)plain->ins; apdu_buf[2] = (unsigned char)plain->p1; apdu_buf[3] = (unsigned char)plain->p2; /* plain_le = plain->le; */ /* padding */ apdu_buf[4] = 0x80; memset(&apdu_buf[5], 0x00, block_size - 5); /* Data -> Data' */ if (plain->lc != 0) if (0 != construct_data_tlv(card, plain, apdu_buf, dataTLV, &data_tlv_len, exdata->smtype)) return -1; if (plain->le != 0 || (plain->le == 0 && plain->resplen != 0)) if (0 != construct_le_tlv(plain, apdu_buf, data_tlv_len, le_tlv, &le_tlv_len, exdata->smtype)) return -1; if (0 != construct_mac_tlv(card, apdu_buf, data_tlv_len, le_tlv_len, mac_tlv, &mac_tlv_len, exdata->smtype)) return -1; memset(apdu_buf + 4, 0, *apdu_buf_len - 4); sm->lc = sm->datalen = data_tlv_len + le_tlv_len + mac_tlv_len; if (sm->lc > 0xFF) { sm->cse = SC_APDU_CASE_4_EXT; apdu_buf[4] = (unsigned char)((sm->lc) / 0x10000); apdu_buf[5] = (unsigned char)(((sm->lc) / 0x100) % 0x100); apdu_buf[6] = (unsigned char)((sm->lc) % 0x100); tmp_lc = 3; } else { apdu_buf[4] = (unsigned char)sm->lc; tmp_lc = 1; } memcpy(apdu_buf + 4 + tmp_lc, dataTLV, data_tlv_len); memcpy(apdu_buf + 4 + tmp_lc + data_tlv_len, le_tlv, le_tlv_len); memcpy(apdu_buf + 4 + tmp_lc + data_tlv_len + le_tlv_len, mac_tlv, mac_tlv_len); memcpy((unsigned char *)sm->data, apdu_buf + 4 + tmp_lc, sm->datalen); *apdu_buf_len = 0; if (4 == le_tlv_len) { sm->cse = SC_APDU_CASE_4_EXT; *(apdu_buf + 4 + tmp_lc + sm->lc) = (unsigned char)(plain->le / 0x100); *(apdu_buf + 4 + tmp_lc + sm->lc + 1) = (unsigned char)(plain->le % 0x100); tmp_le = 2; } else if (3 == le_tlv_len) { *(apdu_buf + 4 + tmp_lc + sm->lc) = (unsigned char)plain->le; tmp_le = 1; } *apdu_buf_len += 4 + tmp_lc + data_tlv_len + le_tlv_len + mac_tlv_len + tmp_le; /* sm->le = calc_le(plain_le); */ return 0; } static int epass2003_sm_wrap_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu *sm) { unsigned char buf[4096] = { 0 }; /* APDU buffer */ size_t buf_len = sizeof(buf); epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); if (exdata->sm) plain->cla |= 0x0C; sm->cse = plain->cse; sm->cla = plain->cla; sm->ins = plain->ins; sm->p1 = plain->p1; sm->p2 = plain->p2; sm->lc = plain->lc; sm->le = plain->le; sm->control = plain->control; sm->flags = plain->flags; switch (sm->cla & 0x0C) { case 0x00: case 0x04: sm->datalen = plain->datalen; memcpy((void *)sm->data, plain->data, plain->datalen); sm->resplen = plain->resplen; memcpy(sm->resp, plain->resp, plain->resplen); break; case 0x0C: memset(buf, 0, sizeof(buf)); if (0 != encode_apdu(card, plain, sm, buf, &buf_len)) return SC_ERROR_CARD_CMD_FAILED; break; default: return SC_ERROR_INCORRECT_PARAMETERS; } return SC_SUCCESS; } /* According to GlobalPlatform Card Specification's SCP01 * decrypt APDU response from * ResponseData' SW1 SW2 * to * ResponseData SW1 SW2 * where * ResponseData'=Data(TLV)+SW12(TLV)+MAC(TLV) * where * Data(TLV)=0x87|L|Cipher * SW12(TLV)=0x99|0x02|SW1+SW2 * MAC(TLV)=0x8e|0x08|MAC */ static int decrypt_response(struct sc_card *card, unsigned char *in, size_t inlen, unsigned char *out, size_t * out_len) { size_t cipher_len; size_t i; unsigned char iv[16] = { 0 }; unsigned char plaintext[4096] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; /* no cipher */ if (in[0] == 0x99) return 0; /* parse cipher length */ if (0x01 == in[2] && 0x82 != in[1]) { cipher_len = in[1]; i = 3; } else if (0x01 == in[3] && 0x81 == in[1]) { cipher_len = in[2]; i = 4; } else if (0x01 == in[4] && 0x82 == in[1]) { cipher_len = in[2] * 0x100; cipher_len += in[3]; i = 5; } else { return -1; } if (cipher_len < 2 || i+cipher_len > inlen || cipher_len > sizeof plaintext) return -1; /* decrypt */ if (KEY_TYPE_AES == exdata->smtype) aes128_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext); else des3_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext); /* unpadding */ while (0x80 != plaintext[cipher_len - 2] && (cipher_len - 2 > 0)) cipher_len--; if (2 == cipher_len || *out_len < cipher_len - 2) return -1; memcpy(out, plaintext, cipher_len - 2); *out_len = cipher_len - 2; return 0; } static int epass2003_sm_unwrap_apdu(struct sc_card *card, struct sc_apdu *sm, struct sc_apdu *plain) { int r; size_t len = 0; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); r = sc_check_sw(card, sm->sw1, sm->sw2); if (r == SC_SUCCESS) { if (exdata->sm) { len = plain->resplen; if (0 != decrypt_response(card, sm->resp, sm->resplen, plain->resp, &len)) return SC_ERROR_CARD_CMD_FAILED; } else { memcpy(plain->resp, sm->resp, sm->resplen); len = sm->resplen; } } plain->resplen = len; plain->sw1 = sm->sw1; plain->sw2 = sm->sw2; sc_log(card->ctx, "unwrapped APDU: resplen %"SC_FORMAT_LEN_SIZE_T"u, SW %02X%02X", plain->resplen, plain->sw1, plain->sw2); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_sm_free_wrapped_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu **sm_apdu) { struct sc_context *ctx = card->ctx; int rv = SC_SUCCESS; LOG_FUNC_CALLED(ctx); if (!sm_apdu) LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); if (!(*sm_apdu)) LOG_FUNC_RETURN(ctx, SC_SUCCESS); if (plain) rv = epass2003_sm_unwrap_apdu(card, *sm_apdu, plain); if ((*sm_apdu)->data) { unsigned char * p = (unsigned char *)((*sm_apdu)->data); free(p); } if ((*sm_apdu)->resp) { free((*sm_apdu)->resp); } free(*sm_apdu); *sm_apdu = NULL; LOG_FUNC_RETURN(ctx, rv); } static int epass2003_sm_get_wrapped_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu **sm_apdu) { struct sc_context *ctx = card->ctx; struct sc_apdu *apdu = NULL; int rv; LOG_FUNC_CALLED(ctx); if (!plain || !sm_apdu) LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); *sm_apdu = NULL; //construct new SM apdu from original apdu apdu = calloc(1, sizeof(struct sc_apdu)); if (!apdu) { rv = SC_ERROR_OUT_OF_MEMORY; goto err; } apdu->data = calloc (1, SC_MAX_EXT_APDU_BUFFER_SIZE); if (!apdu->data) { rv = SC_ERROR_OUT_OF_MEMORY; goto err; } apdu->resp = calloc (1, SC_MAX_EXT_APDU_BUFFER_SIZE); if (!apdu->resp) { rv = SC_ERROR_OUT_OF_MEMORY; goto err; } apdu->datalen = SC_MAX_EXT_APDU_BUFFER_SIZE; apdu->resplen = SC_MAX_EXT_APDU_BUFFER_SIZE; rv = epass2003_sm_wrap_apdu(card, plain, apdu); if (rv) { rv = epass2003_sm_free_wrapped_apdu(card, NULL, &apdu); if (rv < 0) goto err; } *sm_apdu = apdu; apdu = NULL; err: if (apdu) { free((unsigned char *) apdu->data); free(apdu->resp); free(apdu); apdu = NULL; } LOG_FUNC_RETURN(ctx, rv); } static int epass2003_transmit_apdu(struct sc_card *card, struct sc_apdu *apdu) { int r; LOG_FUNC_CALLED(card->ctx); r = sc_transmit_apdu_t(card, apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); return r; } static int get_data(struct sc_card *card, unsigned char type, unsigned char *data, size_t datalen) { int r; struct sc_apdu apdu; unsigned char resp[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; size_t resplen = SC_MAX_APDU_BUFFER_SIZE; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xca, 0x01, type); apdu.resp = resp; apdu.le = 0; apdu.resplen = resplen; if (0x86 == type) { /* No SM temporarily */ unsigned char tmp_sm = exdata->sm; exdata->sm = SM_PLAIN; r = sc_transmit_apdu(card, &apdu); exdata->sm = tmp_sm; } else { r = sc_transmit_apdu_t(card, &apdu); } LOG_TEST_RET(card->ctx, r, "APDU get_data failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "get_data failed"); memcpy(data, resp, datalen); return r; } /* card driver functions */ static int epass2003_match_card(struct sc_card *card) { int r; LOG_FUNC_CALLED(card->ctx); r = _sc_match_atr(card, epass2003_atrs, &card->type); if (r < 0) return 0; return 1; } static int epass2003_init(struct sc_card *card) { unsigned int flags; unsigned int ext_flags; unsigned char data[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; size_t datalen = SC_MAX_APDU_BUFFER_SIZE; epass2003_exdata *exdata = NULL; LOG_FUNC_CALLED(card->ctx); card->name = "epass2003"; card->cla = 0x00; exdata = (epass2003_exdata *)calloc(1, sizeof(epass2003_exdata)); if (!exdata) return SC_ERROR_OUT_OF_MEMORY; card->drv_data = exdata; exdata->sm = SM_SCP01; /* decide FIPS/Non-FIPS mode */ if (SC_SUCCESS != get_data(card, 0x86, data, datalen)) return SC_ERROR_INVALID_CARD; if (0x01 == data[2]) exdata->smtype = KEY_TYPE_AES; else exdata->smtype = KEY_TYPE_DES; if (0x84 == data[14]) { if (0x00 == data[16]) { exdata->sm = SM_PLAIN; } } /* mutual authentication */ card->max_recv_size = 0xD8; card->max_send_size = 0xE8; card->sm_ctx.ops.open = epass2003_refresh; card->sm_ctx.ops.get_sm_apdu = epass2003_sm_get_wrapped_apdu; card->sm_ctx.ops.free_sm_apdu = epass2003_sm_free_wrapped_apdu; /* FIXME (VT): rather then set/unset 'g_sm', better to implement filter for APDUs to be wrapped */ epass2003_refresh(card); card->sm_ctx.sm_mode = SM_MODE_TRANSMIT; flags = SC_ALGORITHM_ONBOARD_KEY_GEN | SC_ALGORITHM_RSA_RAW | SC_ALGORITHM_RSA_HASH_NONE; _sc_card_add_rsa_alg(card, 512, flags, 0); _sc_card_add_rsa_alg(card, 768, flags, 0); _sc_card_add_rsa_alg(card, 1024, flags, 0); _sc_card_add_rsa_alg(card, 2048, flags, 0); //set EC Alg Flags flags = SC_ALGORITHM_ONBOARD_KEY_GEN|SC_ALGORITHM_ECDSA_HASH_SHA1|SC_ALGORITHM_ECDSA_HASH_SHA256|SC_ALGORITHM_ECDSA_HASH_NONE|SC_ALGORITHM_ECDSA_RAW; ext_flags = 0; _sc_card_add_ec_alg(card, 256, flags, ext_flags, NULL); card->caps = SC_CARD_CAP_RNG | SC_CARD_CAP_APDU_EXT; LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_finish(sc_card_t *card) { epass2003_exdata *exdata = (epass2003_exdata *)card->drv_data; if (exdata) free(exdata); return SC_SUCCESS; } /* COS implement SFI as lower 5 bits of FID, and not allow same SFI at the * same DF, so use hook functions to increase/decrease FID by 0x20 */ static int epass2003_hook_path(struct sc_path *path, int inc) { u8 fid_h = path->value[path->len - 2]; u8 fid_l = path->value[path->len - 1]; switch (fid_h) { case 0x29: case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: if (inc) fid_l = fid_l * FID_STEP; else fid_l = fid_l / FID_STEP; path->value[path->len - 1] = fid_l; return 1; default: break; } return 0; } static void epass2003_hook_file(struct sc_file *file, int inc) { int fidl = file->id & 0xff; int fidh = file->id & 0xff00; if (epass2003_hook_path(&file->path, inc)) { if (inc) file->id = fidh + fidl * FID_STEP; else file->id = fidh + fidl / FID_STEP; } } static int epass2003_select_fid_(struct sc_card *card, sc_path_t * in_path, sc_file_t ** file_out) { struct sc_apdu apdu; u8 buf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; u8 pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf; int r, pathlen; sc_file_t *file = NULL; epass2003_hook_path(in_path, 1); memcpy(path, in_path->value, in_path->len); pathlen = in_path->len; sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0x00, 0x00); switch (in_path->type) { case SC_PATH_TYPE_FILE_ID: apdu.p1 = 0; if (pathlen != 2) return SC_ERROR_INVALID_ARGUMENTS; break; default: LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); } apdu.p2 = 0; /* first record, return FCI */ apdu.lc = pathlen; apdu.data = path; apdu.datalen = pathlen; if (file_out != NULL) { apdu.resp = buf; apdu.resplen = sizeof(buf); apdu.le = 0; } else { apdu.cse = (apdu.lc == 0) ? SC_APDU_CASE_1 : SC_APDU_CASE_3_SHORT; } if (path[0] == 0x29) { /* TODO:0x29 accords with FID prefix in profile */ /* Not allowed to select private key file, so fake fci. */ /* 62 16 82 02 11 00 83 02 29 00 85 02 08 00 86 08 FF 90 90 90 FF FF FF FF */ apdu.resplen = 0x18; memcpy(apdu.resp, "\x6f\x16\x82\x02\x11\x00\x83\x02\x29\x00\x85\x02\x08\x00\x86\x08\xff\x90\x90\x90\xff\xff\xff\xff", apdu.resplen); apdu.resp[9] = path[1]; apdu.sw1 = 0x90; apdu.sw2 = 0x00; } else { r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); } if (file_out == NULL) { if (apdu.sw1 == 0x61) LOG_FUNC_RETURN(card->ctx, 0); LOG_FUNC_RETURN(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2)); } r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r) LOG_FUNC_RETURN(card->ctx, r); if (apdu.resplen < 2) LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED); switch (apdu.resp[0]) { case 0x6F: file = sc_file_new(); if (file == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); file->path = *in_path; if (card->ops->process_fci == NULL) { sc_file_free(file); LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); } if ((size_t) apdu.resp[1] + 2 <= apdu.resplen) card->ops->process_fci(card, file, apdu.resp + 2, apdu.resp[1]); epass2003_hook_file(file, 0); *file_out = file; break; case 0x00: /* proprietary coding */ LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED); break; default: LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED); } return 0; } static int epass2003_select_fid(struct sc_card *card, unsigned int id_hi, unsigned int id_lo, sc_file_t ** file_out) { int r; sc_file_t *file = 0; sc_path_t path; memset(&path, 0, sizeof(path)); path.type = SC_PATH_TYPE_FILE_ID; path.value[0] = id_hi; path.value[1] = id_lo; path.len = 2; r = epass2003_select_fid_(card, &path, &file); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); /* update cache */ if (file && file->type == SC_FILE_TYPE_DF) { card->cache.current_path.type = SC_PATH_TYPE_PATH; card->cache.current_path.value[0] = 0x3f; card->cache.current_path.value[1] = 0x00; if (id_hi == 0x3f && id_lo == 0x00) { card->cache.current_path.len = 2; } else { card->cache.current_path.len = 4; card->cache.current_path.value[2] = id_hi; card->cache.current_path.value[3] = id_lo; } } if (file_out) *file_out = file; LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_select_aid(struct sc_card *card, const sc_path_t * in_path, sc_file_t ** file_out) { int r = 0; if (card->cache.valid && card->cache.current_path.type == SC_PATH_TYPE_DF_NAME && card->cache.current_path.len == in_path->len && memcmp(card->cache.current_path.value, in_path->value, in_path->len) == 0) { if (file_out) { *file_out = sc_file_new(); if (!file_out) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); } } else { r = iso_ops->select_file(card, in_path, file_out); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); /* update cache */ card->cache.current_path.type = SC_PATH_TYPE_DF_NAME; card->cache.current_path.len = in_path->len; memcpy(card->cache.current_path.value, in_path->value, in_path->len); } if (file_out) { sc_file_t *file = *file_out; file->type = SC_FILE_TYPE_DF; file->ef_structure = SC_FILE_EF_UNKNOWN; file->path.len = 0; file->size = 0; /* AID */ memcpy(file->name, in_path->value, in_path->len); file->namelen = in_path->len; file->id = 0x0000; } LOG_FUNC_RETURN(card->ctx, r); } static int epass2003_select_path(struct sc_card *card, const u8 pathbuf[16], const size_t len, sc_file_t ** file_out) { u8 n_pathbuf[SC_MAX_PATH_SIZE]; const u8 *path = pathbuf; size_t pathlen = len; int bMatch = -1; unsigned int i; int r; if (pathlen % 2 != 0 || pathlen > 6 || pathlen <= 0) LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); /* if pathlen == 6 then the first FID must be MF (== 3F00) */ if (pathlen == 6 && (path[0] != 0x3f || path[1] != 0x00)) LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); /* unify path (the first FID should be MF) */ if (path[0] != 0x3f || path[1] != 0x00) { n_pathbuf[0] = 0x3f; n_pathbuf[1] = 0x00; for (i = 0; i < pathlen; i++) n_pathbuf[i + 2] = pathbuf[i]; path = n_pathbuf; pathlen += 2; } /* check current working directory */ if (card->cache.valid && card->cache.current_path.type == SC_PATH_TYPE_PATH && card->cache.current_path.len >= 2 && card->cache.current_path.len <= pathlen) { bMatch = 0; for (i = 0; i < card->cache.current_path.len; i += 2) if (card->cache.current_path.value[i] == path[i] && card->cache.current_path.value[i + 1] == path[i + 1]) bMatch += 2; } if (card->cache.valid && bMatch > 2) { if (pathlen - bMatch == 2) { /* we are in the right directory */ return epass2003_select_fid(card, path[bMatch], path[bMatch + 1], file_out); } else if (pathlen - bMatch > 2) { /* two more steps to go */ sc_path_t new_path; /* first step: change directory */ r = epass2003_select_fid(card, path[bMatch], path[bMatch + 1], NULL); LOG_TEST_RET(card->ctx, r, "SELECT FILE (DF-ID) failed"); new_path.type = SC_PATH_TYPE_PATH; new_path.len = pathlen - bMatch - 2; memcpy(new_path.value, &(path[bMatch + 2]), new_path.len); /* final step: select file */ return epass2003_select_file(card, &new_path, file_out); } else { /* if (bMatch - pathlen == 0) */ /* done: we are already in the * requested directory */ sc_log(card->ctx, "cache hit\n"); /* copy file info (if necessary) */ if (file_out) { sc_file_t *file = sc_file_new(); if (!file) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); file->id = (path[pathlen - 2] << 8) + path[pathlen - 1]; file->path = card->cache.current_path; file->type = SC_FILE_TYPE_DF; file->ef_structure = SC_FILE_EF_UNKNOWN; file->size = 0; file->namelen = 0; file->magic = SC_FILE_MAGIC; *file_out = file; } /* nothing left to do */ return SC_SUCCESS; } } else { /* no usable cache */ for (i = 0; i < pathlen - 2; i += 2) { r = epass2003_select_fid(card, path[i], path[i + 1], NULL); LOG_TEST_RET(card->ctx, r, "SELECT FILE (DF-ID) failed"); } return epass2003_select_fid(card, path[pathlen - 2], path[pathlen - 1], file_out); } } static int epass2003_select_file(struct sc_card *card, const sc_path_t * in_path, sc_file_t ** file_out) { int r; char pbuf[SC_MAX_PATH_STRING_SIZE]; LOG_FUNC_CALLED(card->ctx); r = sc_path_print(pbuf, sizeof(pbuf), &card->cache.current_path); if (r != SC_SUCCESS) pbuf[0] = '\0'; sc_log(card->ctx, "current path (%s, %s): %s (len: %"SC_FORMAT_LEN_SIZE_T"u)\n", card->cache.current_path.type == SC_PATH_TYPE_DF_NAME ? "aid" : "path", card->cache.valid ? "valid" : "invalid", pbuf, card->cache.current_path.len); switch (in_path->type) { case SC_PATH_TYPE_FILE_ID: if (in_path->len != 2) LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); return epass2003_select_fid(card, in_path->value[0], in_path->value[1], file_out); case SC_PATH_TYPE_DF_NAME: return epass2003_select_aid(card, in_path, file_out); case SC_PATH_TYPE_PATH: return epass2003_select_path(card, in_path->value, in_path->len, file_out); default: LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); } } static int epass2003_set_security_env(struct sc_card *card, const sc_security_env_t * env, int se_num) { struct sc_apdu apdu; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; u8 *p; unsigned short fid = 0; int r, locked = 0; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x41, 0); p = sbuf; *p++ = 0x80; /* algorithm reference */ *p++ = 0x01; *p++ = 0x84; *p++ = 0x81; *p++ = 0x02; fid = 0x2900; fid += (unsigned short)(0x20 * (env->key_ref[0] & 0xff)); *p++ = fid >> 8; *p++ = fid & 0xff; r = p - sbuf; apdu.lc = r; apdu.datalen = r; apdu.data = sbuf; if (env->algorithm == SC_ALGORITHM_EC) { apdu.p2 = 0xB6; exdata->currAlg = SC_ALGORITHM_EC; if(env->algorithm_flags & SC_ALGORITHM_ECDSA_HASH_SHA1) { sbuf[2] = 0x91; exdata->ecAlgFlags = SC_ALGORITHM_ECDSA_HASH_SHA1; } else if (env->algorithm_flags & SC_ALGORITHM_ECDSA_HASH_SHA256) { sbuf[2] = 0x92; exdata->ecAlgFlags = SC_ALGORITHM_ECDSA_HASH_SHA256; } else { sc_log(card->ctx, "%0x Alg Not Support! ", env->algorithm_flags); goto err; } } else if(env->algorithm == SC_ALGORITHM_RSA) { exdata->currAlg = SC_ALGORITHM_RSA; apdu.p2 = 0xB8; sc_log(card->ctx, "setenv RSA Algorithm alg_flags = %0x\n",env->algorithm_flags); } else { sc_log(card->ctx, "%0x Alg Not Support! ", env->algorithm); } if (se_num > 0) { r = sc_lock(card); LOG_TEST_RET(card->ctx, r, "sc_lock() failed"); locked = 1; } if (apdu.datalen != 0) { r = sc_transmit_apdu_t(card, &apdu); if (r) { sc_log(card->ctx, "%s: APDU transmit failed", sc_strerror(r)); goto err; } r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r) { sc_log(card->ctx, "%s: Card returned error", sc_strerror(r)); goto err; } } if (se_num <= 0) return 0; sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0xF2, se_num); r = sc_transmit_apdu_t(card, &apdu); sc_unlock(card); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); return sc_check_sw(card, apdu.sw1, apdu.sw2); err: if (locked) sc_unlock(card); return r; } static int epass2003_restore_security_env(struct sc_card *card, int se_num) { LOG_FUNC_CALLED(card->ctx); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_decipher(struct sc_card *card, const u8 * data, size_t datalen, u8 * out, size_t outlen) { int r; struct sc_apdu apdu; u8 rbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; epass2003_exdata *exdata = NULL; LOG_FUNC_CALLED(card->ctx); if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; if(exdata->currAlg == SC_ALGORITHM_EC) { if(exdata->ecAlgFlags & SC_ALGORITHM_ECDSA_HASH_SHA1) { r = hash_data(data, datalen, sbuf, SC_ALGORITHM_ECDSA_HASH_SHA1); LOG_TEST_RET(card->ctx, r, "hash_data failed"); sc_format_apdu(card, &apdu, SC_APDU_CASE_3,0x2A, 0x9E, 0x9A); apdu.data = sbuf; apdu.lc = 0x14; apdu.datalen = 0x14; } else if (exdata->ecAlgFlags & SC_ALGORITHM_ECDSA_HASH_SHA256) { r = hash_data(data, datalen, sbuf, SC_ALGORITHM_ECDSA_HASH_SHA256); LOG_TEST_RET(card->ctx, r, "hash_data failed"); sc_format_apdu(card, &apdu, SC_APDU_CASE_3,0x2A, 0x9E, 0x9A); apdu.data = sbuf; apdu.lc = 0x20; apdu.datalen = 0x20; } else { return SC_ERROR_NOT_SUPPORTED; } apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 0; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); if (apdu.sw1 == 0x90 && apdu.sw2 == 0x00) { size_t len = apdu.resplen > outlen ? outlen : apdu.resplen; memcpy(out, apdu.resp, len); LOG_FUNC_RETURN(card->ctx, len); } LOG_FUNC_RETURN(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2)); } else if(exdata->currAlg == SC_ALGORITHM_RSA) { sc_format_apdu(card, &apdu, SC_APDU_CASE_4_EXT, 0x2A, 0x80, 0x86); apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 0; memcpy(sbuf, data, datalen); apdu.data = sbuf; apdu.lc = datalen; apdu.datalen = datalen; } else { sc_format_apdu(card, &apdu, SC_APDU_CASE_4_EXT, 0x2A, 0x80, 0x86); apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 256; memcpy(sbuf, data, datalen); apdu.data = sbuf; apdu.lc = datalen; apdu.datalen = datalen; } r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); if (apdu.sw1 == 0x90 && apdu.sw2 == 0x00) { size_t len = apdu.resplen > outlen ? outlen : apdu.resplen; memcpy(out, apdu.resp, len); LOG_FUNC_RETURN(card->ctx, len); } LOG_FUNC_RETURN(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2)); } static int acl_to_ac_byte(struct sc_card *card, const struct sc_acl_entry *e) { if (e == NULL) return SC_ERROR_OBJECT_NOT_FOUND; switch (e->method) { case SC_AC_NONE: LOG_FUNC_RETURN(card->ctx, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE); case SC_AC_NEVER: LOG_FUNC_RETURN(card->ctx, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_NOONE); default: LOG_FUNC_RETURN(card->ctx, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_USER); } LOG_FUNC_RETURN(card->ctx, SC_ERROR_INCORRECT_PARAMETERS); } static int epass2003_process_fci(struct sc_card *card, sc_file_t * file, const u8 * buf, size_t buflen) { sc_context_t *ctx = card->ctx; size_t taglen, len = buflen; const u8 *tag = NULL, *p = buf; sc_log(ctx, "processing FCI bytes"); tag = sc_asn1_find_tag(ctx, p, len, 0x83, &taglen); if (tag != NULL && taglen == 2) { file->id = (tag[0] << 8) | tag[1]; sc_log(ctx, " file identifier: 0x%02X%02X", tag[0], tag[1]); } tag = sc_asn1_find_tag(ctx, p, len, 0x80, &taglen); if (tag != NULL && taglen > 0 && taglen < 3) { file->size = tag[0]; if (taglen == 2) file->size = (file->size << 8) + tag[1]; sc_log(ctx, " bytes in file: %"SC_FORMAT_LEN_SIZE_T"u", file->size); } if (tag == NULL) { tag = sc_asn1_find_tag(ctx, p, len, 0x81, &taglen); if (tag != NULL && taglen >= 2) { int bytes = (tag[0] << 8) + tag[1]; sc_log(ctx, " bytes in file: %d", bytes); file->size = bytes; } } tag = sc_asn1_find_tag(ctx, p, len, 0x82, &taglen); if (tag != NULL) { if (taglen > 0) { unsigned char byte = tag[0]; const char *type; if (byte == 0x38) { type = "DF"; file->type = SC_FILE_TYPE_DF; } else if (0x01 <= byte && byte <= 0x07) { type = "working EF"; file->type = SC_FILE_TYPE_WORKING_EF; switch (byte) { case 0x01: file->ef_structure = SC_FILE_EF_TRANSPARENT; break; case 0x02: file->ef_structure = SC_FILE_EF_LINEAR_FIXED; break; case 0x04: file->ef_structure = SC_FILE_EF_LINEAR_FIXED; break; case 0x03: case 0x05: case 0x06: case 0x07: break; default: break; } } else if (0x10 == byte) { type = "BSO"; file->type = SC_FILE_TYPE_BSO; } else if (0x11 <= byte) { type = "internal EF"; file->type = SC_FILE_TYPE_INTERNAL_EF; switch (byte) { case 0x11: break; case 0x12: break; default: break; } } else { type = "unknown"; file->type = SC_FILE_TYPE_INTERNAL_EF; } sc_log(ctx, "type %s, EF structure %d", type, byte); } } tag = sc_asn1_find_tag(ctx, p, len, 0x84, &taglen); if (tag != NULL && taglen > 0 && taglen <= 16) { memcpy(file->name, tag, taglen); file->namelen = taglen; sc_log_hex(ctx, "File name", file->name, file->namelen); if (!file->type) file->type = SC_FILE_TYPE_DF; } tag = sc_asn1_find_tag(ctx, p, len, 0x85, &taglen); if (tag != NULL && taglen) sc_file_set_prop_attr(file, tag, taglen); else file->prop_attr_len = 0; tag = sc_asn1_find_tag(ctx, p, len, 0xA5, &taglen); if (tag != NULL && taglen) sc_file_set_prop_attr(file, tag, taglen); tag = sc_asn1_find_tag(ctx, p, len, 0x86, &taglen); if (tag != NULL && taglen) sc_file_set_sec_attr(file, tag, taglen); tag = sc_asn1_find_tag(ctx, p, len, 0x8A, &taglen); if (tag != NULL && taglen == 1) { if (tag[0] == 0x01) file->status = SC_FILE_STATUS_CREATION; else if (tag[0] == 0x07 || tag[0] == 0x05) file->status = SC_FILE_STATUS_ACTIVATED; else if (tag[0] == 0x06 || tag[0] == 0x04) file->status = SC_FILE_STATUS_INVALIDATED; } file->magic = SC_FILE_MAGIC; return 0; } static int epass2003_construct_fci(struct sc_card *card, const sc_file_t * file, u8 * out, size_t * outlen) { u8 *p = out; u8 buf[64]; unsigned char ops[8] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; int rv; unsigned ii; if (*outlen < 2) return SC_ERROR_BUFFER_TOO_SMALL; *p++ = 0x62; p++; if (file->type == SC_FILE_TYPE_WORKING_EF) { if (file->ef_structure == SC_FILE_EF_TRANSPARENT) { buf[0] = (file->size >> 8) & 0xFF; buf[1] = file->size & 0xFF; sc_asn1_put_tag(0x80, buf, 2, p, *outlen - (p - out), &p); } } if (file->type == SC_FILE_TYPE_DF) { buf[0] = 0x38; buf[1] = 0x00; sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p); } else if (file->type == SC_FILE_TYPE_WORKING_EF) { buf[0] = file->ef_structure & 7; if (file->ef_structure == SC_FILE_EF_TRANSPARENT) { buf[1] = 0x00; sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p); } else if (file->ef_structure == SC_FILE_EF_LINEAR_FIXED || file->ef_structure == SC_FILE_EF_LINEAR_VARIABLE) { buf[1] = 0x00; buf[2] = 0x00; buf[3] = 0x40; /* record length */ buf[4] = 0x00; /* record count */ sc_asn1_put_tag(0x82, buf, 5, p, *outlen - (p - out), &p); } else { return SC_ERROR_NOT_SUPPORTED; } } else if (file->type == SC_FILE_TYPE_INTERNAL_EF) { if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_CRT || file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_CRT) { buf[0] = 0x11; buf[1] = 0x00; } else if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC || file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) { buf[0] = 0x12; buf[1] = 0x00; } else { return SC_ERROR_NOT_SUPPORTED; } sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p); } else if (file->type == SC_FILE_TYPE_BSO) { buf[0] = 0x10; buf[1] = 0x00; sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p); } buf[0] = (file->id >> 8) & 0xFF; buf[1] = file->id & 0xFF; sc_asn1_put_tag(0x83, buf, 2, p, *outlen - (p - out), &p); if (file->type == SC_FILE_TYPE_DF) { if (file->namelen != 0) { sc_asn1_put_tag(0x84, file->name, file->namelen, p, *outlen - (p - out), &p); } else { return SC_ERROR_INVALID_ARGUMENTS; } } if (file->type == SC_FILE_TYPE_DF) { unsigned char data[2] = {0x00, 0x7F}; /* 127 files at most */ sc_asn1_put_tag(0x85, data, sizeof(data), p, *outlen - (p - out), &p); } else if (file->type == SC_FILE_TYPE_BSO) { buf[0] = file->size & 0xff; sc_asn1_put_tag(0x85, buf, 1, p, *outlen - (p - out), &p); } else if (file->type == SC_FILE_TYPE_INTERNAL_EF) { if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_CRT || file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC|| file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_CRT|| file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) { buf[0] = (file->size >> 8) & 0xFF; buf[1] = file->size & 0xFF; sc_asn1_put_tag(0x85, buf, 2, p, *outlen - (p - out), &p); } } if (file->sec_attr_len) { memcpy(buf, file->sec_attr, file->sec_attr_len); sc_asn1_put_tag(0x86, buf, file->sec_attr_len, p, *outlen - (p - out), &p); } else { sc_log(card->ctx, "SC_FILE_ACL"); if (file->type == SC_FILE_TYPE_DF) { ops[0] = SC_AC_OP_LIST_FILES; ops[1] = SC_AC_OP_CREATE; ops[3] = SC_AC_OP_DELETE; } else if (file->type == SC_FILE_TYPE_WORKING_EF) { if (file->ef_structure == SC_FILE_EF_TRANSPARENT) { ops[0] = SC_AC_OP_READ; ops[1] = SC_AC_OP_UPDATE; ops[3] = SC_AC_OP_DELETE; } else if (file->ef_structure == SC_FILE_EF_LINEAR_FIXED || file->ef_structure == SC_FILE_EF_LINEAR_VARIABLE) { ops[0] = SC_AC_OP_READ; ops[1] = SC_AC_OP_UPDATE; ops[2] = SC_AC_OP_WRITE; ops[3] = SC_AC_OP_DELETE; } else { return SC_ERROR_NOT_SUPPORTED; } } else if (file->type == SC_FILE_TYPE_BSO) { ops[0] = SC_AC_OP_UPDATE; ops[3] = SC_AC_OP_DELETE; } else if (file->type == SC_FILE_TYPE_INTERNAL_EF) { if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_CRT || file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_CRT) { ops[1] = SC_AC_OP_UPDATE; ops[2] = SC_AC_OP_CRYPTO; ops[3] = SC_AC_OP_DELETE; } else if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC|| file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) { ops[0] = SC_AC_OP_READ; ops[1] = SC_AC_OP_UPDATE; ops[2] = SC_AC_OP_CRYPTO; ops[3] = SC_AC_OP_DELETE; } } else { return SC_ERROR_NOT_SUPPORTED; } for (ii = 0; ii < sizeof(ops); ii++) { const struct sc_acl_entry *entry; buf[ii] = 0xFF; if (ops[ii] == 0xFF) continue; entry = sc_file_get_acl_entry(file, ops[ii]); rv = acl_to_ac_byte(card, entry); LOG_TEST_RET(card->ctx, rv, "Invalid ACL"); buf[ii] = rv; } sc_asn1_put_tag(0x86, buf, sizeof(ops), p, *outlen - (p - out), &p); if(file->size == 256) { out[4]= 0x13; } } /* VT ??? */ if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC|| file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) { unsigned char data[2] = {0x00, 0x66}; sc_asn1_put_tag(0x87, data, sizeof(data), p, *outlen - (p - out), &p); if(file->size == 256) { out[4]= 0x14; } } out[1] = p - out - 2; *outlen = p - out; return 0; } static int epass2003_create_file(struct sc_card *card, sc_file_t * file) { int r; size_t len; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; struct sc_apdu apdu; len = SC_MAX_APDU_BUFFER_SIZE; epass2003_hook_file(file, 1); if (card->ops->construct_fci == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); r = epass2003_construct_fci(card, file, sbuf, &len); LOG_TEST_RET(card->ctx, r, "construct_fci() failed"); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE0, 0x00, 0x00); apdu.lc = len; apdu.datalen = len; apdu.data = sbuf; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "APDU sw1/2 wrong"); epass2003_hook_file(file, 0); return r; } static int epass2003_delete_file(struct sc_card *card, const sc_path_t * path) { int r; u8 sbuf[2]; struct sc_apdu apdu; LOG_FUNC_CALLED(card->ctx); r = sc_select_file(card, path, NULL); epass2003_hook_path((struct sc_path *)path, 1); if (r == SC_SUCCESS) { sbuf[0] = path->value[path->len - 2]; sbuf[1] = path->value[path->len - 1]; sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE4, 0x00, 0x00); apdu.lc = 2; apdu.datalen = 2; apdu.data = sbuf; } else { LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); } r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "Delete file failed"); LOG_FUNC_RETURN(card->ctx, r); } static int epass2003_list_files(struct sc_card *card, unsigned char *buf, size_t buflen) { struct sc_apdu apdu; unsigned char rbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x34, 0x00, 0x00); apdu.cla = 0x80; apdu.le = 0; apdu.resplen = sizeof(rbuf); apdu.resp = rbuf; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "Card returned error"); if (apdu.resplen == 0x100 && rbuf[0] == 0 && rbuf[1] == 0) LOG_FUNC_RETURN(card->ctx, 0); buflen = buflen < apdu.resplen ? buflen : apdu.resplen; memcpy(buf, rbuf, buflen); LOG_FUNC_RETURN(card->ctx, buflen); } static int internal_write_rsa_key_factor(struct sc_card *card, unsigned short fid, u8 factor, sc_pkcs15_bignum_t data) { int r; struct sc_apdu apdu; u8 sbuff[SC_MAX_EXT_APDU_BUFFER_SIZE] = { 0 }; LOG_FUNC_CALLED(card->ctx); sbuff[0] = ((fid & 0xff00) >> 8); sbuff[1] = (fid & 0x00ff); memcpy(&sbuff[2], data.data, data.len); // sc_mem_reverse(&sbuff[2], data.len); sc_format_apdu(card, &apdu, SC_APDU_CASE_3, 0xe7, factor, 0x00); apdu.cla = 0x80; apdu.lc = apdu.datalen = 2 + data.len; apdu.data = sbuff; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "Write rsa key factor failed"); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int internal_write_rsa_key(struct sc_card *card, unsigned short fid, struct sc_pkcs15_prkey_rsa *rsa) { int r; LOG_FUNC_CALLED(card->ctx); r = internal_write_rsa_key_factor(card, fid, 0x02, rsa->modulus); LOG_TEST_RET(card->ctx, r, "write n failed"); r = internal_write_rsa_key_factor(card, fid, 0x03, rsa->d); LOG_TEST_RET(card->ctx, r, "write d failed"); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int hash_data(const unsigned char *data, size_t datalen, unsigned char *hash, unsigned int mechanismType) { if ((NULL == data) || (NULL == hash)) return SC_ERROR_INVALID_ARGUMENTS; if(mechanismType & SC_ALGORITHM_ECDSA_HASH_SHA1) { unsigned char data_hash[24] = { 0 }; size_t len = 0; sha1_digest(data, datalen, data_hash); len = REVERSE_ORDER4(datalen); memcpy(&data_hash[20], &len, 4); memcpy(hash, data_hash, 24); } else if(mechanismType & SC_ALGORITHM_ECDSA_HASH_SHA256) { unsigned char data_hash[36] = { 0 }; size_t len = 0; sha256_digest(data, datalen, data_hash); len = REVERSE_ORDER4(datalen); memcpy(&data_hash[32], &len, 4); memcpy(hash, data_hash, 36); } else { return SC_ERROR_NOT_SUPPORTED; } return SC_SUCCESS; } static int install_secret_key(struct sc_card *card, unsigned char ktype, unsigned char kid, unsigned char useac, unsigned char modifyac, unsigned char EC, unsigned char *data, unsigned long dataLen) { int r; struct sc_apdu apdu; unsigned char isapp = 0x00; /* appendable */ unsigned char tmp_data[256] = { 0 }; tmp_data[0] = ktype; tmp_data[1] = kid; tmp_data[2] = useac; tmp_data[3] = modifyac; tmp_data[8] = 0xFF; if (0x04 == ktype || 0x06 == ktype) { tmp_data[4] = EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_SO; tmp_data[5] = EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_SO; tmp_data[7] = (kid == PIN_ID[0] ? EPASS2003_AC_USER : EPASS2003_AC_SO); tmp_data[9] = (EC << 4) | EC; } memcpy(&tmp_data[10], data, dataLen); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xe3, isapp, 0x00); apdu.cla = 0x80; apdu.lc = apdu.datalen = 10 + dataLen; apdu.data = tmp_data; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU install_secret_key failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "install_secret_key failed"); return r; } static int internal_install_pre(struct sc_card *card) { int r; /* init key for enc */ r = install_secret_key(card, 0x01, 0x00, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE, 0, g_init_key_enc, 16); LOG_TEST_RET(card->ctx, r, "Install init key failed"); /* init key for mac */ r = install_secret_key(card, 0x02, 0x00, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE, 0, g_init_key_mac, 16); LOG_TEST_RET(card->ctx, r, "Install init key failed"); return r; } /* use external auth secret as pin */ static int internal_install_pin(struct sc_card *card, sc_epass2003_wkey_data * pin) { int r; unsigned char hash[HASH_LEN] = { 0 }; r = hash_data(pin->key_data.es_secret.key_val, pin->key_data.es_secret.key_len, hash, SC_ALGORITHM_ECDSA_HASH_SHA1); LOG_TEST_RET(card->ctx, r, "hash data failed"); r = install_secret_key(card, 0x04, pin->key_data.es_secret.kid, pin->key_data.es_secret.ac[0], pin->key_data.es_secret.ac[1], pin->key_data.es_secret.EC, hash, HASH_LEN); LOG_TEST_RET(card->ctx, r, "Install failed"); return r; } static int epass2003_write_key(struct sc_card *card, sc_epass2003_wkey_data * data) { LOG_FUNC_CALLED(card->ctx); if (data->type & SC_EPASS2003_KEY) { if (data->type == SC_EPASS2003_KEY_RSA) return internal_write_rsa_key(card, data->key_data.es_key.fid, data->key_data.es_key.rsa); else LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); } else if (data->type & SC_EPASS2003_SECRET) { if (data->type == SC_EPASS2003_SECRET_PRE) return internal_install_pre(card); else if (data->type == SC_EPASS2003_SECRET_PIN) return internal_install_pin(card, data); else LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); } else { LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); } LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_gen_key(struct sc_card *card, sc_epass2003_gen_key_data * data) { int r; size_t len = data->key_length; struct sc_apdu apdu; u8 rbuf[SC_MAX_EXT_APDU_BUFFER_SIZE] = { 0 }; u8 sbuf[SC_MAX_EXT_APDU_BUFFER_SIZE] = { 0 }; LOG_FUNC_CALLED(card->ctx); if(len == 256) { sbuf[0] = 0x02; } else { sbuf[0] = 0x01; } sbuf[1] = (u8) ((len >> 8) & 0xff); sbuf[2] = (u8) (len & 0xff); sbuf[3] = (u8) ((data->prkey_id >> 8) & 0xFF); sbuf[4] = (u8) ((data->prkey_id) & 0xFF); sbuf[5] = (u8) ((data->pukey_id >> 8) & 0xFF); sbuf[6] = (u8) ((data->pukey_id) & 0xFF); /* generate key */ sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x46, 0x00, 0x00); apdu.lc = apdu.datalen = 7; apdu.data = sbuf; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "generate keypair failed"); /* read public key */ sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xb4, 0x02, 0x00); if(len == 256) { apdu.p1 = 0x00; } apdu.cla = 0x80; apdu.lc = apdu.datalen = 2; apdu.data = &sbuf[5]; apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 0x00; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "get pukey failed"); if (len < apdu.resplen) LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); data->modulus = (u8 *) malloc(len); if (!data->modulus) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); memcpy(data->modulus, rbuf, len); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_erase_card(struct sc_card *card) { int r; LOG_FUNC_CALLED(card->ctx); sc_invalidate_cache(card); r = sc_delete_file(card, sc_get_mf_path()); LOG_TEST_RET(card->ctx, r, "delete MF failed"); LOG_FUNC_RETURN(card->ctx, r); } static int epass2003_get_serialnr(struct sc_card *card, sc_serial_number_t * serial) { u8 rbuf[8]; size_t rbuf_len = sizeof(rbuf); LOG_FUNC_CALLED(card->ctx); if (SC_SUCCESS != get_data(card, 0x80, rbuf, rbuf_len)) return SC_ERROR_CARD_CMD_FAILED; card->serialnr.len = serial->len = 8; memcpy(card->serialnr.value, rbuf, 8); memcpy(serial->value, rbuf, 8); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_card_ctl(struct sc_card *card, unsigned long cmd, void *ptr) { LOG_FUNC_CALLED(card->ctx); sc_log(card->ctx, "cmd is %0lx", cmd); switch (cmd) { case SC_CARDCTL_ENTERSAFE_WRITE_KEY: return epass2003_write_key(card, (sc_epass2003_wkey_data *) ptr); case SC_CARDCTL_ENTERSAFE_GENERATE_KEY: return epass2003_gen_key(card, (sc_epass2003_gen_key_data *) ptr); case SC_CARDCTL_ERASE_CARD: return epass2003_erase_card(card); case SC_CARDCTL_GET_SERIALNR: return epass2003_get_serialnr(card, (sc_serial_number_t *) ptr); default: return SC_ERROR_NOT_SUPPORTED; } } static void internal_sanitize_pin_info(struct sc_pin_cmd_pin *pin, unsigned int num) { pin->encoding = SC_PIN_ENCODING_ASCII; pin->min_length = 4; pin->max_length = 16; pin->pad_length = 16; pin->offset = 5 + num * 16; pin->pad_char = 0x00; } static int get_external_key_maxtries(struct sc_card *card, unsigned char *maxtries) { unsigned char maxcounter[2] = { 0 }; static const sc_path_t file_path = { {0x3f, 0x00, 0x50, 0x15, 0x9f, 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 6, 0, 0, SC_PATH_TYPE_PATH, {{0}, 0} }; int ret; ret = sc_select_file(card, &file_path, NULL); LOG_TEST_RET(card->ctx, ret, "select max counter file failed"); ret = sc_read_binary(card, 0, maxcounter, 2, 0); LOG_TEST_RET(card->ctx, ret, "read max counter file failed"); *maxtries = maxcounter[0]; return SC_SUCCESS; } static int get_external_key_retries(struct sc_card *card, unsigned char kid, unsigned char *retries) { int r; struct sc_apdu apdu; unsigned char random[16] = { 0 }; r = sc_get_challenge(card, random, 8); LOG_TEST_RET(card->ctx, r, "get challenge get_external_key_retries failed"); sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x82, 0x01, 0x80 | kid); apdu.resp = NULL; apdu.resplen = 0; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU get_external_key_retries failed"); if (retries && ((0x63 == (apdu.sw1 & 0xff)) && (0xC0 == (apdu.sw2 & 0xf0)))) { *retries = (apdu.sw2 & 0x0f); r = SC_SUCCESS; } else { LOG_TEST_RET(card->ctx, r, "get_external_key_retries failed"); r = SC_ERROR_CARD_CMD_FAILED; } return r; } static int epass2003_get_challenge(sc_card_t *card, u8 *rnd, size_t len) { u8 rbuf[16]; size_t out_len; int r; LOG_FUNC_CALLED(card->ctx); r = iso_ops->get_challenge(card, rbuf, sizeof rbuf); LOG_TEST_RET(card->ctx, r, "GET CHALLENGE cmd failed"); if (len < (size_t) r) { out_len = len; } else { out_len = (size_t) r; } memcpy(rnd, rbuf, out_len); LOG_FUNC_RETURN(card->ctx, (int) out_len); } static int external_key_auth(struct sc_card *card, unsigned char kid, unsigned char *data, size_t datalen) { int r; struct sc_apdu apdu; unsigned char random[16] = { 0 }; unsigned char tmp_data[16] = { 0 }; unsigned char hash[HASH_LEN] = { 0 }; unsigned char iv[16] = { 0 }; r = sc_get_challenge(card, random, 8); LOG_TEST_RET(card->ctx, r, "get challenge external_key_auth failed"); r = hash_data(data, datalen, hash, SC_ALGORITHM_ECDSA_HASH_SHA1); LOG_TEST_RET(card->ctx, r, "hash data failed"); des3_encrypt_cbc(hash, HASH_LEN, iv, random, 8, tmp_data); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x82, 0x01, 0x80 | kid); apdu.lc = apdu.datalen = 8; apdu.data = tmp_data; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU external_key_auth failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "external_key_auth failed"); return r; } static int update_secret_key(struct sc_card *card, unsigned char ktype, unsigned char kid, const unsigned char *data, unsigned long datalen) { int r; struct sc_apdu apdu; unsigned char hash[HASH_LEN] = { 0 }; unsigned char tmp_data[256] = { 0 }; unsigned char maxtries = 0; r = hash_data(data, datalen, hash, SC_ALGORITHM_ECDSA_HASH_SHA1); LOG_TEST_RET(card->ctx, r, "hash data failed"); r = get_external_key_maxtries(card, &maxtries); LOG_TEST_RET(card->ctx, r, "get max counter failed"); tmp_data[0] = (maxtries << 4) | maxtries; memcpy(&tmp_data[1], hash, HASH_LEN); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xe5, ktype, kid); apdu.cla = 0x80; apdu.lc = apdu.datalen = 1 + HASH_LEN; apdu.data = tmp_data; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU update_secret_key failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "update_secret_key failed"); return r; } /* use external auth secret as pin */ static int epass2003_pin_cmd(struct sc_card *card, struct sc_pin_cmd_data *data, int *tries_left) { int r; u8 kid; u8 retries = 0; u8 pin_low = 3; unsigned char maxtries = 0; LOG_FUNC_CALLED(card->ctx); internal_sanitize_pin_info(&data->pin1, 0); internal_sanitize_pin_info(&data->pin2, 1); data->flags |= SC_PIN_CMD_NEED_PADDING; kid = data->pin_reference; /* get pin retries */ if (data->cmd == SC_PIN_CMD_GET_INFO) { r = get_external_key_retries(card, 0x80 | kid, &retries); if (r == SC_SUCCESS) { data->pin1.tries_left = retries; if (tries_left) *tries_left = retries; r = get_external_key_maxtries(card, &maxtries); LOG_TEST_RET(card->ctx, r, "get max counter failed"); data->pin1.max_tries = maxtries; } //remove below code, because the old implement only return PIN retries, now modify the code and return PIN status // return r; } else if (data->cmd == SC_PIN_CMD_UNBLOCK) { /* verify */ r = external_key_auth(card, (kid + 1), (unsigned char *)data->pin1.data, data->pin1.len); LOG_TEST_RET(card->ctx, r, "verify pin failed"); } else if (data->cmd == SC_PIN_CMD_CHANGE || data->cmd == SC_PIN_CMD_UNBLOCK) { /* change */ r = update_secret_key(card, 0x04, kid, data->pin2.data, (unsigned long)data->pin2.len); LOG_TEST_RET(card->ctx, r, "verify pin failed"); } else { r = external_key_auth(card, kid, (unsigned char *)data->pin1.data, data->pin1.len); get_external_key_retries(card, 0x80 | kid, &retries); if (retries < pin_low) sc_log(card->ctx, "Verification failed (remaining tries: %d)", retries); } LOG_TEST_RET(card->ctx, r, "verify pin failed"); if (r == SC_SUCCESS) { data->pin1.logged_in = SC_PIN_STATE_LOGGED_IN; } return r; } static struct sc_card_driver *sc_get_driver(void) { struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); if (iso_ops == NULL) iso_ops = iso_drv->ops; epass2003_ops = *iso_ops; epass2003_ops.match_card = epass2003_match_card; epass2003_ops.init = epass2003_init; epass2003_ops.finish = epass2003_finish; epass2003_ops.write_binary = NULL; epass2003_ops.write_record = NULL; epass2003_ops.select_file = epass2003_select_file; epass2003_ops.get_response = NULL; epass2003_ops.restore_security_env = epass2003_restore_security_env; epass2003_ops.set_security_env = epass2003_set_security_env; epass2003_ops.decipher = epass2003_decipher; epass2003_ops.compute_signature = epass2003_decipher; epass2003_ops.create_file = epass2003_create_file; epass2003_ops.delete_file = epass2003_delete_file; epass2003_ops.list_files = epass2003_list_files; epass2003_ops.card_ctl = epass2003_card_ctl; epass2003_ops.process_fci = epass2003_process_fci; epass2003_ops.construct_fci = epass2003_construct_fci; epass2003_ops.pin_cmd = epass2003_pin_cmd; epass2003_ops.check_sw = epass2003_check_sw; epass2003_ops.get_challenge = epass2003_get_challenge; return &epass2003_drv; } struct sc_card_driver *sc_get_epass2003_driver(void) { return sc_get_driver(); } #endif /* #ifdef ENABLE_OPENSSL */ #endif /* #ifdef ENABLE_SM */
./CrossVul/dataset_final_sorted/CWE-119/c/good_341_1
crossvul-cpp_data_bad_339_10
/* * util.c: utility functions used by OpenSC command line tools. * * Copyright (C) 2011 OpenSC Project developers * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "config.h" #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #ifndef _WIN32 #include <termios.h> #else #include <conio.h> #endif #include <ctype.h> #include "util.h" #include "ui/notify.h" int is_string_valid_atr(const char *atr_str) { unsigned char atr[SC_MAX_ATR_SIZE]; size_t atr_len = sizeof(atr); if (sc_hex_to_bin(atr_str, atr, &atr_len)) return 0; if (atr_len < 2) return 0; if (atr[0] != 0x3B && atr[0] != 0x3F) return 0; return 1; } int util_connect_card_ex(sc_context_t *ctx, sc_card_t **cardp, const char *reader_id, int do_wait, int do_lock, int verbose) { struct sc_reader *reader = NULL, *found = NULL; struct sc_card *card = NULL; int r; sc_notify_init(); if (do_wait) { unsigned int event; if (sc_ctx_get_reader_count(ctx) == 0) { fprintf(stderr, "Waiting for a reader to be attached...\n"); r = sc_wait_for_event(ctx, SC_EVENT_READER_ATTACHED, &found, &event, -1, NULL); if (r < 0) { fprintf(stderr, "Error while waiting for a reader: %s\n", sc_strerror(r)); return 3; } r = sc_ctx_detect_readers(ctx); if (r < 0) { fprintf(stderr, "Error while refreshing readers: %s\n", sc_strerror(r)); return 3; } } fprintf(stderr, "Waiting for a card to be inserted...\n"); r = sc_wait_for_event(ctx, SC_EVENT_CARD_INSERTED, &found, &event, -1, NULL); if (r < 0) { fprintf(stderr, "Error while waiting for a card: %s\n", sc_strerror(r)); return 3; } reader = found; } else if (sc_ctx_get_reader_count(ctx) == 0) { fprintf(stderr, "No smart card readers found.\n"); return 1; } else { if (!reader_id) { unsigned int i; /* Automatically try to skip to a reader with a card if reader not specified */ for (i = 0; i < sc_ctx_get_reader_count(ctx); i++) { reader = sc_ctx_get_reader(ctx, i); if (sc_detect_card_presence(reader) & SC_READER_CARD_PRESENT) { fprintf(stderr, "Using reader with a card: %s\n", reader->name); goto autofound; } } /* If no reader had a card, default to the first reader */ reader = sc_ctx_get_reader(ctx, 0); } else { /* If the reader identifier looks like an ATR, try to find the reader with that card */ if (is_string_valid_atr(reader_id)) { unsigned char atr_buf[SC_MAX_ATR_SIZE]; size_t atr_buf_len = sizeof(atr_buf); unsigned int i; sc_hex_to_bin(reader_id, atr_buf, &atr_buf_len); /* Loop readers, looking for a card with ATR */ for (i = 0; i < sc_ctx_get_reader_count(ctx); i++) { struct sc_reader *rdr = sc_ctx_get_reader(ctx, i); if (!(sc_detect_card_presence(rdr) & SC_READER_CARD_PRESENT)) continue; else if (rdr->atr.len != atr_buf_len) continue; else if (memcmp(rdr->atr.value, atr_buf, rdr->atr.len)) continue; fprintf(stderr, "Matched ATR in reader: %s\n", rdr->name); reader = rdr; goto autofound; } } else { char *endptr = NULL; unsigned int num; errno = 0; num = strtol(reader_id, &endptr, 0); if (!errno && endptr && *endptr == '\0') reader = sc_ctx_get_reader(ctx, num); else reader = sc_ctx_get_reader_by_name(ctx, reader_id); } } autofound: if (!reader) { fprintf(stderr, "Reader \"%s\" not found (%d reader(s) detected)\n", reader_id, sc_ctx_get_reader_count(ctx)); return 1; } if (sc_detect_card_presence(reader) <= 0) { fprintf(stderr, "Card not present.\n"); return 3; } } if (verbose) printf("Connecting to card in reader %s...\n", reader->name); r = sc_connect_card(reader, &card); if (r < 0) { fprintf(stderr, "Failed to connect to card: %s\n", sc_strerror(r)); return 1; } if (verbose) printf("Using card driver %s.\n", card->driver->name); if (do_lock) { r = sc_lock(card); if (r < 0) { fprintf(stderr, "Failed to lock card: %s\n", sc_strerror(r)); sc_disconnect_card(card); return 1; } } *cardp = card; return 0; } int util_connect_card(sc_context_t *ctx, sc_card_t **cardp, const char *reader_id, int do_wait, int verbose) { return util_connect_card_ex(ctx, cardp, reader_id, do_wait, 1, verbose); } void util_print_binary(FILE *f, const u8 *buf, int count) { int i; for (i = 0; i < count; i++) { unsigned char c = buf[i]; const char *format; if (!isprint(c)) format = "\\x%02X"; else format = "%c"; fprintf(f, format, c); } (void) fflush(f); } void util_hex_dump(FILE *f, const u8 *in, int len, const char *sep) { int i; for (i = 0; i < len; i++) { if (sep != NULL && i) fprintf(f, "%s", sep); fprintf(f, "%02X", in[i]); } } void util_hex_dump_asc(FILE *f, const u8 *in, size_t count, int addr) { int lines = 0; while (count) { char ascbuf[17]; size_t i; if (addr >= 0) { fprintf(f, "%08X: ", addr); addr += 16; } for (i = 0; i < count && i < 16; i++) { fprintf(f, "%02X ", *in); if (isprint(*in)) ascbuf[i] = *in; else ascbuf[i] = '.'; in++; } count -= i; ascbuf[i] = 0; for (; i < 16 && lines; i++) fprintf(f, " "); fprintf(f, "%s\n", ascbuf); lines++; } } NORETURN void util_print_usage_and_die(const char *app_name, const struct option options[], const char *option_help[], const char *args) { int i; int header_shown = 0; if (args) printf("Usage: %s [OPTIONS] %s\n", app_name, args); else printf("Usage: %s [OPTIONS]\n", app_name); for (i = 0; options[i].name; i++) { char buf[40]; const char *arg_str; /* Skip "hidden" options */ if (option_help[i] == NULL) continue; if (!header_shown++) printf("Options:\n"); switch (options[i].has_arg) { case 1: arg_str = " <arg>"; break; case 2: arg_str = " [arg]"; break; default: arg_str = ""; break; } if (isascii(options[i].val) && isprint(options[i].val) && !isspace(options[i].val)) sprintf(buf, "-%c, --%s%s", options[i].val, options[i].name, arg_str); else sprintf(buf, " --%s%s", options[i].name, arg_str); /* print the line - wrap if necessary */ if (strlen(buf) > 28) { printf(" %s\n", buf); buf[0] = '\0'; } printf(" %-28s %s\n", buf, option_help[i]); } exit(2); } const char * util_acl_to_str(const sc_acl_entry_t *e) { static char line[80], buf[20]; unsigned int acl; if (e == NULL) return "N/A"; line[0] = 0; while (e != NULL) { acl = e->method; switch (acl) { case SC_AC_UNKNOWN: return "N/A"; case SC_AC_NEVER: return "NEVR"; case SC_AC_NONE: return "NONE"; case SC_AC_CHV: strcpy(buf, "CHV"); if (e->key_ref != SC_AC_KEY_REF_NONE) sprintf(buf + 3, "%d", e->key_ref); break; case SC_AC_TERM: strcpy(buf, "TERM"); break; case SC_AC_PRO: strcpy(buf, "PROT"); break; case SC_AC_AUT: strcpy(buf, "AUTH"); if (e->key_ref != SC_AC_KEY_REF_NONE) sprintf(buf + 4, "%d", e->key_ref); break; case SC_AC_SEN: strcpy(buf, "Sec.Env. "); if (e->key_ref != SC_AC_KEY_REF_NONE) sprintf(buf + 3, "#%d", e->key_ref); break; case SC_AC_SCB: strcpy(buf, "Sec.ControlByte "); if (e->key_ref != SC_AC_KEY_REF_NONE) sprintf(buf + 3, "Ox%X", e->key_ref); break; case SC_AC_IDA: strcpy(buf, "PKCS#15 AuthID "); if (e->key_ref != SC_AC_KEY_REF_NONE) sprintf(buf + 3, "#%d", e->key_ref); break; default: strcpy(buf, "????"); break; } strcat(line, buf); strcat(line, " "); e = e->next; } line[strlen(line)-1] = 0; /* get rid of trailing space */ return line; } NORETURN void util_fatal(const char *fmt, ...) { va_list ap; va_start(ap, fmt); fprintf(stderr, "error: "); vfprintf(stderr, fmt, ap); fprintf(stderr, "\nAborting.\n"); va_end(ap); sc_notify_close(); exit(1); } void util_error(const char *fmt, ...) { va_list ap; va_start(ap, fmt); fprintf(stderr, "error: "); vfprintf(stderr, fmt, ap); fprintf(stderr, "\n"); va_end(ap); } void util_warn(const char *fmt, ...) { va_list ap; va_start(ap, fmt); fprintf(stderr, "warning: "); vfprintf(stderr, fmt, ap); fprintf(stderr, "\n"); va_end(ap); } int util_getpass (char **lineptr, size_t *len, FILE *stream) { #define MAX_PASS_SIZE 128 char *buf; size_t i; int ch = 0; #ifndef _WIN32 struct termios old, new; fflush(stdout); if (tcgetattr (fileno (stdout), &old) != 0) return -1; new = old; new.c_lflag &= ~ECHO; if (tcsetattr (fileno (stdout), TCSAFLUSH, &new) != 0) return -1; #endif buf = calloc(1, MAX_PASS_SIZE); if (!buf) return -1; for (i = 0; i < MAX_PASS_SIZE - 1; i++) { #ifndef _WIN32 ch = getchar(); #else ch = _getch(); #endif if (ch == 0 || ch == 3) break; if (ch == '\n' || ch == '\r') break; buf[i] = (char) ch; } #ifndef _WIN32 tcsetattr (fileno (stdout), TCSAFLUSH, &old); fputs("\n", stdout); #endif if (ch == 0 || ch == 3) { free(buf); return -1; } if (*lineptr && (!len || *len < i+1)) { free(*lineptr); *lineptr = NULL; } if (*lineptr) { memcpy(*lineptr,buf,i+1); memset(buf, 0, MAX_PASS_SIZE); free(buf); } else { *lineptr = buf; if (len) *len = MAX_PASS_SIZE; } return i; } size_t util_get_pin(const char *input, const char **pin) { size_t inputlen = strlen(input); size_t pinlen = 0; if(inputlen > 4 && strncasecmp(input, "env:", 4) == 0) { // Get a PIN from a environment variable *pin = getenv(input + 4); pinlen = *pin ? strlen(*pin) : 0; } else { //Just use the input *pin = input; pinlen = inputlen; } return pinlen; }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_339_10
crossvul-cpp_data_good_1611_4
/* t1lib * * This file contains functions for reading PFA and PFB files. * * Copyright (c) 1998-2013 Eddie Kohler * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, subject to the * conditions listed in the Click LICENSE file, which is available in full at * http://github.com/kohler/click/blob/master/LICENSE. The conditions * include: you must preserve this copyright notice, and you cannot mention * the copyright holders in advertising related to the Software without * their permission. The Software is provided WITHOUT ANY WARRANTY, EXPRESS * OR IMPLIED. This notice is a summary of the Click LICENSE file; the * license in that file is binding. */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> #include "t1lib.h" #ifdef __cplusplus extern "C" { #endif #define PFA_ASCII 1 #define PFA_EEXEC_TEST 2 #define PFA_HEX 3 #define PFA_BINARY 4 /* This function returns the value (0-15) of a single hex digit. It returns 0 for an invalid hex digit. */ static int hexval(char c) { if (c >= 'A' && c <= 'F') return c - 'A' + 10; else if (c >= 'a' && c <= 'f') return c - 'a' + 10; else if (c >= '0' && c <= '9') return c - '0'; else return 0; } /* This function translates a string of hexadecimal digits into binary data. We allow an odd number of digits. Returns length of binary data. */ static int translate_hex_string(char *s, char *saved_orphan) { int c1 = *saved_orphan; char *start = s; char *t = s; for (; *s; s++) { if (isspace((unsigned char) *s)) continue; if (c1) { *t++ = (hexval(c1) << 4) + hexval(*s); c1 = 0; } else c1 = *s; } *saved_orphan = c1; return t - start; } /* This function returns 1 if the string contains all '0's. */ static int all_zeroes(char *s) { if (*s == '\0' || *s == '\n') return 0; while (*s == '0') s++; return *s == '\0' || *s == '\n'; } /* This function handles the entire file. */ #define LINESIZE 1024 void process_pfa(FILE *ifp, const char *ifp_filename, struct font_reader *fr) { /* Loop until no more input. We need to look for `currentfile eexec' to start eexec section (hex to binary conversion) and line of all zeros to switch back to ASCII. */ /* Don't use fgets() in case line-endings are indicated by bare \r's, as occurs in Macintosh fonts. */ /* 2.Aug.1999 - At the behest of Tom Kacvinsky <tjk@ams.org>, support binary PFA fonts. */ char buffer[LINESIZE]; int c = 0; int blocktyp = PFA_ASCII; char saved_orphan = 0; (void)ifp_filename; while (c != EOF) { char *line = buffer, *last = buffer; int crlf = 0; c = getc(ifp); while (c != EOF && c != '\r' && c != '\n' && last < buffer + LINESIZE - 1) { *last++ = c; c = getc(ifp); } /* handle the end of the line */ if (last == buffer + LINESIZE - 1) /* buffer overrun: don't append newline even if we have it */ ungetc(c, ifp); else if (c == '\r' && blocktyp != PFA_BINARY) { /* change CR or CR/LF into LF, unless reading binary data! (This condition was wrong before, caused Thanh problems - 6.Mar.2001) */ c = getc(ifp); if (c != '\n') ungetc(c, ifp), crlf = 1; else crlf = 2; *last++ = '\n'; } else if (c != EOF) *last++ = c; *last = 0; /* now that we have the line, handle it */ if (blocktyp == PFA_ASCII) { if (strncmp(line, "currentfile eexec", 17) == 0 && isspace((unsigned char) line[17])) { char saved_p; /* assert(line == buffer); */ for (line += 18; isspace((unsigned char) *line); line++) /* nada */; saved_p = *line; *line = 0; fr->output_ascii(buffer, line - buffer); *line = saved_p; blocktyp = PFA_EEXEC_TEST; if (!*line) continue; } else { fr->output_ascii(line, last - line); continue; } } /* check immediately after "currentfile eexec" for ASCII or binary */ if (blocktyp == PFA_EEXEC_TEST) { /* 8.Feb.2004: fix bug if first character in a binary eexec block is 0, reported by Werner Lemberg */ for (; line < last && isspace((unsigned char) *line); line++) /* nada */; if (line == last) continue; else if (last >= line + 4 && isxdigit((unsigned char) line[0]) && isxdigit((unsigned char) line[1]) && isxdigit((unsigned char) line[2]) && isxdigit((unsigned char) line[3])) blocktyp = PFA_HEX; else blocktyp = PFA_BINARY; memmove(buffer, line, last - line + 1); last = buffer + (last - line); line = buffer; /* patch up crlf fix */ if (blocktyp == PFA_BINARY && crlf) { last[-1] = '\r'; if (crlf == 2) *last++ = '\n'; } } /* blocktyp == PFA_HEX || blocktyp == PFA_BINARY */ if (all_zeroes(line)) { /* XXX not safe */ fr->output_ascii(line, last - line); blocktyp = PFA_ASCII; } else if (blocktyp == PFA_HEX) { int len = translate_hex_string(line, &saved_orphan); if (len) fr->output_binary((unsigned char *)line, len); } else fr->output_binary((unsigned char *)line, last - line); } fr->output_end(); } /* Process a PFB file. */ /* XXX Doesn't handle "currentfile eexec" as intelligently as process_pfa does. */ static int handle_pfb_ascii(struct font_reader *fr, char *line, int len) { /* Divide PFB_ASCII blocks into lines */ int start = 0; while (1) { int pos = start; while (pos < len && line[pos] != '\n' && line[pos] != '\r') pos++; if (pos >= len) { if (pos == start) return 0; else if (start == 0 && pos == LINESIZE - 1) { line[pos] = 0; fr->output_ascii(line, pos); return 0; } else { memmove(line, line + start, pos - start); return pos - start; } } else if (pos < len - 1 && line[pos] == '\r' && line[pos+1] == '\n') { line[pos] = '\n'; line[pos+1] = 0; fr->output_ascii(line + start, pos + 1 - start); start = pos + 2; } else { char save = line[pos+1]; line[pos] = '\n'; line[pos+1] = 0; fr->output_ascii(line + start, pos + 1 - start); line[pos+1] = save; start = pos + 1; } } } void process_pfb(FILE *ifp, const char *ifp_filename, struct font_reader *fr) { int blocktyp = 0; unsigned block_len = 0; int c = 0; unsigned filepos = 0; int linepos = 0; char line[LINESIZE]; while (1) { while (block_len == 0) { c = getc(ifp); blocktyp = getc(ifp); if (c != PFB_MARKER || (blocktyp != PFB_ASCII && blocktyp != PFB_BINARY && blocktyp != PFB_DONE)) { if (c == EOF || blocktyp == EOF) error("%s corrupted: no end-of-file marker", ifp_filename); else error("%s corrupted: bad block marker at position %u", ifp_filename, filepos); blocktyp = PFB_DONE; } if (blocktyp == PFB_DONE) goto done; block_len = getc(ifp) & 0xFF; block_len |= (getc(ifp) & 0xFF) << 8; block_len |= (getc(ifp) & 0xFF) << 16; block_len |= (unsigned) (getc(ifp) & 0xFF) << 24; if (feof(ifp)) { error("%s corrupted: bad block length at position %u", ifp_filename, filepos); blocktyp = PFB_DONE; goto done; } filepos += 6; } /* read the block in its entirety, in LINESIZE chunks */ while (block_len > 0) { unsigned rest = LINESIZE - 1 - linepos; /* leave space for '\0' */ unsigned n = (block_len > rest ? rest : block_len); int actual = fread(line + linepos, 1, n, ifp); if (actual != (int) n) { error("%s corrupted: block short by %u bytes at position %u", ifp_filename, block_len - actual, filepos); block_len = actual; } if (blocktyp == PFB_BINARY) fr->output_binary((unsigned char *)line, actual); else linepos = handle_pfb_ascii(fr, line, linepos + actual); block_len -= actual; filepos += actual; } /* handle any leftover line */ if (linepos > 0) { line[linepos] = 0; fr->output_ascii(line, linepos); linepos = 0; } } done: c = getc(ifp); if (c != EOF) error("%s corrupted: data after PFB end marker at position %u", ifp_filename, filepos - 2); fr->output_end(); } #define DEFAULT_BLOCKLEN (1L<<12) void init_pfb_writer(struct pfb_writer *w, int blocklen, FILE *f) { w->len = DEFAULT_BLOCKLEN; w->buf = (unsigned char *)malloc(w->len); if (!w->buf) fatal_error("out of memory"); w->max_len = (blocklen <= 0 ? 0xFFFFFFFFU : (unsigned)blocklen); w->pos = 0; w->blocktyp = PFB_ASCII; w->binary_blocks_written = 0; w->f = f; } void pfb_writer_output_block(struct pfb_writer *w) { /* do nothing if nothing in block */ if (w->pos == 0) return; /* output four-byte block length */ putc(PFB_MARKER, w->f); putc(w->blocktyp, w->f); putc((int)(w->pos & 0xff), w->f); putc((int)((w->pos >> 8) & 0xff), w->f); putc((int)((w->pos >> 16) & 0xff), w->f); putc((int)((w->pos >> 24) & 0xff), w->f); /* output block data */ fwrite(w->buf, 1, w->pos, w->f); /* mark block buffer empty and uninitialized */ w->pos = 0; if (w->blocktyp == PFB_BINARY) w->binary_blocks_written++; } void pfb_writer_grow_buf(struct pfb_writer *w) { if (w->len < w->max_len) { /* grow w->buf */ unsigned new_len = w->len * 2; unsigned char *new_buf; if (new_len > w->max_len) new_len = w->max_len; new_buf = (unsigned char *)malloc(new_len); if (!new_buf) { error("out of memory; continuing with a smaller block size"); w->max_len = w->len; pfb_writer_output_block(w); } else { memcpy(new_buf, w->buf, w->len); free(w->buf); w->buf = new_buf; w->len = new_len; } } else /* buf already the right size, just output the block */ pfb_writer_output_block(w); } void pfb_writer_end(struct pfb_writer *w) { if (w->pos) pfb_writer_output_block(w); putc(PFB_MARKER, w->f); putc(PFB_DONE, w->f); } /* This CRC table and routine were borrowed from macutils-2.0b3 */ static unsigned short crctab[256] = { 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7, 0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF, 0x1231, 0x0210, 0x3273, 0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6, 0x9339, 0x8318, 0xB37B, 0xA35A, 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE, 0x2462, 0x3443, 0x0420, 0x1401, 0x64E6, 0x74C7, 0x44A4, 0x5485, 0xA56A, 0xB54B, 0x8528, 0x9509, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D, 0x3653, 0x2672, 0x1611, 0x0630, 0x76D7, 0x66F6, 0x5695, 0x46B4, 0xB75B, 0xA77A, 0x9719, 0x8738, 0xF7DF, 0xE7FE, 0xD79D, 0xC7BC, 0x48C4, 0x58E5, 0x6886, 0x78A7, 0x0840, 0x1861, 0x2802, 0x3823, 0xC9CC, 0xD9ED, 0xE98E, 0xF9AF, 0x8948, 0x9969, 0xA90A, 0xB92B, 0x5AF5, 0x4AD4, 0x7AB7, 0x6A96, 0x1A71, 0x0A50, 0x3A33, 0x2A12, 0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E, 0x9B79, 0x8B58, 0xBB3B, 0xAB1A, 0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x2C22, 0x3C03, 0x0C60, 0x1C41, 0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD, 0xAD2A, 0xBD0B, 0x8D68, 0x9D49, 0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70, 0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78, 0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F, 0x1080, 0x00A1, 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067, 0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C, 0xE37F, 0xF35E, 0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256, 0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0xF56E, 0xE54F, 0xD52C, 0xC50D, 0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C, 0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634, 0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB, 0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1, 0x3882, 0x28A3, 0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A, 0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92, 0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9, 0x7C26, 0x6C07, 0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1, 0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8, 0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0, }; /* * Update a CRC check on the given buffer. */ int crcbuf(int crc, unsigned int len, const char *buf) { const unsigned char *ubuf = (const unsigned char *)buf; while (len--) crc = ((crc << 8) & 0xFF00) ^ crctab[((crc >> 8) & 0xFF) ^ *ubuf++]; return crc; } #ifdef __cplusplus } #endif
./CrossVul/dataset_final_sorted/CWE-119/c/good_1611_4
crossvul-cpp_data_good_3311_0
/* DVB USB framework compliant Linux driver for the * DVBWorld DVB-S 2101, 2102, DVB-S2 2104, DVB-C 3101, * TeVii S421, S480, S482, S600, S630, S632, S650, S660, S662, * Prof 1100, 7500, * Geniatech SU3000, T220, * TechnoTrend S2-4600, * Terratec Cinergy S2 cards * Copyright (C) 2008-2012 Igor M. Liplianin (liplianin@me.by) * * 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, version 2. * * see Documentation/dvb/README.dvb-usb for more information */ #include "dvb-usb-ids.h" #include "dw2102.h" #include "si21xx.h" #include "stv0299.h" #include "z0194a.h" #include "stv0288.h" #include "stb6000.h" #include "eds1547.h" #include "cx24116.h" #include "tda1002x.h" #include "mt312.h" #include "zl10039.h" #include "ts2020.h" #include "ds3000.h" #include "stv0900.h" #include "stv6110.h" #include "stb6100.h" #include "stb6100_proc.h" #include "m88rs2000.h" #include "tda18271.h" #include "cxd2820r.h" #include "m88ds3103.h" /* Max transfer size done by I2C transfer functions */ #define MAX_XFER_SIZE 64 #define DW210X_READ_MSG 0 #define DW210X_WRITE_MSG 1 #define REG_1F_SYMBOLRATE_BYTE0 0x1f #define REG_20_SYMBOLRATE_BYTE1 0x20 #define REG_21_SYMBOLRATE_BYTE2 0x21 /* on my own*/ #define DW2102_VOLTAGE_CTRL (0x1800) #define SU3000_STREAM_CTRL (0x1900) #define DW2102_RC_QUERY (0x1a00) #define DW2102_LED_CTRL (0x1b00) #define DW2101_FIRMWARE "dvb-usb-dw2101.fw" #define DW2102_FIRMWARE "dvb-usb-dw2102.fw" #define DW2104_FIRMWARE "dvb-usb-dw2104.fw" #define DW3101_FIRMWARE "dvb-usb-dw3101.fw" #define S630_FIRMWARE "dvb-usb-s630.fw" #define S660_FIRMWARE "dvb-usb-s660.fw" #define P1100_FIRMWARE "dvb-usb-p1100.fw" #define P7500_FIRMWARE "dvb-usb-p7500.fw" #define err_str "did not find the firmware file. (%s) " \ "Please see linux/Documentation/dvb/ for more details " \ "on firmware-problems." struct dw2102_state { u8 initialized; u8 last_lock; u8 data[MAX_XFER_SIZE + 4]; struct i2c_client *i2c_client_demod; struct i2c_client *i2c_client_tuner; /* fe hook functions*/ int (*old_set_voltage)(struct dvb_frontend *f, enum fe_sec_voltage v); int (*fe_read_status)(struct dvb_frontend *fe, enum fe_status *status); }; /* debug */ static int dvb_usb_dw2102_debug; module_param_named(debug, dvb_usb_dw2102_debug, int, 0644); MODULE_PARM_DESC(debug, "set debugging level (1=info 2=xfer 4=rc(or-able))." DVB_USB_DEBUG_STATUS); /* demod probe */ static int demod_probe = 1; module_param_named(demod, demod_probe, int, 0644); MODULE_PARM_DESC(demod, "demod to probe (1=cx24116 2=stv0903+stv6110 4=stv0903+stb6100(or-able))."); DVB_DEFINE_MOD_OPT_ADAPTER_NR(adapter_nr); static int dw210x_op_rw(struct usb_device *dev, u8 request, u16 value, u16 index, u8 * data, u16 len, int flags) { int ret; u8 *u8buf; unsigned int pipe = (flags == DW210X_READ_MSG) ? usb_rcvctrlpipe(dev, 0) : usb_sndctrlpipe(dev, 0); u8 request_type = (flags == DW210X_READ_MSG) ? USB_DIR_IN : USB_DIR_OUT; u8buf = kmalloc(len, GFP_KERNEL); if (!u8buf) return -ENOMEM; if (flags == DW210X_WRITE_MSG) memcpy(u8buf, data, len); ret = usb_control_msg(dev, pipe, request, request_type | USB_TYPE_VENDOR, value, index , u8buf, len, 2000); if (flags == DW210X_READ_MSG) memcpy(data, u8buf, len); kfree(u8buf); return ret; } /* I2C */ static int dw2102_i2c_transfer(struct i2c_adapter *adap, struct i2c_msg msg[], int num) { struct dvb_usb_device *d = i2c_get_adapdata(adap); int i = 0; u8 buf6[] = {0x2c, 0x05, 0xc0, 0, 0, 0, 0}; u16 value; if (!d) return -ENODEV; if (mutex_lock_interruptible(&d->i2c_mutex) < 0) return -EAGAIN; switch (num) { case 2: /* read stv0299 register */ value = msg[0].buf[0];/* register */ for (i = 0; i < msg[1].len; i++) { dw210x_op_rw(d->udev, 0xb5, value + i, 0, buf6, 2, DW210X_READ_MSG); msg[1].buf[i] = buf6[0]; } break; case 1: switch (msg[0].addr) { case 0x68: /* write to stv0299 register */ buf6[0] = 0x2a; buf6[1] = msg[0].buf[0]; buf6[2] = msg[0].buf[1]; dw210x_op_rw(d->udev, 0xb2, 0, 0, buf6, 3, DW210X_WRITE_MSG); break; case 0x60: if (msg[0].flags == 0) { /* write to tuner pll */ buf6[0] = 0x2c; buf6[1] = 5; buf6[2] = 0xc0; buf6[3] = msg[0].buf[0]; buf6[4] = msg[0].buf[1]; buf6[5] = msg[0].buf[2]; buf6[6] = msg[0].buf[3]; dw210x_op_rw(d->udev, 0xb2, 0, 0, buf6, 7, DW210X_WRITE_MSG); } else { /* read from tuner */ dw210x_op_rw(d->udev, 0xb5, 0, 0, buf6, 1, DW210X_READ_MSG); msg[0].buf[0] = buf6[0]; } break; case (DW2102_RC_QUERY): dw210x_op_rw(d->udev, 0xb8, 0, 0, buf6, 2, DW210X_READ_MSG); msg[0].buf[0] = buf6[0]; msg[0].buf[1] = buf6[1]; break; case (DW2102_VOLTAGE_CTRL): buf6[0] = 0x30; buf6[1] = msg[0].buf[0]; dw210x_op_rw(d->udev, 0xb2, 0, 0, buf6, 2, DW210X_WRITE_MSG); break; } break; } mutex_unlock(&d->i2c_mutex); return num; } static int dw2102_serit_i2c_transfer(struct i2c_adapter *adap, struct i2c_msg msg[], int num) { struct dvb_usb_device *d = i2c_get_adapdata(adap); u8 buf6[] = {0, 0, 0, 0, 0, 0, 0}; if (!d) return -ENODEV; if (mutex_lock_interruptible(&d->i2c_mutex) < 0) return -EAGAIN; switch (num) { case 2: /* read si2109 register by number */ buf6[0] = msg[0].addr << 1; buf6[1] = msg[0].len; buf6[2] = msg[0].buf[0]; dw210x_op_rw(d->udev, 0xc2, 0, 0, buf6, msg[0].len + 2, DW210X_WRITE_MSG); /* read si2109 register */ dw210x_op_rw(d->udev, 0xc3, 0xd0, 0, buf6, msg[1].len + 2, DW210X_READ_MSG); memcpy(msg[1].buf, buf6 + 2, msg[1].len); break; case 1: switch (msg[0].addr) { case 0x68: /* write to si2109 register */ buf6[0] = msg[0].addr << 1; buf6[1] = msg[0].len; memcpy(buf6 + 2, msg[0].buf, msg[0].len); dw210x_op_rw(d->udev, 0xc2, 0, 0, buf6, msg[0].len + 2, DW210X_WRITE_MSG); break; case(DW2102_RC_QUERY): dw210x_op_rw(d->udev, 0xb8, 0, 0, buf6, 2, DW210X_READ_MSG); msg[0].buf[0] = buf6[0]; msg[0].buf[1] = buf6[1]; break; case(DW2102_VOLTAGE_CTRL): buf6[0] = 0x30; buf6[1] = msg[0].buf[0]; dw210x_op_rw(d->udev, 0xb2, 0, 0, buf6, 2, DW210X_WRITE_MSG); break; } break; } mutex_unlock(&d->i2c_mutex); return num; } static int dw2102_earda_i2c_transfer(struct i2c_adapter *adap, struct i2c_msg msg[], int num) { struct dvb_usb_device *d = i2c_get_adapdata(adap); int ret; if (!d) return -ENODEV; if (mutex_lock_interruptible(&d->i2c_mutex) < 0) return -EAGAIN; switch (num) { case 2: { /* read */ /* first write first register number */ u8 ibuf[MAX_XFER_SIZE], obuf[3]; if (2 + msg[1].len > sizeof(ibuf)) { warn("i2c rd: len=%d is too big!\n", msg[1].len); ret = -EOPNOTSUPP; goto unlock; } obuf[0] = msg[0].addr << 1; obuf[1] = msg[0].len; obuf[2] = msg[0].buf[0]; dw210x_op_rw(d->udev, 0xc2, 0, 0, obuf, msg[0].len + 2, DW210X_WRITE_MSG); /* second read registers */ dw210x_op_rw(d->udev, 0xc3, 0xd1 , 0, ibuf, msg[1].len + 2, DW210X_READ_MSG); memcpy(msg[1].buf, ibuf + 2, msg[1].len); break; } case 1: switch (msg[0].addr) { case 0x68: { /* write to register */ u8 obuf[MAX_XFER_SIZE]; if (2 + msg[0].len > sizeof(obuf)) { warn("i2c wr: len=%d is too big!\n", msg[1].len); ret = -EOPNOTSUPP; goto unlock; } obuf[0] = msg[0].addr << 1; obuf[1] = msg[0].len; memcpy(obuf + 2, msg[0].buf, msg[0].len); dw210x_op_rw(d->udev, 0xc2, 0, 0, obuf, msg[0].len + 2, DW210X_WRITE_MSG); break; } case 0x61: { /* write to tuner */ u8 obuf[MAX_XFER_SIZE]; if (2 + msg[0].len > sizeof(obuf)) { warn("i2c wr: len=%d is too big!\n", msg[1].len); ret = -EOPNOTSUPP; goto unlock; } obuf[0] = msg[0].addr << 1; obuf[1] = msg[0].len; memcpy(obuf + 2, msg[0].buf, msg[0].len); dw210x_op_rw(d->udev, 0xc2, 0, 0, obuf, msg[0].len + 2, DW210X_WRITE_MSG); break; } case(DW2102_RC_QUERY): { u8 ibuf[2]; dw210x_op_rw(d->udev, 0xb8, 0, 0, ibuf, 2, DW210X_READ_MSG); memcpy(msg[0].buf, ibuf , 2); break; } case(DW2102_VOLTAGE_CTRL): { u8 obuf[2]; obuf[0] = 0x30; obuf[1] = msg[0].buf[0]; dw210x_op_rw(d->udev, 0xb2, 0, 0, obuf, 2, DW210X_WRITE_MSG); break; } } break; } ret = num; unlock: mutex_unlock(&d->i2c_mutex); return ret; } static int dw2104_i2c_transfer(struct i2c_adapter *adap, struct i2c_msg msg[], int num) { struct dvb_usb_device *d = i2c_get_adapdata(adap); int len, i, j, ret; if (!d) return -ENODEV; if (mutex_lock_interruptible(&d->i2c_mutex) < 0) return -EAGAIN; for (j = 0; j < num; j++) { switch (msg[j].addr) { case(DW2102_RC_QUERY): { u8 ibuf[2]; dw210x_op_rw(d->udev, 0xb8, 0, 0, ibuf, 2, DW210X_READ_MSG); memcpy(msg[j].buf, ibuf , 2); break; } case(DW2102_VOLTAGE_CTRL): { u8 obuf[2]; obuf[0] = 0x30; obuf[1] = msg[j].buf[0]; dw210x_op_rw(d->udev, 0xb2, 0, 0, obuf, 2, DW210X_WRITE_MSG); break; } /*case 0x55: cx24116 case 0x6a: stv0903 case 0x68: ds3000, stv0903 case 0x60: ts2020, stv6110, stb6100 */ default: { if (msg[j].flags == I2C_M_RD) { /* read registers */ u8 ibuf[MAX_XFER_SIZE]; if (2 + msg[j].len > sizeof(ibuf)) { warn("i2c rd: len=%d is too big!\n", msg[j].len); ret = -EOPNOTSUPP; goto unlock; } dw210x_op_rw(d->udev, 0xc3, (msg[j].addr << 1) + 1, 0, ibuf, msg[j].len + 2, DW210X_READ_MSG); memcpy(msg[j].buf, ibuf + 2, msg[j].len); mdelay(10); } else if (((msg[j].buf[0] == 0xb0) && (msg[j].addr == 0x68)) || ((msg[j].buf[0] == 0xf7) && (msg[j].addr == 0x55))) { /* write firmware */ u8 obuf[19]; obuf[0] = msg[j].addr << 1; obuf[1] = (msg[j].len > 15 ? 17 : msg[j].len); obuf[2] = msg[j].buf[0]; len = msg[j].len - 1; i = 1; do { memcpy(obuf + 3, msg[j].buf + i, (len > 16 ? 16 : len)); dw210x_op_rw(d->udev, 0xc2, 0, 0, obuf, (len > 16 ? 16 : len) + 3, DW210X_WRITE_MSG); i += 16; len -= 16; } while (len > 0); } else { /* write registers */ u8 obuf[MAX_XFER_SIZE]; if (2 + msg[j].len > sizeof(obuf)) { warn("i2c wr: len=%d is too big!\n", msg[j].len); ret = -EOPNOTSUPP; goto unlock; } obuf[0] = msg[j].addr << 1; obuf[1] = msg[j].len; memcpy(obuf + 2, msg[j].buf, msg[j].len); dw210x_op_rw(d->udev, 0xc2, 0, 0, obuf, msg[j].len + 2, DW210X_WRITE_MSG); } break; } } } ret = num; unlock: mutex_unlock(&d->i2c_mutex); return ret; } static int dw3101_i2c_transfer(struct i2c_adapter *adap, struct i2c_msg msg[], int num) { struct dvb_usb_device *d = i2c_get_adapdata(adap); int ret; int i; if (!d) return -ENODEV; if (mutex_lock_interruptible(&d->i2c_mutex) < 0) return -EAGAIN; switch (num) { case 2: { /* read */ /* first write first register number */ u8 ibuf[MAX_XFER_SIZE], obuf[3]; if (2 + msg[1].len > sizeof(ibuf)) { warn("i2c rd: len=%d is too big!\n", msg[1].len); ret = -EOPNOTSUPP; goto unlock; } obuf[0] = msg[0].addr << 1; obuf[1] = msg[0].len; obuf[2] = msg[0].buf[0]; dw210x_op_rw(d->udev, 0xc2, 0, 0, obuf, msg[0].len + 2, DW210X_WRITE_MSG); /* second read registers */ dw210x_op_rw(d->udev, 0xc3, 0x19 , 0, ibuf, msg[1].len + 2, DW210X_READ_MSG); memcpy(msg[1].buf, ibuf + 2, msg[1].len); break; } case 1: switch (msg[0].addr) { case 0x60: case 0x0c: { /* write to register */ u8 obuf[MAX_XFER_SIZE]; if (2 + msg[0].len > sizeof(obuf)) { warn("i2c wr: len=%d is too big!\n", msg[0].len); ret = -EOPNOTSUPP; goto unlock; } obuf[0] = msg[0].addr << 1; obuf[1] = msg[0].len; memcpy(obuf + 2, msg[0].buf, msg[0].len); dw210x_op_rw(d->udev, 0xc2, 0, 0, obuf, msg[0].len + 2, DW210X_WRITE_MSG); break; } case(DW2102_RC_QUERY): { u8 ibuf[2]; dw210x_op_rw(d->udev, 0xb8, 0, 0, ibuf, 2, DW210X_READ_MSG); memcpy(msg[0].buf, ibuf , 2); break; } } break; } for (i = 0; i < num; i++) { deb_xfer("%02x:%02x: %s ", i, msg[i].addr, msg[i].flags == 0 ? ">>>" : "<<<"); debug_dump(msg[i].buf, msg[i].len, deb_xfer); } ret = num; unlock: mutex_unlock(&d->i2c_mutex); return ret; } static int s6x0_i2c_transfer(struct i2c_adapter *adap, struct i2c_msg msg[], int num) { struct dvb_usb_device *d = i2c_get_adapdata(adap); struct usb_device *udev; int len, i, j, ret; if (!d) return -ENODEV; udev = d->udev; if (mutex_lock_interruptible(&d->i2c_mutex) < 0) return -EAGAIN; for (j = 0; j < num; j++) { switch (msg[j].addr) { case (DW2102_RC_QUERY): { u8 ibuf[5]; dw210x_op_rw(d->udev, 0xb8, 0, 0, ibuf, 5, DW210X_READ_MSG); memcpy(msg[j].buf, ibuf + 3, 2); break; } case (DW2102_VOLTAGE_CTRL): { u8 obuf[2]; obuf[0] = 1; obuf[1] = msg[j].buf[1];/* off-on */ dw210x_op_rw(d->udev, 0x8a, 0, 0, obuf, 2, DW210X_WRITE_MSG); obuf[0] = 3; obuf[1] = msg[j].buf[0];/* 13v-18v */ dw210x_op_rw(d->udev, 0x8a, 0, 0, obuf, 2, DW210X_WRITE_MSG); break; } case (DW2102_LED_CTRL): { u8 obuf[2]; obuf[0] = 5; obuf[1] = msg[j].buf[0]; dw210x_op_rw(d->udev, 0x8a, 0, 0, obuf, 2, DW210X_WRITE_MSG); break; } /*case 0x55: cx24116 case 0x6a: stv0903 case 0x68: ds3000, stv0903, rs2000 case 0x60: ts2020, stv6110, stb6100 case 0xa0: eeprom */ default: { if (msg[j].flags == I2C_M_RD) { /* read registers */ u8 ibuf[MAX_XFER_SIZE]; if (msg[j].len > sizeof(ibuf)) { warn("i2c rd: len=%d is too big!\n", msg[j].len); ret = -EOPNOTSUPP; goto unlock; } dw210x_op_rw(d->udev, 0x91, 0, 0, ibuf, msg[j].len, DW210X_READ_MSG); memcpy(msg[j].buf, ibuf, msg[j].len); break; } else if ((msg[j].buf[0] == 0xb0) && (msg[j].addr == 0x68)) { /* write firmware */ u8 obuf[19]; obuf[0] = (msg[j].len > 16 ? 18 : msg[j].len + 1); obuf[1] = msg[j].addr << 1; obuf[2] = msg[j].buf[0]; len = msg[j].len - 1; i = 1; do { memcpy(obuf + 3, msg[j].buf + i, (len > 16 ? 16 : len)); dw210x_op_rw(d->udev, 0x80, 0, 0, obuf, (len > 16 ? 16 : len) + 3, DW210X_WRITE_MSG); i += 16; len -= 16; } while (len > 0); } else if (j < (num - 1)) { /* write register addr before read */ u8 obuf[MAX_XFER_SIZE]; if (2 + msg[j].len > sizeof(obuf)) { warn("i2c wr: len=%d is too big!\n", msg[j].len); ret = -EOPNOTSUPP; goto unlock; } obuf[0] = msg[j + 1].len; obuf[1] = (msg[j].addr << 1); memcpy(obuf + 2, msg[j].buf, msg[j].len); dw210x_op_rw(d->udev, le16_to_cpu(udev->descriptor.idProduct) == 0x7500 ? 0x92 : 0x90, 0, 0, obuf, msg[j].len + 2, DW210X_WRITE_MSG); break; } else { /* write registers */ u8 obuf[MAX_XFER_SIZE]; if (2 + msg[j].len > sizeof(obuf)) { warn("i2c wr: len=%d is too big!\n", msg[j].len); ret = -EOPNOTSUPP; goto unlock; } obuf[0] = msg[j].len + 1; obuf[1] = (msg[j].addr << 1); memcpy(obuf + 2, msg[j].buf, msg[j].len); dw210x_op_rw(d->udev, 0x80, 0, 0, obuf, msg[j].len + 2, DW210X_WRITE_MSG); break; } break; } } } ret = num; unlock: mutex_unlock(&d->i2c_mutex); return ret; } static int su3000_i2c_transfer(struct i2c_adapter *adap, struct i2c_msg msg[], int num) { struct dvb_usb_device *d = i2c_get_adapdata(adap); struct dw2102_state *state; if (!d) return -ENODEV; state = d->priv; if (mutex_lock_interruptible(&d->i2c_mutex) < 0) return -EAGAIN; if (mutex_lock_interruptible(&d->data_mutex) < 0) { mutex_unlock(&d->i2c_mutex); return -EAGAIN; } switch (num) { case 1: switch (msg[0].addr) { case SU3000_STREAM_CTRL: state->data[0] = msg[0].buf[0] + 0x36; state->data[1] = 3; state->data[2] = 0; if (dvb_usb_generic_rw(d, state->data, 3, state->data, 0, 0) < 0) err("i2c transfer failed."); break; case DW2102_RC_QUERY: state->data[0] = 0x10; if (dvb_usb_generic_rw(d, state->data, 1, state->data, 2, 0) < 0) err("i2c transfer failed."); msg[0].buf[1] = state->data[0]; msg[0].buf[0] = state->data[1]; break; default: /* always i2c write*/ state->data[0] = 0x08; state->data[1] = msg[0].addr; state->data[2] = msg[0].len; memcpy(&state->data[3], msg[0].buf, msg[0].len); if (dvb_usb_generic_rw(d, state->data, msg[0].len + 3, state->data, 1, 0) < 0) err("i2c transfer failed."); } break; case 2: /* always i2c read */ state->data[0] = 0x09; state->data[1] = msg[0].len; state->data[2] = msg[1].len; state->data[3] = msg[0].addr; memcpy(&state->data[4], msg[0].buf, msg[0].len); if (dvb_usb_generic_rw(d, state->data, msg[0].len + 4, state->data, msg[1].len + 1, 0) < 0) err("i2c transfer failed."); memcpy(msg[1].buf, &state->data[1], msg[1].len); break; default: warn("more than 2 i2c messages at a time is not handled yet."); break; } mutex_unlock(&d->data_mutex); mutex_unlock(&d->i2c_mutex); return num; } static u32 dw210x_i2c_func(struct i2c_adapter *adapter) { return I2C_FUNC_I2C; } static struct i2c_algorithm dw2102_i2c_algo = { .master_xfer = dw2102_i2c_transfer, .functionality = dw210x_i2c_func, }; static struct i2c_algorithm dw2102_serit_i2c_algo = { .master_xfer = dw2102_serit_i2c_transfer, .functionality = dw210x_i2c_func, }; static struct i2c_algorithm dw2102_earda_i2c_algo = { .master_xfer = dw2102_earda_i2c_transfer, .functionality = dw210x_i2c_func, }; static struct i2c_algorithm dw2104_i2c_algo = { .master_xfer = dw2104_i2c_transfer, .functionality = dw210x_i2c_func, }; static struct i2c_algorithm dw3101_i2c_algo = { .master_xfer = dw3101_i2c_transfer, .functionality = dw210x_i2c_func, }; static struct i2c_algorithm s6x0_i2c_algo = { .master_xfer = s6x0_i2c_transfer, .functionality = dw210x_i2c_func, }; static struct i2c_algorithm su3000_i2c_algo = { .master_xfer = su3000_i2c_transfer, .functionality = dw210x_i2c_func, }; static int dw210x_read_mac_address(struct dvb_usb_device *d, u8 mac[6]) { int i; u8 ibuf[] = {0, 0}; u8 eeprom[256], eepromline[16]; for (i = 0; i < 256; i++) { if (dw210x_op_rw(d->udev, 0xb6, 0xa0 , i, ibuf, 2, DW210X_READ_MSG) < 0) { err("read eeprom failed."); return -1; } else { eepromline[i%16] = ibuf[0]; eeprom[i] = ibuf[0]; } if ((i % 16) == 15) { deb_xfer("%02x: ", i - 15); debug_dump(eepromline, 16, deb_xfer); } } memcpy(mac, eeprom + 8, 6); return 0; }; static int s6x0_read_mac_address(struct dvb_usb_device *d, u8 mac[6]) { int i, ret; u8 ibuf[] = { 0 }, obuf[] = { 0 }; u8 eeprom[256], eepromline[16]; struct i2c_msg msg[] = { { .addr = 0xa0 >> 1, .flags = 0, .buf = obuf, .len = 1, }, { .addr = 0xa0 >> 1, .flags = I2C_M_RD, .buf = ibuf, .len = 1, } }; for (i = 0; i < 256; i++) { obuf[0] = i; ret = s6x0_i2c_transfer(&d->i2c_adap, msg, 2); if (ret != 2) { err("read eeprom failed."); return -1; } else { eepromline[i % 16] = ibuf[0]; eeprom[i] = ibuf[0]; } if ((i % 16) == 15) { deb_xfer("%02x: ", i - 15); debug_dump(eepromline, 16, deb_xfer); } } memcpy(mac, eeprom + 16, 6); return 0; }; static int su3000_streaming_ctrl(struct dvb_usb_adapter *adap, int onoff) { static u8 command_start[] = {0x00}; static u8 command_stop[] = {0x01}; struct i2c_msg msg = { .addr = SU3000_STREAM_CTRL, .flags = 0, .buf = onoff ? command_start : command_stop, .len = 1 }; i2c_transfer(&adap->dev->i2c_adap, &msg, 1); return 0; } static int su3000_power_ctrl(struct dvb_usb_device *d, int i) { struct dw2102_state *state = (struct dw2102_state *)d->priv; int ret = 0; info("%s: %d, initialized %d", __func__, i, state->initialized); if (i && !state->initialized) { mutex_lock(&d->data_mutex); state->data[0] = 0xde; state->data[1] = 0; state->initialized = 1; /* reset board */ ret = dvb_usb_generic_rw(d, state->data, 2, NULL, 0, 0); mutex_unlock(&d->data_mutex); } return ret; } static int su3000_read_mac_address(struct dvb_usb_device *d, u8 mac[6]) { int i; u8 obuf[] = { 0x1f, 0xf0 }; u8 ibuf[] = { 0 }; struct i2c_msg msg[] = { { .addr = 0x51, .flags = 0, .buf = obuf, .len = 2, }, { .addr = 0x51, .flags = I2C_M_RD, .buf = ibuf, .len = 1, } }; for (i = 0; i < 6; i++) { obuf[1] = 0xf0 + i; if (i2c_transfer(&d->i2c_adap, msg, 2) != 2) break; else mac[i] = ibuf[0]; } return 0; } static int su3000_identify_state(struct usb_device *udev, struct dvb_usb_device_properties *props, struct dvb_usb_device_description **desc, int *cold) { info("%s", __func__); *cold = 0; return 0; } static int dw210x_set_voltage(struct dvb_frontend *fe, enum fe_sec_voltage voltage) { static u8 command_13v[] = {0x00, 0x01}; static u8 command_18v[] = {0x01, 0x01}; static u8 command_off[] = {0x00, 0x00}; struct i2c_msg msg = { .addr = DW2102_VOLTAGE_CTRL, .flags = 0, .buf = command_off, .len = 2, }; struct dvb_usb_adapter *udev_adap = (struct dvb_usb_adapter *)(fe->dvb->priv); if (voltage == SEC_VOLTAGE_18) msg.buf = command_18v; else if (voltage == SEC_VOLTAGE_13) msg.buf = command_13v; i2c_transfer(&udev_adap->dev->i2c_adap, &msg, 1); return 0; } static int s660_set_voltage(struct dvb_frontend *fe, enum fe_sec_voltage voltage) { struct dvb_usb_adapter *d = (struct dvb_usb_adapter *)(fe->dvb->priv); struct dw2102_state *st = (struct dw2102_state *)d->dev->priv; dw210x_set_voltage(fe, voltage); if (st->old_set_voltage) st->old_set_voltage(fe, voltage); return 0; } static void dw210x_led_ctrl(struct dvb_frontend *fe, int offon) { static u8 led_off[] = { 0 }; static u8 led_on[] = { 1 }; struct i2c_msg msg = { .addr = DW2102_LED_CTRL, .flags = 0, .buf = led_off, .len = 1 }; struct dvb_usb_adapter *udev_adap = (struct dvb_usb_adapter *)(fe->dvb->priv); if (offon) msg.buf = led_on; i2c_transfer(&udev_adap->dev->i2c_adap, &msg, 1); } static int tt_s2_4600_read_status(struct dvb_frontend *fe, enum fe_status *status) { struct dvb_usb_adapter *d = (struct dvb_usb_adapter *)(fe->dvb->priv); struct dw2102_state *st = (struct dw2102_state *)d->dev->priv; int ret; ret = st->fe_read_status(fe, status); /* resync slave fifo when signal change from unlock to lock */ if ((*status & FE_HAS_LOCK) && (!st->last_lock)) su3000_streaming_ctrl(d, 1); st->last_lock = (*status & FE_HAS_LOCK) ? 1 : 0; return ret; } static struct stv0299_config sharp_z0194a_config = { .demod_address = 0x68, .inittab = sharp_z0194a_inittab, .mclk = 88000000UL, .invert = 1, .skip_reinit = 0, .lock_output = STV0299_LOCKOUTPUT_1, .volt13_op0_op1 = STV0299_VOLT13_OP1, .min_delay_ms = 100, .set_symbol_rate = sharp_z0194a_set_symbol_rate, }; static struct cx24116_config dw2104_config = { .demod_address = 0x55, .mpg_clk_pos_pol = 0x01, }; static struct si21xx_config serit_sp1511lhb_config = { .demod_address = 0x68, .min_delay_ms = 100, }; static struct tda10023_config dw3101_tda10023_config = { .demod_address = 0x0c, .invert = 1, }; static struct mt312_config zl313_config = { .demod_address = 0x0e, }; static struct ds3000_config dw2104_ds3000_config = { .demod_address = 0x68, }; static struct ts2020_config dw2104_ts2020_config = { .tuner_address = 0x60, .clk_out_div = 1, .frequency_div = 1060000, }; static struct ds3000_config s660_ds3000_config = { .demod_address = 0x68, .ci_mode = 1, .set_lock_led = dw210x_led_ctrl, }; static struct ts2020_config s660_ts2020_config = { .tuner_address = 0x60, .clk_out_div = 1, .frequency_div = 1146000, }; static struct stv0900_config dw2104a_stv0900_config = { .demod_address = 0x6a, .demod_mode = 0, .xtal = 27000000, .clkmode = 3,/* 0-CLKI, 2-XTALI, else AUTO */ .diseqc_mode = 2,/* 2/3 PWM */ .tun1_maddress = 0,/* 0x60 */ .tun1_adc = 0,/* 2 Vpp */ .path1_mode = 3, }; static struct stb6100_config dw2104a_stb6100_config = { .tuner_address = 0x60, .refclock = 27000000, }; static struct stv0900_config dw2104_stv0900_config = { .demod_address = 0x68, .demod_mode = 0, .xtal = 8000000, .clkmode = 3, .diseqc_mode = 2, .tun1_maddress = 0, .tun1_adc = 1,/* 1 Vpp */ .path1_mode = 3, }; static struct stv6110_config dw2104_stv6110_config = { .i2c_address = 0x60, .mclk = 16000000, .clk_div = 1, }; static struct stv0900_config prof_7500_stv0900_config = { .demod_address = 0x6a, .demod_mode = 0, .xtal = 27000000, .clkmode = 3,/* 0-CLKI, 2-XTALI, else AUTO */ .diseqc_mode = 2,/* 2/3 PWM */ .tun1_maddress = 0,/* 0x60 */ .tun1_adc = 0,/* 2 Vpp */ .path1_mode = 3, .tun1_type = 3, .set_lock_led = dw210x_led_ctrl, }; static struct ds3000_config su3000_ds3000_config = { .demod_address = 0x68, .ci_mode = 1, .set_lock_led = dw210x_led_ctrl, }; static struct cxd2820r_config cxd2820r_config = { .i2c_address = 0x6c, /* (0xd8 >> 1) */ .ts_mode = 0x38, .ts_clock_inv = 1, }; static struct tda18271_config tda18271_config = { .output_opt = TDA18271_OUTPUT_LT_OFF, .gate = TDA18271_GATE_DIGITAL, }; static u8 m88rs2000_inittab[] = { DEMOD_WRITE, 0x9a, 0x30, DEMOD_WRITE, 0x00, 0x01, WRITE_DELAY, 0x19, 0x00, DEMOD_WRITE, 0x00, 0x00, DEMOD_WRITE, 0x9a, 0xb0, DEMOD_WRITE, 0x81, 0xc1, DEMOD_WRITE, 0x81, 0x81, DEMOD_WRITE, 0x86, 0xc6, DEMOD_WRITE, 0x9a, 0x30, DEMOD_WRITE, 0xf0, 0x80, DEMOD_WRITE, 0xf1, 0xbf, DEMOD_WRITE, 0xb0, 0x45, DEMOD_WRITE, 0xb2, 0x01, DEMOD_WRITE, 0x9a, 0xb0, 0xff, 0xaa, 0xff }; static struct m88rs2000_config s421_m88rs2000_config = { .demod_addr = 0x68, .inittab = m88rs2000_inittab, }; static int dw2104_frontend_attach(struct dvb_usb_adapter *d) { struct dvb_tuner_ops *tuner_ops = NULL; if (demod_probe & 4) { d->fe_adap[0].fe = dvb_attach(stv0900_attach, &dw2104a_stv0900_config, &d->dev->i2c_adap, 0); if (d->fe_adap[0].fe != NULL) { if (dvb_attach(stb6100_attach, d->fe_adap[0].fe, &dw2104a_stb6100_config, &d->dev->i2c_adap)) { tuner_ops = &d->fe_adap[0].fe->ops.tuner_ops; tuner_ops->set_frequency = stb6100_set_freq; tuner_ops->get_frequency = stb6100_get_freq; tuner_ops->set_bandwidth = stb6100_set_bandw; tuner_ops->get_bandwidth = stb6100_get_bandw; d->fe_adap[0].fe->ops.set_voltage = dw210x_set_voltage; info("Attached STV0900+STB6100!"); return 0; } } } if (demod_probe & 2) { d->fe_adap[0].fe = dvb_attach(stv0900_attach, &dw2104_stv0900_config, &d->dev->i2c_adap, 0); if (d->fe_adap[0].fe != NULL) { if (dvb_attach(stv6110_attach, d->fe_adap[0].fe, &dw2104_stv6110_config, &d->dev->i2c_adap)) { d->fe_adap[0].fe->ops.set_voltage = dw210x_set_voltage; info("Attached STV0900+STV6110A!"); return 0; } } } if (demod_probe & 1) { d->fe_adap[0].fe = dvb_attach(cx24116_attach, &dw2104_config, &d->dev->i2c_adap); if (d->fe_adap[0].fe != NULL) { d->fe_adap[0].fe->ops.set_voltage = dw210x_set_voltage; info("Attached cx24116!"); return 0; } } d->fe_adap[0].fe = dvb_attach(ds3000_attach, &dw2104_ds3000_config, &d->dev->i2c_adap); if (d->fe_adap[0].fe != NULL) { dvb_attach(ts2020_attach, d->fe_adap[0].fe, &dw2104_ts2020_config, &d->dev->i2c_adap); d->fe_adap[0].fe->ops.set_voltage = dw210x_set_voltage; info("Attached DS3000!"); return 0; } return -EIO; } static struct dvb_usb_device_properties dw2102_properties; static struct dvb_usb_device_properties dw2104_properties; static struct dvb_usb_device_properties s6x0_properties; static int dw2102_frontend_attach(struct dvb_usb_adapter *d) { if (dw2102_properties.i2c_algo == &dw2102_serit_i2c_algo) { /*dw2102_properties.adapter->tuner_attach = NULL;*/ d->fe_adap[0].fe = dvb_attach(si21xx_attach, &serit_sp1511lhb_config, &d->dev->i2c_adap); if (d->fe_adap[0].fe != NULL) { d->fe_adap[0].fe->ops.set_voltage = dw210x_set_voltage; info("Attached si21xx!"); return 0; } } if (dw2102_properties.i2c_algo == &dw2102_earda_i2c_algo) { d->fe_adap[0].fe = dvb_attach(stv0288_attach, &earda_config, &d->dev->i2c_adap); if (d->fe_adap[0].fe != NULL) { if (dvb_attach(stb6000_attach, d->fe_adap[0].fe, 0x61, &d->dev->i2c_adap)) { d->fe_adap[0].fe->ops.set_voltage = dw210x_set_voltage; info("Attached stv0288!"); return 0; } } } if (dw2102_properties.i2c_algo == &dw2102_i2c_algo) { /*dw2102_properties.adapter->tuner_attach = dw2102_tuner_attach;*/ d->fe_adap[0].fe = dvb_attach(stv0299_attach, &sharp_z0194a_config, &d->dev->i2c_adap); if (d->fe_adap[0].fe != NULL) { d->fe_adap[0].fe->ops.set_voltage = dw210x_set_voltage; info("Attached stv0299!"); return 0; } } return -EIO; } static int dw3101_frontend_attach(struct dvb_usb_adapter *d) { d->fe_adap[0].fe = dvb_attach(tda10023_attach, &dw3101_tda10023_config, &d->dev->i2c_adap, 0x48); if (d->fe_adap[0].fe != NULL) { info("Attached tda10023!"); return 0; } return -EIO; } static int zl100313_frontend_attach(struct dvb_usb_adapter *d) { d->fe_adap[0].fe = dvb_attach(mt312_attach, &zl313_config, &d->dev->i2c_adap); if (d->fe_adap[0].fe != NULL) { if (dvb_attach(zl10039_attach, d->fe_adap[0].fe, 0x60, &d->dev->i2c_adap)) { d->fe_adap[0].fe->ops.set_voltage = dw210x_set_voltage; info("Attached zl100313+zl10039!"); return 0; } } return -EIO; } static int stv0288_frontend_attach(struct dvb_usb_adapter *d) { u8 obuf[] = {7, 1}; d->fe_adap[0].fe = dvb_attach(stv0288_attach, &earda_config, &d->dev->i2c_adap); if (d->fe_adap[0].fe == NULL) return -EIO; if (NULL == dvb_attach(stb6000_attach, d->fe_adap[0].fe, 0x61, &d->dev->i2c_adap)) return -EIO; d->fe_adap[0].fe->ops.set_voltage = dw210x_set_voltage; dw210x_op_rw(d->dev->udev, 0x8a, 0, 0, obuf, 2, DW210X_WRITE_MSG); info("Attached stv0288+stb6000!"); return 0; } static int ds3000_frontend_attach(struct dvb_usb_adapter *d) { struct dw2102_state *st = d->dev->priv; u8 obuf[] = {7, 1}; d->fe_adap[0].fe = dvb_attach(ds3000_attach, &s660_ds3000_config, &d->dev->i2c_adap); if (d->fe_adap[0].fe == NULL) return -EIO; dvb_attach(ts2020_attach, d->fe_adap[0].fe, &s660_ts2020_config, &d->dev->i2c_adap); st->old_set_voltage = d->fe_adap[0].fe->ops.set_voltage; d->fe_adap[0].fe->ops.set_voltage = s660_set_voltage; dw210x_op_rw(d->dev->udev, 0x8a, 0, 0, obuf, 2, DW210X_WRITE_MSG); info("Attached ds3000+ts2020!"); return 0; } static int prof_7500_frontend_attach(struct dvb_usb_adapter *d) { u8 obuf[] = {7, 1}; d->fe_adap[0].fe = dvb_attach(stv0900_attach, &prof_7500_stv0900_config, &d->dev->i2c_adap, 0); if (d->fe_adap[0].fe == NULL) return -EIO; d->fe_adap[0].fe->ops.set_voltage = dw210x_set_voltage; dw210x_op_rw(d->dev->udev, 0x8a, 0, 0, obuf, 2, DW210X_WRITE_MSG); info("Attached STV0900+STB6100A!"); return 0; } static int su3000_frontend_attach(struct dvb_usb_adapter *adap) { struct dvb_usb_device *d = adap->dev; struct dw2102_state *state = d->priv; mutex_lock(&d->data_mutex); state->data[0] = 0xe; state->data[1] = 0x80; state->data[2] = 0; if (dvb_usb_generic_rw(d, state->data, 3, state->data, 1, 0) < 0) err("command 0x0e transfer failed."); state->data[0] = 0xe; state->data[1] = 0x02; state->data[2] = 1; if (dvb_usb_generic_rw(d, state->data, 3, state->data, 1, 0) < 0) err("command 0x0e transfer failed."); msleep(300); state->data[0] = 0xe; state->data[1] = 0x83; state->data[2] = 0; if (dvb_usb_generic_rw(d, state->data, 3, state->data, 1, 0) < 0) err("command 0x0e transfer failed."); state->data[0] = 0xe; state->data[1] = 0x83; state->data[2] = 1; if (dvb_usb_generic_rw(d, state->data, 3, state->data, 1, 0) < 0) err("command 0x0e transfer failed."); state->data[0] = 0x51; if (dvb_usb_generic_rw(d, state->data, 1, state->data, 1, 0) < 0) err("command 0x51 transfer failed."); mutex_unlock(&d->data_mutex); adap->fe_adap[0].fe = dvb_attach(ds3000_attach, &su3000_ds3000_config, &d->i2c_adap); if (adap->fe_adap[0].fe == NULL) return -EIO; if (dvb_attach(ts2020_attach, adap->fe_adap[0].fe, &dw2104_ts2020_config, &d->i2c_adap)) { info("Attached DS3000/TS2020!"); return 0; } info("Failed to attach DS3000/TS2020!"); return -EIO; } static int t220_frontend_attach(struct dvb_usb_adapter *adap) { struct dvb_usb_device *d = adap->dev; struct dw2102_state *state = d->priv; mutex_lock(&d->data_mutex); state->data[0] = 0xe; state->data[1] = 0x87; state->data[2] = 0x0; if (dvb_usb_generic_rw(d, state->data, 3, state->data, 1, 0) < 0) err("command 0x0e transfer failed."); state->data[0] = 0xe; state->data[1] = 0x86; state->data[2] = 1; if (dvb_usb_generic_rw(d, state->data, 3, state->data, 1, 0) < 0) err("command 0x0e transfer failed."); state->data[0] = 0xe; state->data[1] = 0x80; state->data[2] = 0; if (dvb_usb_generic_rw(d, state->data, 3, state->data, 1, 0) < 0) err("command 0x0e transfer failed."); msleep(50); state->data[0] = 0xe; state->data[1] = 0x80; state->data[2] = 1; if (dvb_usb_generic_rw(d, state->data, 3, state->data, 1, 0) < 0) err("command 0x0e transfer failed."); state->data[0] = 0x51; if (dvb_usb_generic_rw(d, state->data, 1, state->data, 1, 0) < 0) err("command 0x51 transfer failed."); mutex_unlock(&d->data_mutex); adap->fe_adap[0].fe = dvb_attach(cxd2820r_attach, &cxd2820r_config, &d->i2c_adap, NULL); if (adap->fe_adap[0].fe != NULL) { if (dvb_attach(tda18271_attach, adap->fe_adap[0].fe, 0x60, &d->i2c_adap, &tda18271_config)) { info("Attached TDA18271HD/CXD2820R!"); return 0; } } info("Failed to attach TDA18271HD/CXD2820R!"); return -EIO; } static int m88rs2000_frontend_attach(struct dvb_usb_adapter *adap) { struct dvb_usb_device *d = adap->dev; struct dw2102_state *state = d->priv; mutex_lock(&d->data_mutex); state->data[0] = 0x51; if (dvb_usb_generic_rw(d, state->data, 1, state->data, 1, 0) < 0) err("command 0x51 transfer failed."); mutex_unlock(&d->data_mutex); adap->fe_adap[0].fe = dvb_attach(m88rs2000_attach, &s421_m88rs2000_config, &d->i2c_adap); if (adap->fe_adap[0].fe == NULL) return -EIO; if (dvb_attach(ts2020_attach, adap->fe_adap[0].fe, &dw2104_ts2020_config, &d->i2c_adap)) { info("Attached RS2000/TS2020!"); return 0; } info("Failed to attach RS2000/TS2020!"); return -EIO; } static int tt_s2_4600_frontend_attach(struct dvb_usb_adapter *adap) { struct dvb_usb_device *d = adap->dev; struct dw2102_state *state = d->priv; struct i2c_adapter *i2c_adapter; struct i2c_client *client; struct i2c_board_info board_info; struct m88ds3103_platform_data m88ds3103_pdata = {}; struct ts2020_config ts2020_config = {}; mutex_lock(&d->data_mutex); state->data[0] = 0xe; state->data[1] = 0x80; state->data[2] = 0x0; if (dvb_usb_generic_rw(d, state->data, 3, state->data, 1, 0) < 0) err("command 0x0e transfer failed."); state->data[0] = 0xe; state->data[1] = 0x02; state->data[2] = 1; if (dvb_usb_generic_rw(d, state->data, 3, state->data, 1, 0) < 0) err("command 0x0e transfer failed."); msleep(300); state->data[0] = 0xe; state->data[1] = 0x83; state->data[2] = 0; if (dvb_usb_generic_rw(d, state->data, 3, state->data, 1, 0) < 0) err("command 0x0e transfer failed."); state->data[0] = 0xe; state->data[1] = 0x83; state->data[2] = 1; if (dvb_usb_generic_rw(d, state->data, 3, state->data, 1, 0) < 0) err("command 0x0e transfer failed."); state->data[0] = 0x51; if (dvb_usb_generic_rw(d, state->data, 1, state->data, 1, 0) < 0) err("command 0x51 transfer failed."); mutex_unlock(&d->data_mutex); /* attach demod */ m88ds3103_pdata.clk = 27000000; m88ds3103_pdata.i2c_wr_max = 33; m88ds3103_pdata.ts_mode = M88DS3103_TS_CI; m88ds3103_pdata.ts_clk = 16000; m88ds3103_pdata.ts_clk_pol = 0; m88ds3103_pdata.spec_inv = 0; m88ds3103_pdata.agc = 0x99; m88ds3103_pdata.agc_inv = 0; m88ds3103_pdata.clk_out = M88DS3103_CLOCK_OUT_ENABLED; m88ds3103_pdata.envelope_mode = 0; m88ds3103_pdata.lnb_hv_pol = 1; m88ds3103_pdata.lnb_en_pol = 0; memset(&board_info, 0, sizeof(board_info)); strlcpy(board_info.type, "m88ds3103", I2C_NAME_SIZE); board_info.addr = 0x68; board_info.platform_data = &m88ds3103_pdata; request_module("m88ds3103"); client = i2c_new_device(&d->i2c_adap, &board_info); if (client == NULL || client->dev.driver == NULL) return -ENODEV; if (!try_module_get(client->dev.driver->owner)) { i2c_unregister_device(client); return -ENODEV; } adap->fe_adap[0].fe = m88ds3103_pdata.get_dvb_frontend(client); i2c_adapter = m88ds3103_pdata.get_i2c_adapter(client); state->i2c_client_demod = client; /* attach tuner */ ts2020_config.fe = adap->fe_adap[0].fe; memset(&board_info, 0, sizeof(board_info)); strlcpy(board_info.type, "ts2022", I2C_NAME_SIZE); board_info.addr = 0x60; board_info.platform_data = &ts2020_config; request_module("ts2020"); client = i2c_new_device(i2c_adapter, &board_info); if (client == NULL || client->dev.driver == NULL) { dvb_frontend_detach(adap->fe_adap[0].fe); return -ENODEV; } if (!try_module_get(client->dev.driver->owner)) { i2c_unregister_device(client); dvb_frontend_detach(adap->fe_adap[0].fe); return -ENODEV; } /* delegate signal strength measurement to tuner */ adap->fe_adap[0].fe->ops.read_signal_strength = adap->fe_adap[0].fe->ops.tuner_ops.get_rf_strength; state->i2c_client_tuner = client; /* hook fe: need to resync the slave fifo when signal locks */ state->fe_read_status = adap->fe_adap[0].fe->ops.read_status; adap->fe_adap[0].fe->ops.read_status = tt_s2_4600_read_status; state->last_lock = 0; return 0; } static int dw2102_tuner_attach(struct dvb_usb_adapter *adap) { dvb_attach(dvb_pll_attach, adap->fe_adap[0].fe, 0x60, &adap->dev->i2c_adap, DVB_PLL_OPERA1); return 0; } static int dw3101_tuner_attach(struct dvb_usb_adapter *adap) { dvb_attach(dvb_pll_attach, adap->fe_adap[0].fe, 0x60, &adap->dev->i2c_adap, DVB_PLL_TUA6034); return 0; } static int dw2102_rc_query(struct dvb_usb_device *d) { u8 key[2]; struct i2c_msg msg = { .addr = DW2102_RC_QUERY, .flags = I2C_M_RD, .buf = key, .len = 2 }; if (d->props.i2c_algo->master_xfer(&d->i2c_adap, &msg, 1) == 1) { if (msg.buf[0] != 0xff) { deb_rc("%s: rc code: %x, %x\n", __func__, key[0], key[1]); rc_keydown(d->rc_dev, RC_TYPE_UNKNOWN, key[0], 0); } } return 0; } static int prof_rc_query(struct dvb_usb_device *d) { u8 key[2]; struct i2c_msg msg = { .addr = DW2102_RC_QUERY, .flags = I2C_M_RD, .buf = key, .len = 2 }; if (d->props.i2c_algo->master_xfer(&d->i2c_adap, &msg, 1) == 1) { if (msg.buf[0] != 0xff) { deb_rc("%s: rc code: %x, %x\n", __func__, key[0], key[1]); rc_keydown(d->rc_dev, RC_TYPE_UNKNOWN, key[0]^0xff, 0); } } return 0; } static int su3000_rc_query(struct dvb_usb_device *d) { u8 key[2]; struct i2c_msg msg = { .addr = DW2102_RC_QUERY, .flags = I2C_M_RD, .buf = key, .len = 2 }; if (d->props.i2c_algo->master_xfer(&d->i2c_adap, &msg, 1) == 1) { if (msg.buf[0] != 0xff) { deb_rc("%s: rc code: %x, %x\n", __func__, key[0], key[1]); rc_keydown(d->rc_dev, RC_TYPE_RC5, RC_SCANCODE_RC5(key[1], key[0]), 0); } } return 0; } enum dw2102_table_entry { CYPRESS_DW2102, CYPRESS_DW2101, CYPRESS_DW2104, TEVII_S650, TERRATEC_CINERGY_S, CYPRESS_DW3101, TEVII_S630, PROF_1100, TEVII_S660, PROF_7500, GENIATECH_SU3000, TERRATEC_CINERGY_S2, TEVII_S480_1, TEVII_S480_2, X3M_SPC1400HD, TEVII_S421, TEVII_S632, TERRATEC_CINERGY_S2_R2, TERRATEC_CINERGY_S2_R3, TERRATEC_CINERGY_S2_R4, GOTVIEW_SAT_HD, GENIATECH_T220, TECHNOTREND_S2_4600, TEVII_S482_1, TEVII_S482_2, TERRATEC_CINERGY_S2_BOX, TEVII_S662 }; static struct usb_device_id dw2102_table[] = { [CYPRESS_DW2102] = {USB_DEVICE(USB_VID_CYPRESS, USB_PID_DW2102)}, [CYPRESS_DW2101] = {USB_DEVICE(USB_VID_CYPRESS, 0x2101)}, [CYPRESS_DW2104] = {USB_DEVICE(USB_VID_CYPRESS, USB_PID_DW2104)}, [TEVII_S650] = {USB_DEVICE(0x9022, USB_PID_TEVII_S650)}, [TERRATEC_CINERGY_S] = {USB_DEVICE(USB_VID_TERRATEC, USB_PID_TERRATEC_CINERGY_S)}, [CYPRESS_DW3101] = {USB_DEVICE(USB_VID_CYPRESS, USB_PID_DW3101)}, [TEVII_S630] = {USB_DEVICE(0x9022, USB_PID_TEVII_S630)}, [PROF_1100] = {USB_DEVICE(0x3011, USB_PID_PROF_1100)}, [TEVII_S660] = {USB_DEVICE(0x9022, USB_PID_TEVII_S660)}, [PROF_7500] = {USB_DEVICE(0x3034, 0x7500)}, [GENIATECH_SU3000] = {USB_DEVICE(0x1f4d, 0x3000)}, [TERRATEC_CINERGY_S2] = {USB_DEVICE(USB_VID_TERRATEC, USB_PID_TERRATEC_CINERGY_S2_R1)}, [TEVII_S480_1] = {USB_DEVICE(0x9022, USB_PID_TEVII_S480_1)}, [TEVII_S480_2] = {USB_DEVICE(0x9022, USB_PID_TEVII_S480_2)}, [X3M_SPC1400HD] = {USB_DEVICE(0x1f4d, 0x3100)}, [TEVII_S421] = {USB_DEVICE(0x9022, USB_PID_TEVII_S421)}, [TEVII_S632] = {USB_DEVICE(0x9022, USB_PID_TEVII_S632)}, [TERRATEC_CINERGY_S2_R2] = {USB_DEVICE(USB_VID_TERRATEC, USB_PID_TERRATEC_CINERGY_S2_R2)}, [TERRATEC_CINERGY_S2_R3] = {USB_DEVICE(USB_VID_TERRATEC, USB_PID_TERRATEC_CINERGY_S2_R3)}, [TERRATEC_CINERGY_S2_R4] = {USB_DEVICE(USB_VID_TERRATEC, USB_PID_TERRATEC_CINERGY_S2_R4)}, [GOTVIEW_SAT_HD] = {USB_DEVICE(0x1FE1, USB_PID_GOTVIEW_SAT_HD)}, [GENIATECH_T220] = {USB_DEVICE(0x1f4d, 0xD220)}, [TECHNOTREND_S2_4600] = {USB_DEVICE(USB_VID_TECHNOTREND, USB_PID_TECHNOTREND_CONNECT_S2_4600)}, [TEVII_S482_1] = {USB_DEVICE(0x9022, 0xd483)}, [TEVII_S482_2] = {USB_DEVICE(0x9022, 0xd484)}, [TERRATEC_CINERGY_S2_BOX] = {USB_DEVICE(USB_VID_TERRATEC, 0x0105)}, [TEVII_S662] = {USB_DEVICE(0x9022, USB_PID_TEVII_S662)}, { } }; MODULE_DEVICE_TABLE(usb, dw2102_table); static int dw2102_load_firmware(struct usb_device *dev, const struct firmware *frmwr) { u8 *b, *p; int ret = 0, i; u8 reset; u8 reset16[] = {0, 0, 0, 0, 0, 0, 0}; const struct firmware *fw; switch (le16_to_cpu(dev->descriptor.idProduct)) { case 0x2101: ret = request_firmware(&fw, DW2101_FIRMWARE, &dev->dev); if (ret != 0) { err(err_str, DW2101_FIRMWARE); return ret; } break; default: fw = frmwr; break; } info("start downloading DW210X firmware"); p = kmalloc(fw->size, GFP_KERNEL); reset = 1; /*stop the CPU*/ dw210x_op_rw(dev, 0xa0, 0x7f92, 0, &reset, 1, DW210X_WRITE_MSG); dw210x_op_rw(dev, 0xa0, 0xe600, 0, &reset, 1, DW210X_WRITE_MSG); if (p != NULL) { memcpy(p, fw->data, fw->size); for (i = 0; i < fw->size; i += 0x40) { b = (u8 *) p + i; if (dw210x_op_rw(dev, 0xa0, i, 0, b , 0x40, DW210X_WRITE_MSG) != 0x40) { err("error while transferring firmware"); ret = -EINVAL; break; } } /* restart the CPU */ reset = 0; if (ret || dw210x_op_rw(dev, 0xa0, 0x7f92, 0, &reset, 1, DW210X_WRITE_MSG) != 1) { err("could not restart the USB controller CPU."); ret = -EINVAL; } if (ret || dw210x_op_rw(dev, 0xa0, 0xe600, 0, &reset, 1, DW210X_WRITE_MSG) != 1) { err("could not restart the USB controller CPU."); ret = -EINVAL; } /* init registers */ switch (le16_to_cpu(dev->descriptor.idProduct)) { case USB_PID_TEVII_S650: dw2104_properties.rc.core.rc_codes = RC_MAP_TEVII_NEC; case USB_PID_DW2104: reset = 1; dw210x_op_rw(dev, 0xc4, 0x0000, 0, &reset, 1, DW210X_WRITE_MSG); /* break omitted intentionally */ case USB_PID_DW3101: reset = 0; dw210x_op_rw(dev, 0xbf, 0x0040, 0, &reset, 0, DW210X_WRITE_MSG); break; case USB_PID_TERRATEC_CINERGY_S: case USB_PID_DW2102: dw210x_op_rw(dev, 0xbf, 0x0040, 0, &reset, 0, DW210X_WRITE_MSG); dw210x_op_rw(dev, 0xb9, 0x0000, 0, &reset16[0], 2, DW210X_READ_MSG); /* check STV0299 frontend */ dw210x_op_rw(dev, 0xb5, 0, 0, &reset16[0], 2, DW210X_READ_MSG); if ((reset16[0] == 0xa1) || (reset16[0] == 0x80)) { dw2102_properties.i2c_algo = &dw2102_i2c_algo; dw2102_properties.adapter->fe[0].tuner_attach = &dw2102_tuner_attach; break; } else { /* check STV0288 frontend */ reset16[0] = 0xd0; reset16[1] = 1; reset16[2] = 0; dw210x_op_rw(dev, 0xc2, 0, 0, &reset16[0], 3, DW210X_WRITE_MSG); dw210x_op_rw(dev, 0xc3, 0xd1, 0, &reset16[0], 3, DW210X_READ_MSG); if (reset16[2] == 0x11) { dw2102_properties.i2c_algo = &dw2102_earda_i2c_algo; break; } } case 0x2101: dw210x_op_rw(dev, 0xbc, 0x0030, 0, &reset16[0], 2, DW210X_READ_MSG); dw210x_op_rw(dev, 0xba, 0x0000, 0, &reset16[0], 7, DW210X_READ_MSG); dw210x_op_rw(dev, 0xba, 0x0000, 0, &reset16[0], 7, DW210X_READ_MSG); dw210x_op_rw(dev, 0xb9, 0x0000, 0, &reset16[0], 2, DW210X_READ_MSG); break; } msleep(100); kfree(p); } if (le16_to_cpu(dev->descriptor.idProduct) == 0x2101) release_firmware(fw); return ret; } static struct dvb_usb_device_properties dw2102_properties = { .caps = DVB_USB_IS_AN_I2C_ADAPTER, .usb_ctrl = DEVICE_SPECIFIC, .firmware = DW2102_FIRMWARE, .no_reconnect = 1, .i2c_algo = &dw2102_serit_i2c_algo, .rc.core = { .rc_interval = 150, .rc_codes = RC_MAP_DM1105_NEC, .module_name = "dw2102", .allowed_protos = RC_BIT_NEC, .rc_query = dw2102_rc_query, }, .generic_bulk_ctrl_endpoint = 0x81, /* parameter for the MPEG2-data transfer */ .num_adapters = 1, .download_firmware = dw2102_load_firmware, .read_mac_address = dw210x_read_mac_address, .adapter = { { .num_frontends = 1, .fe = {{ .frontend_attach = dw2102_frontend_attach, .stream = { .type = USB_BULK, .count = 8, .endpoint = 0x82, .u = { .bulk = { .buffersize = 4096, } } }, }}, } }, .num_device_descs = 3, .devices = { {"DVBWorld DVB-S 2102 USB2.0", {&dw2102_table[CYPRESS_DW2102], NULL}, {NULL}, }, {"DVBWorld DVB-S 2101 USB2.0", {&dw2102_table[CYPRESS_DW2101], NULL}, {NULL}, }, {"TerraTec Cinergy S USB", {&dw2102_table[TERRATEC_CINERGY_S], NULL}, {NULL}, }, } }; static struct dvb_usb_device_properties dw2104_properties = { .caps = DVB_USB_IS_AN_I2C_ADAPTER, .usb_ctrl = DEVICE_SPECIFIC, .firmware = DW2104_FIRMWARE, .no_reconnect = 1, .i2c_algo = &dw2104_i2c_algo, .rc.core = { .rc_interval = 150, .rc_codes = RC_MAP_DM1105_NEC, .module_name = "dw2102", .allowed_protos = RC_BIT_NEC, .rc_query = dw2102_rc_query, }, .generic_bulk_ctrl_endpoint = 0x81, /* parameter for the MPEG2-data transfer */ .num_adapters = 1, .download_firmware = dw2102_load_firmware, .read_mac_address = dw210x_read_mac_address, .adapter = { { .num_frontends = 1, .fe = {{ .frontend_attach = dw2104_frontend_attach, .stream = { .type = USB_BULK, .count = 8, .endpoint = 0x82, .u = { .bulk = { .buffersize = 4096, } } }, }}, } }, .num_device_descs = 2, .devices = { { "DVBWorld DW2104 USB2.0", {&dw2102_table[CYPRESS_DW2104], NULL}, {NULL}, }, { "TeVii S650 USB2.0", {&dw2102_table[TEVII_S650], NULL}, {NULL}, }, } }; static struct dvb_usb_device_properties dw3101_properties = { .caps = DVB_USB_IS_AN_I2C_ADAPTER, .usb_ctrl = DEVICE_SPECIFIC, .firmware = DW3101_FIRMWARE, .no_reconnect = 1, .i2c_algo = &dw3101_i2c_algo, .rc.core = { .rc_interval = 150, .rc_codes = RC_MAP_DM1105_NEC, .module_name = "dw2102", .allowed_protos = RC_BIT_NEC, .rc_query = dw2102_rc_query, }, .generic_bulk_ctrl_endpoint = 0x81, /* parameter for the MPEG2-data transfer */ .num_adapters = 1, .download_firmware = dw2102_load_firmware, .read_mac_address = dw210x_read_mac_address, .adapter = { { .num_frontends = 1, .fe = {{ .frontend_attach = dw3101_frontend_attach, .tuner_attach = dw3101_tuner_attach, .stream = { .type = USB_BULK, .count = 8, .endpoint = 0x82, .u = { .bulk = { .buffersize = 4096, } } }, }}, } }, .num_device_descs = 1, .devices = { { "DVBWorld DVB-C 3101 USB2.0", {&dw2102_table[CYPRESS_DW3101], NULL}, {NULL}, }, } }; static struct dvb_usb_device_properties s6x0_properties = { .caps = DVB_USB_IS_AN_I2C_ADAPTER, .usb_ctrl = DEVICE_SPECIFIC, .size_of_priv = sizeof(struct dw2102_state), .firmware = S630_FIRMWARE, .no_reconnect = 1, .i2c_algo = &s6x0_i2c_algo, .rc.core = { .rc_interval = 150, .rc_codes = RC_MAP_TEVII_NEC, .module_name = "dw2102", .allowed_protos = RC_BIT_NEC, .rc_query = dw2102_rc_query, }, .generic_bulk_ctrl_endpoint = 0x81, .num_adapters = 1, .download_firmware = dw2102_load_firmware, .read_mac_address = s6x0_read_mac_address, .adapter = { { .num_frontends = 1, .fe = {{ .frontend_attach = zl100313_frontend_attach, .stream = { .type = USB_BULK, .count = 8, .endpoint = 0x82, .u = { .bulk = { .buffersize = 4096, } } }, }}, } }, .num_device_descs = 1, .devices = { {"TeVii S630 USB", {&dw2102_table[TEVII_S630], NULL}, {NULL}, }, } }; static struct dvb_usb_device_properties *p1100; static struct dvb_usb_device_description d1100 = { "Prof 1100 USB ", {&dw2102_table[PROF_1100], NULL}, {NULL}, }; static struct dvb_usb_device_properties *s660; static struct dvb_usb_device_description d660 = { "TeVii S660 USB", {&dw2102_table[TEVII_S660], NULL}, {NULL}, }; static struct dvb_usb_device_description d480_1 = { "TeVii S480.1 USB", {&dw2102_table[TEVII_S480_1], NULL}, {NULL}, }; static struct dvb_usb_device_description d480_2 = { "TeVii S480.2 USB", {&dw2102_table[TEVII_S480_2], NULL}, {NULL}, }; static struct dvb_usb_device_properties *p7500; static struct dvb_usb_device_description d7500 = { "Prof 7500 USB DVB-S2", {&dw2102_table[PROF_7500], NULL}, {NULL}, }; static struct dvb_usb_device_properties *s421; static struct dvb_usb_device_description d421 = { "TeVii S421 PCI", {&dw2102_table[TEVII_S421], NULL}, {NULL}, }; static struct dvb_usb_device_description d632 = { "TeVii S632 USB", {&dw2102_table[TEVII_S632], NULL}, {NULL}, }; static struct dvb_usb_device_properties su3000_properties = { .caps = DVB_USB_IS_AN_I2C_ADAPTER, .usb_ctrl = DEVICE_SPECIFIC, .size_of_priv = sizeof(struct dw2102_state), .power_ctrl = su3000_power_ctrl, .num_adapters = 1, .identify_state = su3000_identify_state, .i2c_algo = &su3000_i2c_algo, .rc.core = { .rc_interval = 150, .rc_codes = RC_MAP_SU3000, .module_name = "dw2102", .allowed_protos = RC_BIT_RC5, .rc_query = su3000_rc_query, }, .read_mac_address = su3000_read_mac_address, .generic_bulk_ctrl_endpoint = 0x01, .adapter = { { .num_frontends = 1, .fe = {{ .streaming_ctrl = su3000_streaming_ctrl, .frontend_attach = su3000_frontend_attach, .stream = { .type = USB_BULK, .count = 8, .endpoint = 0x82, .u = { .bulk = { .buffersize = 4096, } } } }}, } }, .num_device_descs = 6, .devices = { { "SU3000HD DVB-S USB2.0", { &dw2102_table[GENIATECH_SU3000], NULL }, { NULL }, }, { "Terratec Cinergy S2 USB HD", { &dw2102_table[TERRATEC_CINERGY_S2], NULL }, { NULL }, }, { "X3M TV SPC1400HD PCI", { &dw2102_table[X3M_SPC1400HD], NULL }, { NULL }, }, { "Terratec Cinergy S2 USB HD Rev.2", { &dw2102_table[TERRATEC_CINERGY_S2_R2], NULL }, { NULL }, }, { "Terratec Cinergy S2 USB HD Rev.3", { &dw2102_table[TERRATEC_CINERGY_S2_R3], NULL }, { NULL }, }, { "GOTVIEW Satellite HD", { &dw2102_table[GOTVIEW_SAT_HD], NULL }, { NULL }, }, } }; static struct dvb_usb_device_properties t220_properties = { .caps = DVB_USB_IS_AN_I2C_ADAPTER, .usb_ctrl = DEVICE_SPECIFIC, .size_of_priv = sizeof(struct dw2102_state), .power_ctrl = su3000_power_ctrl, .num_adapters = 1, .identify_state = su3000_identify_state, .i2c_algo = &su3000_i2c_algo, .rc.core = { .rc_interval = 150, .rc_codes = RC_MAP_SU3000, .module_name = "dw2102", .allowed_protos = RC_BIT_RC5, .rc_query = su3000_rc_query, }, .read_mac_address = su3000_read_mac_address, .generic_bulk_ctrl_endpoint = 0x01, .adapter = { { .num_frontends = 1, .fe = { { .streaming_ctrl = su3000_streaming_ctrl, .frontend_attach = t220_frontend_attach, .stream = { .type = USB_BULK, .count = 8, .endpoint = 0x82, .u = { .bulk = { .buffersize = 4096, } } } } }, } }, .num_device_descs = 1, .devices = { { "Geniatech T220 DVB-T/T2 USB2.0", { &dw2102_table[GENIATECH_T220], NULL }, { NULL }, }, } }; static struct dvb_usb_device_properties tt_s2_4600_properties = { .caps = DVB_USB_IS_AN_I2C_ADAPTER, .usb_ctrl = DEVICE_SPECIFIC, .size_of_priv = sizeof(struct dw2102_state), .power_ctrl = su3000_power_ctrl, .num_adapters = 1, .identify_state = su3000_identify_state, .i2c_algo = &su3000_i2c_algo, .rc.core = { .rc_interval = 250, .rc_codes = RC_MAP_TT_1500, .module_name = "dw2102", .allowed_protos = RC_BIT_RC5, .rc_query = su3000_rc_query, }, .read_mac_address = su3000_read_mac_address, .generic_bulk_ctrl_endpoint = 0x01, .adapter = { { .num_frontends = 1, .fe = {{ .streaming_ctrl = su3000_streaming_ctrl, .frontend_attach = tt_s2_4600_frontend_attach, .stream = { .type = USB_BULK, .count = 8, .endpoint = 0x82, .u = { .bulk = { .buffersize = 4096, } } } } }, } }, .num_device_descs = 5, .devices = { { "TechnoTrend TT-connect S2-4600", { &dw2102_table[TECHNOTREND_S2_4600], NULL }, { NULL }, }, { "TeVii S482 (tuner 1)", { &dw2102_table[TEVII_S482_1], NULL }, { NULL }, }, { "TeVii S482 (tuner 2)", { &dw2102_table[TEVII_S482_2], NULL }, { NULL }, }, { "Terratec Cinergy S2 USB BOX", { &dw2102_table[TERRATEC_CINERGY_S2_BOX], NULL }, { NULL }, }, { "TeVii S662", { &dw2102_table[TEVII_S662], NULL }, { NULL }, }, } }; static int dw2102_probe(struct usb_interface *intf, const struct usb_device_id *id) { p1100 = kmemdup(&s6x0_properties, sizeof(struct dvb_usb_device_properties), GFP_KERNEL); if (!p1100) return -ENOMEM; /* copy default structure */ /* fill only different fields */ p1100->firmware = P1100_FIRMWARE; p1100->devices[0] = d1100; p1100->rc.core.rc_query = prof_rc_query; p1100->rc.core.rc_codes = RC_MAP_TBS_NEC; p1100->adapter->fe[0].frontend_attach = stv0288_frontend_attach; s660 = kmemdup(&s6x0_properties, sizeof(struct dvb_usb_device_properties), GFP_KERNEL); if (!s660) { kfree(p1100); return -ENOMEM; } s660->firmware = S660_FIRMWARE; s660->num_device_descs = 3; s660->devices[0] = d660; s660->devices[1] = d480_1; s660->devices[2] = d480_2; s660->adapter->fe[0].frontend_attach = ds3000_frontend_attach; p7500 = kmemdup(&s6x0_properties, sizeof(struct dvb_usb_device_properties), GFP_KERNEL); if (!p7500) { kfree(p1100); kfree(s660); return -ENOMEM; } p7500->firmware = P7500_FIRMWARE; p7500->devices[0] = d7500; p7500->rc.core.rc_query = prof_rc_query; p7500->rc.core.rc_codes = RC_MAP_TBS_NEC; p7500->adapter->fe[0].frontend_attach = prof_7500_frontend_attach; s421 = kmemdup(&su3000_properties, sizeof(struct dvb_usb_device_properties), GFP_KERNEL); if (!s421) { kfree(p1100); kfree(s660); kfree(p7500); return -ENOMEM; } s421->num_device_descs = 2; s421->devices[0] = d421; s421->devices[1] = d632; s421->adapter->fe[0].frontend_attach = m88rs2000_frontend_attach; if (0 == dvb_usb_device_init(intf, &dw2102_properties, THIS_MODULE, NULL, adapter_nr) || 0 == dvb_usb_device_init(intf, &dw2104_properties, THIS_MODULE, NULL, adapter_nr) || 0 == dvb_usb_device_init(intf, &dw3101_properties, THIS_MODULE, NULL, adapter_nr) || 0 == dvb_usb_device_init(intf, &s6x0_properties, THIS_MODULE, NULL, adapter_nr) || 0 == dvb_usb_device_init(intf, p1100, THIS_MODULE, NULL, adapter_nr) || 0 == dvb_usb_device_init(intf, s660, THIS_MODULE, NULL, adapter_nr) || 0 == dvb_usb_device_init(intf, p7500, THIS_MODULE, NULL, adapter_nr) || 0 == dvb_usb_device_init(intf, s421, THIS_MODULE, NULL, adapter_nr) || 0 == dvb_usb_device_init(intf, &su3000_properties, THIS_MODULE, NULL, adapter_nr) || 0 == dvb_usb_device_init(intf, &t220_properties, THIS_MODULE, NULL, adapter_nr) || 0 == dvb_usb_device_init(intf, &tt_s2_4600_properties, THIS_MODULE, NULL, adapter_nr)) return 0; return -ENODEV; } static void dw2102_disconnect(struct usb_interface *intf) { struct dvb_usb_device *d = usb_get_intfdata(intf); struct dw2102_state *st = (struct dw2102_state *)d->priv; struct i2c_client *client; /* remove I2C client for tuner */ client = st->i2c_client_tuner; if (client) { module_put(client->dev.driver->owner); i2c_unregister_device(client); } /* remove I2C client for demodulator */ client = st->i2c_client_demod; if (client) { module_put(client->dev.driver->owner); i2c_unregister_device(client); } dvb_usb_device_exit(intf); } static struct usb_driver dw2102_driver = { .name = "dw2102", .probe = dw2102_probe, .disconnect = dw2102_disconnect, .id_table = dw2102_table, }; module_usb_driver(dw2102_driver); MODULE_AUTHOR("Igor M. Liplianin (c) liplianin@me.by"); MODULE_DESCRIPTION("Driver for DVBWorld DVB-S 2101, 2102, DVB-S2 2104, DVB-C 3101 USB2.0, TeVii S421, S480, S482, S600, S630, S632, S650, TeVii S660, S662, Prof 1100, 7500 USB2.0, Geniatech SU3000, T220, TechnoTrend S2-4600, Terratec Cinergy S2 devices"); MODULE_VERSION("0.1"); MODULE_LICENSE("GPL"); MODULE_FIRMWARE(DW2101_FIRMWARE); MODULE_FIRMWARE(DW2102_FIRMWARE); MODULE_FIRMWARE(DW2104_FIRMWARE); MODULE_FIRMWARE(DW3101_FIRMWARE); MODULE_FIRMWARE(S630_FIRMWARE); MODULE_FIRMWARE(S660_FIRMWARE); MODULE_FIRMWARE(P1100_FIRMWARE); MODULE_FIRMWARE(P7500_FIRMWARE);
./CrossVul/dataset_final_sorted/CWE-119/c/good_3311_0
crossvul-cpp_data_bad_3414_0
/* * XWD image format * * Copyright (c) 2012 Paul B Mahol * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <inttypes.h> #include "libavutil/imgutils.h" #include "avcodec.h" #include "bytestream.h" #include "internal.h" #include "xwd.h" static int xwd_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { AVFrame *p = data; const uint8_t *buf = avpkt->data; int i, ret, buf_size = avpkt->size; uint32_t version, header_size, vclass, ncolors; uint32_t xoffset, be, bpp, lsize, rsize; uint32_t pixformat, pixdepth, bunit, bitorder, bpad; uint32_t rgb[3]; uint8_t *ptr; GetByteContext gb; if (buf_size < XWD_HEADER_SIZE) return AVERROR_INVALIDDATA; bytestream2_init(&gb, buf, buf_size); header_size = bytestream2_get_be32u(&gb); version = bytestream2_get_be32u(&gb); if (version != XWD_VERSION) { av_log(avctx, AV_LOG_ERROR, "unsupported version\n"); return AVERROR_INVALIDDATA; } if (buf_size < header_size || header_size < XWD_HEADER_SIZE) { av_log(avctx, AV_LOG_ERROR, "invalid header size\n"); return AVERROR_INVALIDDATA; } pixformat = bytestream2_get_be32u(&gb); pixdepth = bytestream2_get_be32u(&gb); avctx->width = bytestream2_get_be32u(&gb); avctx->height = bytestream2_get_be32u(&gb); xoffset = bytestream2_get_be32u(&gb); be = bytestream2_get_be32u(&gb); bunit = bytestream2_get_be32u(&gb); bitorder = bytestream2_get_be32u(&gb); bpad = bytestream2_get_be32u(&gb); bpp = bytestream2_get_be32u(&gb); lsize = bytestream2_get_be32u(&gb); vclass = bytestream2_get_be32u(&gb); rgb[0] = bytestream2_get_be32u(&gb); rgb[1] = bytestream2_get_be32u(&gb); rgb[2] = bytestream2_get_be32u(&gb); bytestream2_skipu(&gb, 8); ncolors = bytestream2_get_be32u(&gb); bytestream2_skipu(&gb, header_size - (XWD_HEADER_SIZE - 20)); av_log(avctx, AV_LOG_DEBUG, "pixformat %"PRIu32", pixdepth %"PRIu32", bunit %"PRIu32", bitorder %"PRIu32", bpad %"PRIu32"\n", pixformat, pixdepth, bunit, bitorder, bpad); av_log(avctx, AV_LOG_DEBUG, "vclass %"PRIu32", ncolors %"PRIu32", bpp %"PRIu32", be %"PRIu32", lsize %"PRIu32", xoffset %"PRIu32"\n", vclass, ncolors, bpp, be, lsize, xoffset); av_log(avctx, AV_LOG_DEBUG, "red %0"PRIx32", green %0"PRIx32", blue %0"PRIx32"\n", rgb[0], rgb[1], rgb[2]); if (pixformat > XWD_Z_PIXMAP) { av_log(avctx, AV_LOG_ERROR, "invalid pixmap format\n"); return AVERROR_INVALIDDATA; } if (pixdepth == 0 || pixdepth > 32) { av_log(avctx, AV_LOG_ERROR, "invalid pixmap depth\n"); return AVERROR_INVALIDDATA; } if (xoffset) { avpriv_request_sample(avctx, "xoffset %"PRIu32"", xoffset); return AVERROR_PATCHWELCOME; } if (be > 1) { av_log(avctx, AV_LOG_ERROR, "invalid byte order\n"); return AVERROR_INVALIDDATA; } if (bitorder > 1) { av_log(avctx, AV_LOG_ERROR, "invalid bitmap bit order\n"); return AVERROR_INVALIDDATA; } if (bunit != 8 && bunit != 16 && bunit != 32) { av_log(avctx, AV_LOG_ERROR, "invalid bitmap unit\n"); return AVERROR_INVALIDDATA; } if (bpad != 8 && bpad != 16 && bpad != 32) { av_log(avctx, AV_LOG_ERROR, "invalid bitmap scan-line pad\n"); return AVERROR_INVALIDDATA; } if (bpp == 0 || bpp > 32) { av_log(avctx, AV_LOG_ERROR, "invalid bits per pixel\n"); return AVERROR_INVALIDDATA; } if (ncolors > 256) { av_log(avctx, AV_LOG_ERROR, "invalid number of entries in colormap\n"); return AVERROR_INVALIDDATA; } if ((ret = av_image_check_size(avctx->width, avctx->height, 0, NULL)) < 0) return ret; rsize = FFALIGN(avctx->width * bpp, bpad) / 8; if (lsize < rsize) { av_log(avctx, AV_LOG_ERROR, "invalid bytes per scan-line\n"); return AVERROR_INVALIDDATA; } if (bytestream2_get_bytes_left(&gb) < ncolors * XWD_CMAP_SIZE + (uint64_t)avctx->height * lsize) { av_log(avctx, AV_LOG_ERROR, "input buffer too small\n"); return AVERROR_INVALIDDATA; } if (pixformat != XWD_Z_PIXMAP) { avpriv_report_missing_feature(avctx, "Pixmap format %"PRIu32, pixformat); return AVERROR_PATCHWELCOME; } avctx->pix_fmt = AV_PIX_FMT_NONE; switch (vclass) { case XWD_STATIC_GRAY: case XWD_GRAY_SCALE: if (bpp != 1 && bpp != 8) return AVERROR_INVALIDDATA; if (pixdepth == 1) { avctx->pix_fmt = AV_PIX_FMT_MONOWHITE; } else if (pixdepth == 8) { avctx->pix_fmt = AV_PIX_FMT_GRAY8; } break; case XWD_STATIC_COLOR: case XWD_PSEUDO_COLOR: if (bpp == 8) avctx->pix_fmt = AV_PIX_FMT_PAL8; break; case XWD_TRUE_COLOR: case XWD_DIRECT_COLOR: if (bpp != 16 && bpp != 24 && bpp != 32) return AVERROR_INVALIDDATA; if (bpp == 16 && pixdepth == 15) { if (rgb[0] == 0x7C00 && rgb[1] == 0x3E0 && rgb[2] == 0x1F) avctx->pix_fmt = be ? AV_PIX_FMT_RGB555BE : AV_PIX_FMT_RGB555LE; else if (rgb[0] == 0x1F && rgb[1] == 0x3E0 && rgb[2] == 0x7C00) avctx->pix_fmt = be ? AV_PIX_FMT_BGR555BE : AV_PIX_FMT_BGR555LE; } else if (bpp == 16 && pixdepth == 16) { if (rgb[0] == 0xF800 && rgb[1] == 0x7E0 && rgb[2] == 0x1F) avctx->pix_fmt = be ? AV_PIX_FMT_RGB565BE : AV_PIX_FMT_RGB565LE; else if (rgb[0] == 0x1F && rgb[1] == 0x7E0 && rgb[2] == 0xF800) avctx->pix_fmt = be ? AV_PIX_FMT_BGR565BE : AV_PIX_FMT_BGR565LE; } else if (bpp == 24) { if (rgb[0] == 0xFF0000 && rgb[1] == 0xFF00 && rgb[2] == 0xFF) avctx->pix_fmt = be ? AV_PIX_FMT_RGB24 : AV_PIX_FMT_BGR24; else if (rgb[0] == 0xFF && rgb[1] == 0xFF00 && rgb[2] == 0xFF0000) avctx->pix_fmt = be ? AV_PIX_FMT_BGR24 : AV_PIX_FMT_RGB24; } else if (bpp == 32) { if (rgb[0] == 0xFF0000 && rgb[1] == 0xFF00 && rgb[2] == 0xFF) avctx->pix_fmt = be ? AV_PIX_FMT_ARGB : AV_PIX_FMT_BGRA; else if (rgb[0] == 0xFF && rgb[1] == 0xFF00 && rgb[2] == 0xFF0000) avctx->pix_fmt = be ? AV_PIX_FMT_ABGR : AV_PIX_FMT_RGBA; } bytestream2_skipu(&gb, ncolors * XWD_CMAP_SIZE); break; default: av_log(avctx, AV_LOG_ERROR, "invalid visual class\n"); return AVERROR_INVALIDDATA; } if (avctx->pix_fmt == AV_PIX_FMT_NONE) { avpriv_request_sample(avctx, "Unknown file: bpp %"PRIu32", pixdepth %"PRIu32", vclass %"PRIu32"", bpp, pixdepth, vclass); return AVERROR_PATCHWELCOME; } if ((ret = ff_get_buffer(avctx, p, 0)) < 0) return ret; p->key_frame = 1; p->pict_type = AV_PICTURE_TYPE_I; if (avctx->pix_fmt == AV_PIX_FMT_PAL8) { uint32_t *dst = (uint32_t *)p->data[1]; uint8_t red, green, blue; for (i = 0; i < ncolors; i++) { bytestream2_skipu(&gb, 4); // skip colormap entry number red = bytestream2_get_byteu(&gb); bytestream2_skipu(&gb, 1); green = bytestream2_get_byteu(&gb); bytestream2_skipu(&gb, 1); blue = bytestream2_get_byteu(&gb); bytestream2_skipu(&gb, 3); // skip bitmask flag and padding dst[i] = red << 16 | green << 8 | blue; } } ptr = p->data[0]; for (i = 0; i < avctx->height; i++) { bytestream2_get_bufferu(&gb, ptr, rsize); bytestream2_skipu(&gb, lsize - rsize); ptr += p->linesize[0]; } *got_frame = 1; return buf_size; } AVCodec ff_xwd_decoder = { .name = "xwd", .long_name = NULL_IF_CONFIG_SMALL("XWD (X Window Dump) image"), .type = AVMEDIA_TYPE_VIDEO, .id = AV_CODEC_ID_XWD, .decode = xwd_decode_frame, .capabilities = AV_CODEC_CAP_DR1, };
./CrossVul/dataset_final_sorted/CWE-119/c/bad_3414_0
crossvul-cpp_data_bad_343_0
/* * card-cac.c: Support for CAC from NIST SP800-73 * card-default.c: Support for cards with no driver * * Copyright (C) 2001, 2002 Juha Yrjölä <juha.yrjola@iki.fi> * Copyright (C) 2005,2006,2007,2008,2009,2010 Douglas E. Engert <deengert@anl.gov> * Copyright (C) 2006, Identity Alliance, Thomas Harning <thomas.harning@identityalliance.com> * Copyright (C) 2007, EMC, Russell Larner <rlarner@rsa.com> * Copyright (C) 2016 - 2018, Red Hat, Inc. * * CAC driver author: Robert Relyea <rrelyea@redhat.com> * Further work: Jakub Jelen <jjelen@redhat.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #include <ctype.h> #include <fcntl.h> #include <limits.h> #include <stdlib.h> #include <string.h> #ifdef _WIN32 #include <io.h> #else #include <unistd.h> #endif #ifdef ENABLE_OPENSSL /* openssl only needed for card administration */ #include <openssl/evp.h> #include <openssl/bio.h> #include <openssl/pem.h> #include <openssl/rand.h> #include <openssl/rsa.h> #endif /* ENABLE_OPENSSL */ #include "internal.h" #include "simpletlv.h" #include "cardctl.h" #ifdef ENABLE_ZLIB #include "compression.h" #endif #include "iso7816.h" #define CAC_MAX_SIZE 4096 /* arbitrary, just needs to be 'large enough' */ /* * CAC hardware and APDU constants */ #define CAC_MAX_CHUNK_SIZE 240 #define CAC_INS_SIGN_DECRYPT 0x42 /* A crypto operation */ #define CAC_INS_READ_FILE 0x52 /* read a TL or V file */ #define CAC_INS_GET_ACR 0x4c #define CAC_INS_GET_PROPERTIES 0x56 #define CAC_P1_STEP 0x80 #define CAC_P1_FINAL 0x00 #define CAC_FILE_TAG 1 #define CAC_FILE_VALUE 2 /* TAGS in a TL file */ #define CAC_TAG_CERTIFICATE 0x70 #define CAC_TAG_CERTINFO 0x71 #define CAC_TAG_MSCUID 0x72 #define CAC_TAG_CUID 0xF0 #define CAC_TAG_CC_VERSION_NUMBER 0xF1 #define CAC_TAG_GRAMMAR_VERION_NUMBER 0xF2 #define CAC_TAG_CARDURL 0xF3 #define CAC_TAG_PKCS15 0xF4 #define CAC_TAG_ACCESS_CONTROL 0xF6 #define CAC_TAG_DATA_MODEL 0xF5 #define CAC_TAG_CARD_APDU 0xF7 #define CAC_TAG_REDIRECTION 0xFA #define CAC_TAG_CAPABILITY_TUPLES 0xFB #define CAC_TAG_STATUS_TUPLES 0xFC #define CAC_TAG_NEXT_CCC 0xFD #define CAC_TAG_ERROR_CODES 0xFE #define CAC_TAG_APPLET_FAMILY 0x01 #define CAC_TAG_NUMBER_APPLETS 0x94 #define CAC_TAG_APPLET_ENTRY 0x93 #define CAC_TAG_APPLET_AID 0x92 #define CAC_TAG_APPLET_INFORMATION 0x01 #define CAC_TAG_NUMBER_OF_OBJECTS 0x40 #define CAC_TAG_TV_BUFFER 0x50 #define CAC_TAG_PKI_OBJECT 0x51 #define CAC_TAG_OBJECT_ID 0x41 #define CAC_TAG_BUFFER_PROPERTIES 0x42 #define CAC_TAG_PKI_PROPERTIES 0x43 #define CAC_APP_TYPE_GENERAL 0x01 #define CAC_APP_TYPE_SKI 0x02 #define CAC_APP_TYPE_PKI 0x04 #define CAC_ACR_ACR 0x00 #define CAC_ACR_APPLET_OBJECT 0x10 #define CAC_ACR_AMP 0x20 #define CAC_ACR_SERVICE 0x21 /* hardware data structures (returned in the CCC) */ /* part of the card_url */ typedef struct cac_access_profile { u8 GCACR_listID; u8 GCACR_readTagListACRID; u8 GCACR_updatevalueACRID; u8 GCACR_readvalueACRID; u8 GCACR_createACRID; u8 GCACR_deleteACRID; u8 CryptoACR_listID; u8 CryptoACR_getChallengeACRID; u8 CryptoACR_internalAuthenicateACRID; u8 CryptoACR_pkiComputeACRID; u8 CryptoACR_readTagListACRID; u8 CryptoACR_updatevalueACRID; u8 CryptoACR_readvalueACRID; u8 CryptoACR_createACRID; u8 CryptoACR_deleteACRID; } cac_access_profile_t; /* part of the card url */ typedef struct cac_access_key_info { u8 keyFileID[2]; u8 keynumber; } cac_access_key_info_t; typedef struct cac_card_url { u8 rid[5]; u8 cardApplicationType; u8 objectID[2]; u8 applicationID[2]; cac_access_profile_t accessProfile; u8 pinID; /* not used for VM cards */ cac_access_key_info_t accessKeyInfo; /* not used for VM cards */ u8 keyCryptoAlgorithm; /* not used for VM cards */ } cac_card_url_t; typedef struct cac_cuid { u8 gsc_rid[5]; u8 manufacturer_id; u8 card_type; u8 card_id; } cac_cuid_t; /* data structures to store meta data about CAC objects */ typedef struct cac_object { const char *name; int fd; sc_path_t path; } cac_object_t; #define CAC_MAX_OBJECTS 16 typedef struct { /* OID has two bytes */ unsigned char oid[2]; /* Format is NOT SimpleTLV? */ unsigned char simpletlv; /* Is certificate object and private key is initialized */ unsigned char privatekey; } cac_properties_object_t; typedef struct { unsigned int num_objects; cac_properties_object_t objects[CAC_MAX_OBJECTS]; } cac_properties_t; /* * Flags for Current Selected Object Type * CAC files are TLV files, with TL and V separated. For generic * containers we reintegrate the TL anv V portions into a single * file to read. Certs are also TLV files, but pkcs15 wants the * actual certificate. At select time we know the patch which tells * us what time of files we want to read. We remember that type * so that read_binary can do the appropriate processing. */ #define CAC_OBJECT_TYPE_CERT 1 #define CAC_OBJECT_TYPE_TLV_FILE 4 #define CAC_OBJECT_TYPE_GENERIC 5 /* * CAC private data per card state */ typedef struct cac_private_data { int object_type; /* select set this so we know how to read the file */ int cert_next; /* index number for the next certificate found in the list */ u8 *cache_buf; /* cached version of the currently selected file */ size_t cache_buf_len; /* length of the cached selected file */ int cached; /* is the cached selected file valid */ cac_cuid_t cuid; /* card unique ID from the CCC */ u8 *cac_id; /* card serial number */ size_t cac_id_len; /* card serial number len */ list_t pki_list; /* list of pki containers */ cac_object_t *pki_current; /* current pki object _ctl function */ list_t general_list; /* list of general containers */ cac_object_t *general_current; /* current object for _ctl function */ sc_path_t *aca_path; /* ACA path to be selected before pin verification */ } cac_private_data_t; #define CAC_DATA(card) ((cac_private_data_t*)card->drv_data) int cac_list_compare_path(const void *a, const void *b) { if (a == NULL || b == NULL) return 1; return memcmp( &((cac_object_t *) a)->path, &((cac_object_t *) b)->path, sizeof(sc_path_t)); } /* For SimCList autocopy, we need to know the size of the data elements */ size_t cac_list_meter(const void *el) { return sizeof(cac_object_t); } static cac_private_data_t *cac_new_private_data(void) { cac_private_data_t *priv; priv = calloc(1, sizeof(cac_private_data_t)); if (!priv) return NULL; list_init(&priv->pki_list); list_attributes_comparator(&priv->pki_list, cac_list_compare_path); list_attributes_copy(&priv->pki_list, cac_list_meter, 1); list_init(&priv->general_list); list_attributes_comparator(&priv->general_list, cac_list_compare_path); list_attributes_copy(&priv->general_list, cac_list_meter, 1); /* set other fields as appropriate */ return priv; } static void cac_free_private_data(cac_private_data_t *priv) { free(priv->cac_id); free(priv->cache_buf); free(priv->aca_path); list_destroy(&priv->pki_list); list_destroy(&priv->general_list); free(priv); return; } static int cac_add_object_to_list(list_t *list, const cac_object_t *object) { if (list_append(list, object) < 0) return SC_ERROR_UNKNOWN; return SC_SUCCESS; } /* * Set up the normal CAC paths */ #define CAC_TO_AID(x) x, sizeof(x)-1 #define CAC_2_RID "\xA0\x00\x00\x01\x16" #define CAC_1_RID "\xA0\x00\x00\x00\x79" static const sc_path_t cac_ACA_Path = { "", 0, 0,0,SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x10\x00") } }; static const sc_path_t cac_CCC_Path = { "", 0, 0,0,SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_2_RID "\xDB\x00") } }; #define MAX_CAC_SLOTS 16 /* Maximum number of slots is 16 now */ /* default certificate labels for the CAC card */ static const char *cac_labels[MAX_CAC_SLOTS] = { "CAC ID Certificate", "CAC Email Signature Certificate", "CAC Email Encryption Certificate", "CAC Cert 4", "CAC Cert 5", "CAC Cert 6", "CAC Cert 7", "CAC Cert 8", "CAC Cert 9", "CAC Cert 10", "CAC Cert 11", "CAC Cert 12", "CAC Cert 13", "CAC Cert 14", "CAC Cert 15", "CAC Cert 16" }; /* template for a CAC pki object */ static const cac_object_t cac_cac_pki_obj = { "CAC Certificate", 0x0, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x01\x00") } } }; /* template for emulated cuid */ static const cac_cuid_t cac_cac_cuid = { { 0xa0, 0x00, 0x00, 0x00, 0x79 }, 2, 2, 0 }; /* * CAC general objects defined in 4.3.1.2 of CAC Applet Developer Guide Version 1.0. * doubles as a source for CAC-2 labels. */ static const cac_object_t cac_objects[] = { { "Person Instance", 0x200, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\x00") }}}, { "Personnel", 0x201, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\x01") }}}, { "Benefits", 0x202, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\x02") }}}, { "Other Benefits", 0x203, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\x03") }}}, { "PKI Credential", 0x2FD, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\xFD") }}}, { "PKI Certificate", 0x2FE, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\xFE") }}}, }; static const int cac_object_count = sizeof(cac_objects)/sizeof(cac_objects[0]); /* * use the object id to find our object info on the object in our CAC-1 list */ static const cac_object_t *cac_find_obj_by_id(unsigned short object_id) { int i; for (i = 0; i < cac_object_count; i++) { if (cac_objects[i].fd == object_id) { return &cac_objects[i]; } } return NULL; } /* * Lookup the path in the pki list to see if it is a cert path */ static int cac_is_cert(cac_private_data_t * priv, const sc_path_t *in_path) { cac_object_t test_obj; test_obj.path = *in_path; test_obj.path.index = 0; test_obj.path.count = 0; return (list_contains(&priv->pki_list, &test_obj) != 0); } /* * Send a command and receive data. * * A caller may provide a buffer, and length to read. If not provided, * an internal 4096 byte buffer is used, and a copy is returned to the * caller. that need to be freed by the caller. * * modelled after a similar function in card-piv.c */ static int cac_apdu_io(sc_card_t *card, int ins, int p1, int p2, const u8 * sendbuf, size_t sendbuflen, u8 ** recvbuf, size_t * recvbuflen) { int r; sc_apdu_t apdu; u8 rbufinitbuf[CAC_MAX_SIZE]; u8 *rbuf; size_t rbuflen; unsigned int apdu_case = SC_APDU_CASE_1; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "%02x %02x %02x %"SC_FORMAT_LEN_SIZE_T"u : %"SC_FORMAT_LEN_SIZE_T"u %"SC_FORMAT_LEN_SIZE_T"u\n", ins, p1, p2, sendbuflen, card->max_send_size, card->max_recv_size); rbuf = rbufinitbuf; rbuflen = sizeof(rbufinitbuf); /* if caller provided a buffer and length */ if (recvbuf && *recvbuf && recvbuflen && *recvbuflen) { rbuf = *recvbuf; rbuflen = *recvbuflen; } if (recvbuf) { if (sendbuf) apdu_case = SC_APDU_CASE_4_SHORT; else apdu_case = SC_APDU_CASE_2_SHORT; } else if (sendbuf) apdu_case = SC_APDU_CASE_3_SHORT; sc_format_apdu(card, &apdu, apdu_case, ins, p1, p2); apdu.lc = sendbuflen; apdu.datalen = sendbuflen; apdu.data = sendbuf; if (recvbuf) { apdu.resp = rbuf; apdu.le = (rbuflen > 255) ? 255 : rbuflen; apdu.resplen = rbuflen; } else { apdu.resp = rbuf; apdu.le = 0; apdu.resplen = 0; } sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "calling sc_transmit_apdu flags=%lx le=%"SC_FORMAT_LEN_SIZE_T"u, resplen=%"SC_FORMAT_LEN_SIZE_T"u, resp=%p", apdu.flags, apdu.le, apdu.resplen, apdu.resp); /* with new adpu.c and chaining, this actually reads the whole object */ r = sc_transmit_apdu(card, &apdu); sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "result r=%d apdu.resplen=%"SC_FORMAT_LEN_SIZE_T"u sw1=%02x sw2=%02x", r, apdu.resplen, apdu.sw1, apdu.sw2); if (r < 0) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,"Transmit failed"); goto err; } r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r < 0) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Card returned error "); goto err; } if (recvbuflen) { if (recvbuf && *recvbuf == NULL) { *recvbuf = malloc(apdu.resplen); if (*recvbuf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto err; } memcpy(*recvbuf, rbuf, apdu.resplen); } *recvbuflen = apdu.resplen; r = *recvbuflen; } err: SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } /* * Get ACR of currently ACA applet identified by the acr_type * 5.3.3.5 Get ACR APDU */ static int cac_get_acr(sc_card_t *card, int acr_type, u8 **out_buf, size_t *out_len) { u8 *out = NULL; /* XXX assuming it will not be longer than 255 B */ size_t len = 256; int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* for simplicity we support only ACR without arguments now */ if (acr_type != 0x00 && acr_type != 0x10 && acr_type != 0x20 && acr_type != 0x21) { return SC_ERROR_INVALID_ARGUMENTS; } r = cac_apdu_io(card, CAC_INS_GET_ACR, acr_type, 0, NULL, 0, &out, &len); if (len == 0) { r = SC_ERROR_FILE_NOT_FOUND; } if (r < 0) goto fail; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "got %"SC_FORMAT_LEN_SIZE_T"u bytes out=%p", len, out); *out_len = len; *out_buf = out; return SC_SUCCESS; fail: if (out) free(out); *out_buf = NULL; *out_len = 0; return r; } /* * Read a CAC TLV file. Parameters specify if the TLV file is TL (Tag/Length) file or a V (value) file */ #define HIGH_BYTE_OF_SHORT(x) (((x)>> 8) & 0xff) #define LOW_BYTE_OF_SHORT(x) ((x) & 0xff) static int cac_read_file(sc_card_t *card, int file_type, u8 **out_buf, size_t *out_len) { u8 params[2]; u8 count[2]; u8 *out = NULL; u8 *out_ptr; size_t offset = 0; size_t size = 0; size_t left = 0; size_t len; int r; params[0] = file_type; params[1] = 2; /* get the size */ len = sizeof(count); out_ptr = count; r = cac_apdu_io(card, CAC_INS_READ_FILE, 0, 0, &params[0], sizeof(params), &out_ptr, &len); if (len == 0) { r = SC_ERROR_FILE_NOT_FOUND; } if (r < 0) goto fail; left = size = lebytes2ushort(count); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "got %"SC_FORMAT_LEN_SIZE_T"u bytes out_ptr=%p count&=%p count[0]=0x%02x count[1]=0x%02x, len=0x%04"SC_FORMAT_LEN_SIZE_T"x (%"SC_FORMAT_LEN_SIZE_T"u)", len, out_ptr, &count, count[0], count[1], size, size); out = out_ptr = malloc(size); if (out == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto fail; } for (offset += 2; left > 0; offset += len, left -= len, out_ptr += len) { len = MIN(left, CAC_MAX_CHUNK_SIZE); params[1] = len; r = cac_apdu_io(card, CAC_INS_READ_FILE, HIGH_BYTE_OF_SHORT(offset), LOW_BYTE_OF_SHORT(offset), &params[0], sizeof(params), &out_ptr, &len); /* if there is no data, assume there is no file */ if (len == 0) { r = SC_ERROR_FILE_NOT_FOUND; } if (r < 0) { goto fail; } } *out_len = size; *out_buf = out; return SC_SUCCESS; fail: if (out) free(out); *out_len = 0; return r; } /* * Callers of this may be expecting a certificate, * select file will have saved the object type for us * as well as set that we want the cert from the object. */ static int cac_read_binary(sc_card_t *card, unsigned int idx, unsigned char *buf, size_t count, unsigned long flags) { cac_private_data_t * priv = CAC_DATA(card); int r = 0; u8 *tl = NULL, *val = NULL; u8 *tl_ptr, *val_ptr, *tlv_ptr, *tl_start; u8 *cert_ptr; size_t tl_len, val_len, tlv_len; size_t len, tl_head_len, cert_len; u8 cert_type, tag; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* if we didn't return it all last time, return the remainder */ if (priv->cached) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "returning cached value idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u", idx, count); if (idx > priv->cache_buf_len) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_END_REACHED); } len = MIN(count, priv->cache_buf_len-idx); memcpy(buf, &priv->cache_buf[idx], len); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, len); } sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "clearing cache idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u", idx, count); if (priv->cache_buf) { free(priv->cache_buf); priv->cache_buf = NULL; priv->cache_buf_len = 0; } if (priv->object_type <= 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INTERNAL); r = cac_read_file(card, CAC_FILE_TAG, &tl, &tl_len); if (r < 0) { goto done; } r = cac_read_file(card, CAC_FILE_VALUE, &val, &val_len); if (r < 0) goto done; switch (priv->object_type) { case CAC_OBJECT_TYPE_TLV_FILE: tlv_len = tl_len + val_len; priv->cache_buf = malloc(tlv_len); if (priv->cache_buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto done; } priv->cache_buf_len = tlv_len; for (tl_ptr = tl, val_ptr=val, tlv_ptr = priv->cache_buf; tl_len >= 2 && tlv_len > 0; val_len -= len, tlv_len -= len, val_ptr += len, tlv_ptr += len) { /* get the tag and the length */ tl_start = tl_ptr; if (sc_simpletlv_read_tag(&tl_ptr, tl_len, &tag, &len) != SC_SUCCESS) break; tl_head_len = (tl_ptr - tl_start); sc_simpletlv_put_tag(tag, len, tlv_ptr, tlv_len, &tlv_ptr); tlv_len -= tl_head_len; tl_len -= tl_head_len; /* don't crash on bad data */ if (val_len < len) { len = val_len; } /* if we run out of return space, truncate */ if (tlv_len < len) { len = tlv_len; } memcpy(tlv_ptr, val_ptr, len); } break; case CAC_OBJECT_TYPE_CERT: /* read file */ sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, " obj= cert_file, val_len=%"SC_FORMAT_LEN_SIZE_T"u (0x%04"SC_FORMAT_LEN_SIZE_T"x)", val_len, val_len); cert_len = 0; cert_ptr = NULL; cert_type = 0; for (tl_ptr = tl, val_ptr = val; tl_len >= 2; val_len -= len, val_ptr += len, tl_len -= tl_head_len) { tl_start = tl_ptr; if (sc_simpletlv_read_tag(&tl_ptr, tl_len, &tag, &len) != SC_SUCCESS) break; tl_head_len = tl_ptr - tl_start; /* incomplete value */ if (val_len < len) break; if (tag == CAC_TAG_CERTIFICATE) { cert_len = len; cert_ptr = val_ptr; } if (tag == CAC_TAG_CERTINFO) { if ((len >= 1) && (val_len >=1)) { cert_type = *val_ptr; } } if (tag == CAC_TAG_MSCUID) { sc_log_hex(card->ctx, "MSCUID", val_ptr, len); } if ((val_len < len) || (tl_len < tl_head_len)) { break; } } /* if the info byte is 1, then the cert is compressed, decompress it */ if ((cert_type & 0x3) == 1) { #ifdef ENABLE_ZLIB r = sc_decompress_alloc(&priv->cache_buf, &priv->cache_buf_len, cert_ptr, cert_len, COMPRESSION_AUTO); #else sc_log(card->ctx, "CAC compression not supported, no zlib"); r = SC_ERROR_NOT_SUPPORTED; #endif if (r) goto done; } else if (cert_len > 0) { priv->cache_buf = malloc(cert_len); if (priv->cache_buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto done; } priv->cache_buf_len = cert_len; memcpy(priv->cache_buf, cert_ptr, cert_len); } else { sc_log(card->ctx, "Can't read zero-length certificate"); goto done; } break; case CAC_OBJECT_TYPE_GENERIC: /* TODO * We have some two buffers in unknown encoding that we * need to present in PKCS#15 layer. */ default: /* Unknown object type */ sc_log(card->ctx, "Unknown object type: %x", priv->object_type); r = SC_ERROR_INTERNAL; goto done; } /* OK we've read the data, now copy the required portion out to the callers buffer */ priv->cached = 1; len = MIN(count, priv->cache_buf_len-idx); memcpy(buf, &priv->cache_buf[idx], len); r = len; done: if (tl) free(tl); if (val) free(val); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } /* CAC driver is read only */ static int cac_write_binary(sc_card_t *card, unsigned int idx, const u8 *buf, size_t count, unsigned long flags) { SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_NOT_SUPPORTED); } /* initialize getting a list and return the number of elements in the list */ static int cac_get_init_and_get_count(list_t *list, cac_object_t **entry, int *countp) { *countp = list_size(list); list_iterator_start(list); *entry = list_iterator_next(list); return SC_SUCCESS; } /* finalize the list iterator */ static int cac_final_iterator(list_t *list) { list_iterator_stop(list); return SC_SUCCESS; } /* fill in the obj_info for the current object on the list and advance to the next object */ static int cac_fill_object_info(list_t *list, cac_object_t **entry, sc_pkcs15_data_info_t *obj_info) { memset(obj_info, 0, sizeof(sc_pkcs15_data_info_t)); if (*entry == NULL) { return SC_ERROR_FILE_END_REACHED; } obj_info->path = (*entry)->path; obj_info->path.count = CAC_MAX_SIZE-1; /* read something from the object */ obj_info->id.value[0] = ((*entry)->fd >> 8) & 0xff; obj_info->id.value[1] = (*entry)->fd & 0xff; obj_info->id.len = 2; strncpy(obj_info->app_label, (*entry)->name, SC_PKCS15_MAX_LABEL_SIZE-1); *entry = list_iterator_next(list); return SC_SUCCESS; } static int cac_get_serial_nr_from_CUID(sc_card_t* card, sc_serial_number_t* serial) { cac_private_data_t * priv = CAC_DATA(card); SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_NORMAL); if (card->serialnr.len) { *serial = card->serialnr; SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } if (priv->cac_id_len) { serial->len = MIN(priv->cac_id_len, SC_MAX_SERIALNR); memcpy(serial->value, priv->cac_id, priv->cac_id_len); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_NOT_FOUND); } static int cac_get_ACA_path(sc_card_t *card, sc_path_t *path) { cac_private_data_t * priv = CAC_DATA(card); SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_NORMAL); if (priv->aca_path) { *path = *priv->aca_path; } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } static int cac_card_ctl(sc_card_t *card, unsigned long cmd, void *ptr) { cac_private_data_t * priv = CAC_DATA(card); LOG_FUNC_CALLED(card->ctx); sc_log(card->ctx, "cmd=%ld ptr=%p", cmd, ptr); if (priv == NULL) { LOG_FUNC_RETURN(card->ctx, SC_ERROR_INTERNAL); } switch(cmd) { case SC_CARDCTL_CAC_GET_ACA_PATH: return cac_get_ACA_path(card, (sc_path_t *) ptr); case SC_CARDCTL_GET_SERIALNR: return cac_get_serial_nr_from_CUID(card, (sc_serial_number_t *) ptr); case SC_CARDCTL_CAC_INIT_GET_GENERIC_OBJECTS: return cac_get_init_and_get_count(&priv->general_list, &priv->general_current, (int *)ptr); case SC_CARDCTL_CAC_INIT_GET_CERT_OBJECTS: return cac_get_init_and_get_count(&priv->pki_list, &priv->pki_current, (int *)ptr); case SC_CARDCTL_CAC_GET_NEXT_GENERIC_OBJECT: return cac_fill_object_info(&priv->general_list, &priv->general_current, (sc_pkcs15_data_info_t *)ptr); case SC_CARDCTL_CAC_GET_NEXT_CERT_OBJECT: return cac_fill_object_info(&priv->pki_list, &priv->pki_current, (sc_pkcs15_data_info_t *)ptr); case SC_CARDCTL_CAC_FINAL_GET_GENERIC_OBJECTS: return cac_final_iterator(&priv->general_list); case SC_CARDCTL_CAC_FINAL_GET_CERT_OBJECTS: return cac_final_iterator(&priv->pki_list); } LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); } static int cac_get_challenge(sc_card_t *card, u8 *rnd, size_t len) { /* CAC requires 8 byte response */ u8 rbuf[8]; u8 *rbufp = &rbuf[0]; size_t out_len = sizeof rbuf; int r; LOG_FUNC_CALLED(card->ctx); r = cac_apdu_io(card, 0x84, 0x00, 0x00, NULL, 0, &rbufp, &out_len); LOG_TEST_RET(card->ctx, r, "Could not get challenge"); if (len < out_len) { out_len = len; } memcpy(rnd, rbuf, out_len); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, (int) out_len); } static int cac_set_security_env(sc_card_t *card, const sc_security_env_t *env, int se_num) { int r = SC_SUCCESS; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "flags=%08lx op=%d alg=%d algf=%08x algr=%08x kr0=%02x, krfl=%"SC_FORMAT_LEN_SIZE_T"u\n", env->flags, env->operation, env->algorithm, env->algorithm_flags, env->algorithm_ref, env->key_ref[0], env->key_ref_len); if (env->algorithm != SC_ALGORITHM_RSA) { r = SC_ERROR_NO_CARD_SUPPORT; } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r); } static int cac_restore_security_env(sc_card_t *card, int se_num) { SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } static int cac_rsa_op(sc_card_t *card, const u8 * data, size_t datalen, u8 * out, size_t outlen) { int r; u8 *outp, *rbuf; size_t rbuflen, outplen; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "datalen=%"SC_FORMAT_LEN_SIZE_T"u outlen=%"SC_FORMAT_LEN_SIZE_T"u\n", datalen, outlen); outp = out; outplen = outlen; /* Not strictly necessary. This code requires the caller to have selected the correct PKI container * and authenticated to that container with the verifyPin command... All of this under the reader lock. * The PKCS #15 higher level driver code does all this correctly (it's the same for all cards, just * different sets of APDU's that need to be called), so this call is really a little bit of paranoia */ r = sc_lock(card); if (r != SC_SUCCESS) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); rbuf = NULL; rbuflen = 0; for (; datalen > CAC_MAX_CHUNK_SIZE; data += CAC_MAX_CHUNK_SIZE, datalen -= CAC_MAX_CHUNK_SIZE) { r = cac_apdu_io(card, CAC_INS_SIGN_DECRYPT, CAC_P1_STEP, 0, data, CAC_MAX_CHUNK_SIZE, &rbuf, &rbuflen); if (r < 0) { break; } if (rbuflen != 0) { int n = MIN(rbuflen, outplen); memcpy(outp,rbuf, n); outp += n; outplen -= n; } free(rbuf); rbuf = NULL; rbuflen = 0; } if (r < 0) { goto err; } rbuf = NULL; rbuflen = 0; r = cac_apdu_io(card, CAC_INS_SIGN_DECRYPT, CAC_P1_FINAL, 0, data, datalen, &rbuf, &rbuflen); if (r < 0) { goto err; } if (rbuflen != 0) { int n = MIN(rbuflen, outplen); memcpy(outp,rbuf, n); /*outp += n; unused */ outplen -= n; } free(rbuf); rbuf = NULL; r = outlen-outplen; err: sc_unlock(card); if (r < 0) { sc_mem_clear(out, outlen); } if (rbuf) { free(rbuf); } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } static int cac_compute_signature(sc_card_t *card, const u8 * data, size_t datalen, u8 * out, size_t outlen) { SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, cac_rsa_op(card, data, datalen, out, outlen)); } static int cac_decipher(sc_card_t *card, const u8 * data, size_t datalen, u8 * out, size_t outlen) { SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, cac_rsa_op(card, data, datalen, out, outlen)); } static int cac_parse_properties_object(sc_card_t *card, u8 type, u8 *data, size_t data_len, cac_properties_object_t *object) { size_t len; u8 *val, *val_end, tag; int parsed = 0; if (data_len < 11) return -1; /* Initilize: non-PKI applet */ object->privatekey = 0; val = data; val_end = data + data_len; for (; val < val_end; val += len) { /* get the tag and the length */ if (sc_simpletlv_read_tag(&val, val_end - val, &tag, &len) != SC_SUCCESS) break; switch (tag) { case CAC_TAG_OBJECT_ID: if (len != 2) { sc_log(card->ctx, "TAG: Object ID: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Object ID = 0x%02x 0x%02x", val[0], val[1]); memcpy(&object->oid, val, 2); parsed++; break; case CAC_TAG_BUFFER_PROPERTIES: if (len != 5) { sc_log(card->ctx, "TAG: Buffer Properties: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } /* First byte is "Type of Tag Supported" */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Buffer Properties: Type of Tag Supported = 0x%02x", val[0]); object->simpletlv = val[0]; parsed++; break; case CAC_TAG_PKI_PROPERTIES: /* 4th byte is "Private Key Initialized" */ if (len != 4) { sc_log(card->ctx, "TAG: PKI Properties: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } if (type != CAC_TAG_PKI_OBJECT) { sc_log(card->ctx, "TAG: PKI Properties outside of PKI Object"); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: PKI Properties: Private Key Initialized = 0x%02x", val[2]); object->privatekey = val[2]; parsed++; break; default: /* ignore tags we don't understand */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Unknown (0x%02x)",tag ); break; } } if (parsed < 2) return SC_ERROR_INVALID_DATA; return SC_SUCCESS; } static int cac_get_properties(sc_card_t *card, cac_properties_t *prop) { u8 *rbuf = NULL; size_t rbuflen = 0, len; u8 *val, *val_end, tag; size_t i = 0; int r; prop->num_objects = 0; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); r = cac_apdu_io(card, CAC_INS_GET_PROPERTIES, 0x01, 0x00, NULL, 0, &rbuf, &rbuflen); if (r < 0) return r; val = rbuf; val_end = val + rbuflen; for (; val < val_end; val += len) { /* get the tag and the length */ if (sc_simpletlv_read_tag(&val, val_end - val, &tag, &len) != SC_SUCCESS) break; switch (tag) { case CAC_TAG_APPLET_INFORMATION: if (len != 5) { sc_log(card->ctx, "TAG: Applet Information: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Applet Information: Family: 0x%0x", val[0]); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, " Applet Version: 0x%02x 0x%02x 0x%02x 0x%02x", val[1], val[2], val[3], val[4]); break; case CAC_TAG_NUMBER_OF_OBJECTS: if (len != 1) { sc_log(card->ctx, "TAG: Num objects: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Num objects = %hhd", *val); /* make sure we do not overrun buffer */ prop->num_objects = MIN(val[0], CAC_MAX_OBJECTS); break; case CAC_TAG_TV_BUFFER: if (len != 17) { sc_log(card->ctx, "TAG: TV Object: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: TV Object nr. %"SC_FORMAT_LEN_SIZE_T"u", i); if (i >= CAC_MAX_OBJECTS) { free(rbuf); return SC_SUCCESS; } if (cac_parse_properties_object(card, tag, val, len, &prop->objects[i]) == SC_SUCCESS) i++; break; case CAC_TAG_PKI_OBJECT: if (len != 17) { sc_log(card->ctx, "TAG: PKI Object: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: PKI Object nr. %"SC_FORMAT_LEN_SIZE_T"u", i); if (i >= CAC_MAX_OBJECTS) { free(rbuf); return SC_SUCCESS; } if (cac_parse_properties_object(card, tag, val, len, &prop->objects[i]) == SC_SUCCESS) i++; break; default: /* ignore tags we don't understand */ sc_log(card->ctx, "TAG: Unknown (0x%02x), len=%" SC_FORMAT_LEN_SIZE_T"u", tag, len); break; } } free(rbuf); /* sanity */ if (i != prop->num_objects) sc_log(card->ctx, "The announced number of objects (%u) " "did not match reality (%"SC_FORMAT_LEN_SIZE_T"u)", prop->num_objects, i); prop->num_objects = i; return SC_SUCCESS; } /* * CAC cards use SC_PATH_SELECT_OBJECT_ID rather than SC_PATH_SELECT_FILE_ID. In order to use more * of the PKCS #15 structure, we call the selection SC_PATH_SELECT_FILE_ID, but we set p1 to 2 instead * of 0. Also cac1 does not do any FCI, but it doesn't understand not selecting it. It returns invalid INS * if it doesn't like anything about the select, so we always 'request' FCI for CAC1 * * The rest is just copied from iso7816_select_file */ static int cac_select_file_by_type(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out, int type) { struct sc_context *ctx; struct sc_apdu apdu; unsigned char buf[SC_MAX_APDU_BUFFER_SIZE]; unsigned char pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf; int r, pathlen, pathtype; struct sc_file *file = NULL; cac_private_data_t * priv = CAC_DATA(card); assert(card != NULL && in_path != NULL); ctx = card->ctx; SC_FUNC_CALLED(ctx, SC_LOG_DEBUG_VERBOSE); memcpy(path, in_path->value, in_path->len); pathlen = in_path->len; pathtype = in_path->type; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "path->aid=%x %x %x %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u, path->value = %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u path->type=%d (%x)", in_path->aid.value[0], in_path->aid.value[1], in_path->aid.value[2], in_path->aid.value[3], in_path->aid.value[4], in_path->aid.value[5], in_path->aid.value[6], in_path->aid.len, in_path->value[0], in_path->value[1], in_path->value[2], in_path->value[3], in_path->len, in_path->type, in_path->type); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "file_out=%p index=%d count=%d\n", file_out, in_path->index, in_path->count); /* Sigh, sc_key_select expects paths to keys to have specific formats. There is no override. * we have to add some bytes to the path to make it happy. A better fix would be to give sc_key_file * a flag that says 'no, really this path is fine'. We only need to do this for private keys */ if ((pathlen > 2) && (pathlen <= 4) && memcmp(path, "\x3F\x00", 2) == 0) { if (pathlen > 2) { path += 2; pathlen -= 2; } } /* CAC has multiple different type of objects that aren't PKCS #15. When we read * them we need convert them to something PKCS #15 would understand. Find the object * and object type here: */ if (priv) { /* don't record anything if we haven't been initialized yet */ priv->object_type = CAC_OBJECT_TYPE_GENERIC; if (cac_is_cert(priv, in_path)) { priv->object_type = CAC_OBJECT_TYPE_CERT; } /* forget any old cached values */ if (priv->cache_buf) { free(priv->cache_buf); priv->cache_buf = NULL; } priv->cache_buf_len = 0; priv->cached = 0; } if (in_path->aid.len) { if (!pathlen) { memcpy(path, in_path->aid.value, in_path->aid.len); pathlen = in_path->aid.len; pathtype = SC_PATH_TYPE_DF_NAME; } else { /* First, select the application */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"select application" ); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xA4, 4, 0); apdu.data = in_path->aid.value; apdu.datalen = in_path->aid.len; apdu.lc = in_path->aid.len; r = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r) LOG_FUNC_RETURN(ctx, r); } } sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0, 0); switch (pathtype) { /* ideally we would had SC_PATH_TYPE_OBJECT_ID and add code to the iso7816 select. * Unfortunately we'd also need to update the caching code as well. For now just * use FILE_ID and change p1 here */ case SC_PATH_TYPE_FILE_ID: apdu.p1 = 2; if (pathlen != 2) return SC_ERROR_INVALID_ARGUMENTS; break; case SC_PATH_TYPE_DF_NAME: apdu.p1 = 4; break; default: LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); } apdu.lc = pathlen; apdu.data = path; apdu.datalen = pathlen; apdu.resp = buf; apdu.resplen = sizeof(buf); apdu.le = sc_get_max_recv_size(card) < 256 ? sc_get_max_recv_size(card) : 256; if (file_out != NULL) { apdu.p2 = 0; /* first record, return FCI */ } else { apdu.p2 = 0x0C; } r = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, r, "APDU transmit failed"); if (file_out == NULL) { /* For some cards 'SELECT' can be only with request to return FCI/FCP. */ r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (apdu.sw1 == 0x6A && apdu.sw2 == 0x86) { apdu.p2 = 0x00; apdu.resplen = sizeof(buf); if (sc_transmit_apdu(card, &apdu) == SC_SUCCESS) r = sc_check_sw(card, apdu.sw1, apdu.sw2); } if (apdu.sw1 == 0x61) LOG_FUNC_RETURN(ctx, SC_SUCCESS); LOG_FUNC_RETURN(ctx, r); } r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r) LOG_FUNC_RETURN(ctx, r); /* This needs to come after the applet selection */ if (priv && in_path->len >= 2) { /* get applet properties to know if we can treat the * buffer as SimpleLTV and if we have PKI applet. * * Do this only if we select applets for reading * (not during driver initialization) */ cac_properties_t prop; size_t i = -1; r = cac_get_properties(card, &prop); if (r == SC_SUCCESS) { for (i = 0; i < prop.num_objects; i++) { sc_log(card->ctx, "Searching for our OID: 0x%02x 0x%02x = 0x%02x 0x%02x", prop.objects[i].oid[0], prop.objects[i].oid[1], in_path->value[0], in_path->value[1]); if (memcmp(prop.objects[i].oid, in_path->value, 2) == 0) break; } } if (i < prop.num_objects) { if (prop.objects[i].privatekey) priv->object_type = CAC_OBJECT_TYPE_CERT; else if (prop.objects[i].simpletlv == 0) priv->object_type = CAC_OBJECT_TYPE_TLV_FILE; } } /* CAC cards never return FCI, fake one */ file = sc_file_new(); if (file == NULL) LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY); file->path = *in_path; file->size = CAC_MAX_SIZE; /* we don't know how big, just give a large size until we can read the file */ *file_out = file; SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } static int cac_select_file(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out) { return cac_select_file_by_type(card, in_path, file_out, card->type); } static int cac_finish(sc_card_t *card) { cac_private_data_t * priv = CAC_DATA(card); SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); if (priv) { cac_free_private_data(priv); } return SC_SUCCESS; } /* select the Card Capabilities Container on CAC-2 */ static int cac_select_CCC(sc_card_t *card) { return cac_select_file_by_type(card, &cac_CCC_Path, NULL, SC_CARD_TYPE_CAC_II); } /* Select ACA in non-standard location */ static int cac_select_ACA(sc_card_t *card) { return cac_select_file_by_type(card, &cac_ACA_Path, NULL, SC_CARD_TYPE_CAC_II); } static int cac_path_from_cardurl(sc_card_t *card, sc_path_t *path, cac_card_url_t *val, int len) { if (len < 10) { return SC_ERROR_INVALID_DATA; } sc_mem_clear(path, sizeof(sc_path_t)); memcpy(path->aid.value, &val->rid, sizeof(val->rid)); memcpy(&path->aid.value[5], &val->applicationID, sizeof(val->applicationID)); path->aid.len = sizeof(val->rid) + sizeof(val->applicationID); memcpy(path->value, &val->objectID, sizeof(val->objectID)); path->len = sizeof(val->objectID); path->type = SC_PATH_TYPE_FILE_ID; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "path->aid=%x %x %x %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u, path->value = %x %x len=%"SC_FORMAT_LEN_SIZE_T"u path->type=%d (%x)", path->aid.value[0], path->aid.value[1], path->aid.value[2], path->aid.value[3], path->aid.value[4], path->aid.value[5], path->aid.value[6], path->aid.len, path->value[0], path->value[1], path->len, path->type, path->type); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "rid=%x %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u appid= %x %x len=%"SC_FORMAT_LEN_SIZE_T"u objid= %x %x len=%"SC_FORMAT_LEN_SIZE_T"u", val->rid[0], val->rid[1], val->rid[2], val->rid[3], val->rid[4], sizeof(val->rid), val->applicationID[0], val->applicationID[1], sizeof(val->applicationID), val->objectID[0], val->objectID[1], sizeof(val->objectID)); return SC_SUCCESS; } static int cac_parse_aid(sc_card_t *card, cac_private_data_t *priv, u8 *aid, int aid_len) { cac_object_t new_object; cac_properties_t prop; size_t i; int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* Search for PKI applets (7 B). Ignore generic objects for now */ if (aid_len != 7 || (memcmp(aid, CAC_1_RID "\x01", 6) != 0 && memcmp(aid, CAC_1_RID "\x00", 6) != 0)) return SC_SUCCESS; sc_mem_clear(&new_object.path, sizeof(sc_path_t)); memcpy(new_object.path.aid.value, aid, aid_len); new_object.path.aid.len = aid_len; /* Call without OID set will just select the AID without subseqent * OID selection, which we need to figure out just now */ cac_select_file_by_type(card, &new_object.path, NULL, SC_CARD_TYPE_CAC_II); r = cac_get_properties(card, &prop); if (r < 0) return SC_ERROR_INTERNAL; for (i = 0; i < prop.num_objects; i++) { /* don't fail just because we have more certs than we can support */ if (priv->cert_next >= MAX_CAC_SLOTS) return SC_SUCCESS; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "ACA: pki_object found, cert_next=%d (%s), privkey=%d", priv->cert_next, cac_labels[priv->cert_next], prop.objects[i].privatekey); /* If the private key is not initialized, we can safely * ignore this object here, but increase the pointer to follow * the certificate labels */ if (!prop.objects[i].privatekey) { priv->cert_next++; continue; } /* OID here has always 2B */ memcpy(new_object.path.value, &prop.objects[i].oid, 2); new_object.path.len = 2; new_object.path.type = SC_PATH_TYPE_FILE_ID; new_object.name = cac_labels[priv->cert_next]; new_object.fd = priv->cert_next+1; cac_add_object_to_list(&priv->pki_list, &new_object); priv->cert_next++; } return SC_SUCCESS; } static int cac_parse_cardurl(sc_card_t *card, cac_private_data_t *priv, cac_card_url_t *val, int len) { cac_object_t new_object; const cac_object_t *obj; unsigned short object_id; int r; r = cac_path_from_cardurl(card, &new_object.path, val, len); if (r != SC_SUCCESS) { return r; } switch (val->cardApplicationType) { case CAC_APP_TYPE_PKI: /* we don't want to overflow the cac_label array. This test could * go way if we create a label function that will create a unique label * from a cert index. */ if (priv->cert_next >= MAX_CAC_SLOTS) break; /* don't fail just because we have more certs than we can support */ new_object.name = cac_labels[priv->cert_next]; new_object.fd = priv->cert_next+1; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: pki_object found, cert_next=%d (%s),", priv->cert_next, new_object.name); cac_add_object_to_list(&priv->pki_list, &new_object); priv->cert_next++; break; case CAC_APP_TYPE_GENERAL: object_id = bebytes2ushort(val->objectID); obj = cac_find_obj_by_id(object_id); if (obj == NULL) break; /* don't fail just because we don't recognize the object */ new_object.name = obj->name; new_object.fd = 0; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: gen_object found, objectID=%x (%s),", object_id, new_object.name); cac_add_object_to_list(&priv->general_list, &new_object); break; case CAC_APP_TYPE_SKI: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: ski_object found"); break; default: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: unknown object_object found (type=0x%02x)", val->cardApplicationType); /* don't fail just because there is an unknown object in the CCC */ break; } return SC_SUCCESS; } static int cac_parse_cuid(sc_card_t *card, cac_private_data_t *priv, cac_cuid_t *val, size_t len) { size_t card_id_len; if (len < sizeof(cac_cuid_t)) { return SC_ERROR_INVALID_DATA; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "gsc_rid=%s", sc_dump_hex(val->gsc_rid, sizeof(val->gsc_rid))); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "manufacture id=%x", val->manufacturer_id); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "cac_type=%d", val->card_type); card_id_len = len - (&val->card_id - (u8 *)val); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "card_id=%s (%"SC_FORMAT_LEN_SIZE_T"u)", sc_dump_hex(&val->card_id, card_id_len), card_id_len); priv->cuid = *val; priv->cac_id = malloc(card_id_len); if (priv->cac_id == NULL) { return SC_ERROR_OUT_OF_MEMORY; } memcpy(priv->cac_id, &val->card_id, card_id_len); priv->cac_id_len = card_id_len; return SC_SUCCESS; } static int cac_process_CCC(sc_card_t *card, cac_private_data_t *priv); static int cac_parse_CCC(sc_card_t *card, cac_private_data_t *priv, u8 *tl, size_t tl_len, u8 *val, size_t val_len) { size_t len = 0; u8 *tl_end = tl + tl_len; u8 *val_end = val + val_len; sc_path_t new_path; int r; for (; (tl < tl_end) && (val< val_end); val += len) { /* get the tag and the length */ u8 tag; if (sc_simpletlv_read_tag(&tl, tl_end - tl, &tag, &len) != SC_SUCCESS) break; switch (tag) { case CAC_TAG_CUID: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:CUID"); r = cac_parse_cuid(card, priv, (cac_cuid_t *)val, len); if (r < 0) return r; break; case CAC_TAG_CC_VERSION_NUMBER: if (len != 1) { sc_log(card->ctx, "TAG: CC Version: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } /* ignore the version numbers for now */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: CC Version = 0x%02x", *val); break; case CAC_TAG_GRAMMAR_VERION_NUMBER: if (len != 1) { sc_log(card->ctx, "TAG: Grammar Version: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } /* ignore the version numbers for now */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Grammar Version = 0x%02x", *val); break; case CAC_TAG_CARDURL: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:CARDURL"); r = cac_parse_cardurl(card, priv, (cac_card_url_t *)val, len); if (r < 0) return r; break; /* * The following are really for file systems cards. This code only cares about CAC VM cards */ case CAC_TAG_PKCS15: if (len != 1) { sc_log(card->ctx, "TAG: PKCS15: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } /* TODO should verify that this is '0'. If it's not * zero, we should drop out of here and let the PKCS 15 * code handle this card */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG: PKCS15 = 0x%02x", *val); break; case CAC_TAG_DATA_MODEL: case CAC_TAG_CARD_APDU: case CAC_TAG_CAPABILITY_TUPLES: case CAC_TAG_STATUS_TUPLES: case CAC_TAG_REDIRECTION: case CAC_TAG_ERROR_CODES: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:FSSpecific(0x%02x)", tag); break; case CAC_TAG_ACCESS_CONTROL: /* TODO handle access control later */ sc_log_hex(card->ctx, "TAG:ACCESS Control", val, len); break; case CAC_TAG_NEXT_CCC: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:NEXT CCC"); r = cac_path_from_cardurl(card, &new_path, (cac_card_url_t *)val, len); if (r < 0) return r; r = cac_select_file_by_type(card, &new_path, NULL, SC_CARD_TYPE_CAC_II); if (r < 0) return r; r = cac_process_CCC(card, priv); if (r < 0) return r; break; default: /* ignore tags we don't understand */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:Unknown (0x%02x)",tag ); break; } } return SC_SUCCESS; } static int cac_process_CCC(sc_card_t *card, cac_private_data_t *priv) { u8 *tl = NULL, *val = NULL; size_t tl_len, val_len; int r; r = cac_read_file(card, CAC_FILE_TAG, &tl, &tl_len); if (r < 0) goto done; r = cac_read_file(card, CAC_FILE_VALUE, &val, &val_len); if (r < 0) goto done; r = cac_parse_CCC(card, priv, tl, tl_len, val, val_len); done: if (tl) free(tl); if (val) free(val); return r; } /* Service Applet Table (Table 5-21) should list all the applets on the * card, which is a good start if we don't have CCC */ static int cac_parse_ACA_service(sc_card_t *card, cac_private_data_t *priv, u8 *val, size_t val_len) { size_t len = 0; u8 *val_end = val + val_len; int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); for (; val < val_end; val += len) { /* get the tag and the length */ u8 tag; if (sc_simpletlv_read_tag(&val, val_end - val, &tag, &len) != SC_SUCCESS) break; switch (tag) { case CAC_TAG_APPLET_FAMILY: if (len != 5) { sc_log(card->ctx, "TAG: Applet Information: " "bad length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Applet Information: Family: 0x%02x", val[0]); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, " Applet Version: 0x%02x 0x%02x 0x%02x 0x%02x", val[1], val[2], val[3], val[4]); break; case CAC_TAG_NUMBER_APPLETS: if (len != 1) { sc_log(card->ctx, "TAG: Num applets: " "bad length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Num applets = %hhd", *val); break; case CAC_TAG_APPLET_ENTRY: /* Make sure we match the outer length */ if (len < 3 || val[2] != len - 3) { sc_log(card->ctx, "TAG: Applet Entry: " "bad length (%"SC_FORMAT_LEN_SIZE_T "u) or length of internal buffer", len); break; } sc_debug_hex(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Applet Entry: AID", &val[3], val[2]); /* This is SimpleTLV prefixed with applet ID (1B) */ r = cac_parse_aid(card, priv, &val[3], val[2]); if (r < 0) return r; break; default: /* ignore tags we don't understand */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Unknown (0x%02x)", tag); break; } } return SC_SUCCESS; } /* select a CAC pki applet by index */ static int cac_select_pki_applet(sc_card_t *card, int index) { sc_path_t applet_path = cac_cac_pki_obj.path; applet_path.aid.value[applet_path.aid.len-1] = index; return cac_select_file_by_type(card, &applet_path, NULL, SC_CARD_TYPE_CAC_II); } /* * Find the first existing CAC applet. If none found, then this isn't a CAC */ static int cac_find_first_pki_applet(sc_card_t *card, int *index_out) { int r, i; for (i = 0; i < MAX_CAC_SLOTS; i++) { r = cac_select_pki_applet(card, i); if (r == SC_SUCCESS) { /* Try to read first two bytes of the buffer to * make sure it is not just malfunctioning card */ u8 params[2] = {CAC_FILE_TAG, 2}; u8 data[2], *out_ptr = data; size_t len = 2; r = cac_apdu_io(card, CAC_INS_READ_FILE, 0, 0, &params[0], sizeof(params), &out_ptr, &len); if (r != 2) continue; *index_out = i; return SC_SUCCESS; } } return SC_ERROR_OBJECT_NOT_FOUND; } /* * This emulates CCC for Alt tokens, that do not come with CCC nor ACA applets */ static int cac_populate_cac_alt(sc_card_t *card, int index, cac_private_data_t *priv) { int r, i; cac_object_t pki_obj = cac_cac_pki_obj; u8 buf[100]; u8 *val; size_t val_len; /* populate PKI objects */ for (i = index; i < MAX_CAC_SLOTS; i++) { r = cac_select_pki_applet(card, i); if (r == SC_SUCCESS) { pki_obj.name = cac_labels[i]; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "CAC: pki_object found, cert_next=%d (%s),", i, pki_obj.name); pki_obj.path.aid.value[pki_obj.path.aid.len-1] = i; pki_obj.fd = i+1; /* don't use id of zero */ cac_add_object_to_list(&priv->pki_list, &pki_obj); } } /* populate non-PKI objects */ for (i=0; i < cac_object_count; i++) { r = cac_select_file_by_type(card, &cac_objects[i].path, NULL, SC_CARD_TYPE_CAC_II); if (r == SC_SUCCESS) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "CAC: obj_object found, cert_next=%d (%s),", i, cac_objects[i].name); cac_add_object_to_list(&priv->general_list, &cac_objects[i]); } } /* * create a cuid to simulate the cac 2 cuid. */ priv->cuid = cac_cac_cuid; /* create a serial number by hashing the first 100 bytes of the * first certificate on the card */ r = cac_select_pki_applet(card, index); if (r < 0) { return r; /* shouldn't happen unless the card has been removed or is malfunctioning */ } val = buf; val_len = cac_read_binary(card, 0, val, sizeof(buf), 0); if (val_len > 0) { priv->cac_id = malloc(20); if (priv->cac_id == NULL) { return SC_ERROR_OUT_OF_MEMORY; } #ifdef ENABLE_OPENSSL SHA1(val, val_len, priv->cac_id); priv->cac_id_len = 20; sc_debug_hex(card->ctx, SC_LOG_DEBUG_VERBOSE, "cuid", priv->cac_id, priv->cac_id_len); #else sc_log(card->ctx, "OpenSSL Required"); return SC_ERROR_NOT_SUPPORTED; #endif /* ENABLE_OPENSSL */ } return SC_SUCCESS; } static int cac_process_ACA(sc_card_t *card, cac_private_data_t *priv) { int r; u8 *val = NULL; size_t val_len; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* Assuming ACA is already selected */ r = cac_get_acr(card, CAC_ACR_SERVICE, &val, &val_len); if (r < 0) goto done; r = cac_parse_ACA_service(card, priv, val, val_len); if (r == SC_SUCCESS) { priv->aca_path = malloc(sizeof(sc_path_t)); if (!priv->aca_path) { r = SC_ERROR_OUT_OF_MEMORY; goto done; } memcpy(priv->aca_path, &cac_ACA_Path, sizeof(sc_path_t)); } done: if (val) free(val); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } /* * Look for a CAC card. If it exists, initialize our data structures */ static int cac_find_and_initialize(sc_card_t *card, int initialize) { int r, index; cac_private_data_t *priv = NULL; /* already initialized? */ if (card->drv_data) { return SC_SUCCESS; } /* is this a CAC-2 specified in NIST Interagency Report 6887 - * "Government Smart Card Interoperability Specification v2.1 July 2003" */ r = cac_select_CCC(card); if (r == SC_SUCCESS) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "CCC found, is CAC-2"); if (!initialize) /* match card only */ return r; priv = cac_new_private_data(); if (!priv) return SC_ERROR_OUT_OF_MEMORY; r = cac_process_CCC(card, priv); if (r == SC_SUCCESS) { card->type = SC_CARD_TYPE_CAC_II; card->drv_data = priv; return r; } } /* Even some ALT tokens can be missing CCC so we should try with ACA */ r = cac_select_ACA(card); if (r == SC_SUCCESS) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "ACA found, is CAC-2 without CCC"); if (!initialize) /* match card only */ return r; if (!priv) { priv = cac_new_private_data(); if (!priv) return SC_ERROR_OUT_OF_MEMORY; } r = cac_process_ACA(card, priv); if (r == SC_SUCCESS) { card->type = SC_CARD_TYPE_CAC_II; card->drv_data = priv; return r; } } /* is this a CAC Alt token without any accompanying structures */ r = cac_find_first_pki_applet(card, &index); if (r == SC_SUCCESS) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "PKI applet found, is bare CAC Alt"); if (!initialize) /* match card only */ return r; if (!priv) { priv = cac_new_private_data(); if (!priv) return SC_ERROR_OUT_OF_MEMORY; } card->drv_data = priv; /* needed for the read_binary() */ r = cac_populate_cac_alt(card, index, priv); if (r == SC_SUCCESS) { card->type = SC_CARD_TYPE_CAC_II; return r; } card->drv_data = NULL; /* reset on failure */ } if (priv) { cac_free_private_data(priv); } return r; } /* NOTE: returns a bool, 1 card matches, 0 it does not */ static int cac_match_card(sc_card_t *card) { int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* Since we send an APDU, the card's logout function may be called... * however it may be in dirty memory */ card->ops->logout = NULL; r = cac_find_and_initialize(card, 0); return (r == SC_SUCCESS); /* never match */ } static int cac_init(sc_card_t *card) { int r; unsigned long flags; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); r = cac_find_and_initialize(card, 1); if (r < 0) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_CARD); } flags = SC_ALGORITHM_RSA_RAW; _sc_card_add_rsa_alg(card, 1024, flags, 0); /* mandatory */ _sc_card_add_rsa_alg(card, 2048, flags, 0); /* optional */ _sc_card_add_rsa_alg(card, 3072, flags, 0); /* optional */ card->caps |= SC_CARD_CAP_RNG | SC_CARD_CAP_ISO7816_PIN_INFO; SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } static int cac_pin_cmd(sc_card_t *card, struct sc_pin_cmd_data *data, int *tries_left) { /* CAC, like PIV needs Extra validation of (new) PIN during * a PIN change request, to ensure it's not outside the * FIPS 201 4.1.6.1 (numeric only) and * FIPS 140-2 * (6 character minimum) requirements. */ struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); if (data->cmd == SC_PIN_CMD_CHANGE) { int i = 0; if (data->pin2.len < 6) { return SC_ERROR_INVALID_PIN_LENGTH; } for(i=0; i < data->pin2.len; ++i) { if (!isdigit(data->pin2.data[i])) { return SC_ERROR_INVALID_DATA; } } } return iso_drv->ops->pin_cmd(card, data, tries_left); } static struct sc_card_operations cac_ops; static struct sc_card_driver cac_drv = { "Common Access Card (CAC)", "cac", &cac_ops, NULL, 0, NULL }; static struct sc_card_driver * sc_get_driver(void) { struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); cac_ops = *iso_drv->ops; cac_ops.match_card = cac_match_card; cac_ops.init = cac_init; cac_ops.finish = cac_finish; cac_ops.select_file = cac_select_file; /* need to record object type */ cac_ops.get_challenge = cac_get_challenge; cac_ops.read_binary = cac_read_binary; cac_ops.write_binary = cac_write_binary; cac_ops.set_security_env = cac_set_security_env; cac_ops.restore_security_env = cac_restore_security_env; cac_ops.compute_signature = cac_compute_signature; cac_ops.decipher = cac_decipher; cac_ops.card_ctl = cac_card_ctl; cac_ops.pin_cmd = cac_pin_cmd; return &cac_drv; } struct sc_card_driver * sc_get_cac_driver(void) { return sc_get_driver(); }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_343_0
crossvul-cpp_data_bad_507_3
/****************************************************************************** ** Copyright (c) 2015-2018, Intel Corporation ** ** All rights reserved. ** ** ** ** Redistribution and use in source and binary forms, with or without ** ** modification, are permitted provided that the following conditions ** ** are met: ** ** 1. Redistributions of source code must retain the above copyright ** ** notice, this list of conditions and the following disclaimer. ** ** 2. Redistributions in binary form must reproduce the above copyright ** ** notice, this list of conditions and the following disclaimer in the ** ** documentation and/or other materials provided with the distribution. ** ** 3. Neither the name of the copyright holder nor the names of its ** ** contributors may be used to endorse or promote products derived ** ** from this software without specific prior written permission. ** ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** ** HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED ** ** TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR ** ** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF ** ** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ** ** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ** ** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ******************************************************************************/ /* Alexander Heinecke (Intel Corp.) ******************************************************************************/ /** * @file * This file is part of GemmCodeGenerator. * * @author Alexander Heinecke (alexander.heinecke AT mytum.de, http://www5.in.tum.de/wiki/index.php/Alexander_Heinecke,_M.Sc.,_M.Sc._with_honors) * * @section LICENSE * Copyright (c) 2012-2014, Technische Universitaet Muenchen * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @section DESCRIPTION * <DESCRIPTION> */ #include "generator_common.h" #include "generator_spgemm_csc_reader.h" #if defined(LIBXSMM_OFFLOAD_TARGET) # pragma offload_attribute(push,target(LIBXSMM_OFFLOAD_TARGET)) #endif #include <stdlib.h> #include <string.h> #include <assert.h> #include <stdio.h> #if defined(LIBXSMM_OFFLOAD_TARGET) # pragma offload_attribute(pop) #endif LIBXSMM_API_INTERN void libxsmm_sparse_csc_reader( libxsmm_generated_code* io_generated_code, const char* i_csc_file_in, unsigned int** o_row_idx, unsigned int** o_column_idx, double** o_values, unsigned int* o_row_count, unsigned int* o_column_count, unsigned int* o_element_count ) { FILE *l_csc_file_handle; const unsigned int l_line_length = 512; char l_line[512/*l_line_length*/+1]; unsigned int l_header_read = 0; unsigned int* l_column_idx_id = NULL; unsigned int l_i = 0; l_csc_file_handle = fopen( i_csc_file_in, "r" ); if ( l_csc_file_handle == NULL ) { LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSC_INPUT ); return; } while (fgets(l_line, l_line_length, l_csc_file_handle) != NULL) { if ( strlen(l_line) == l_line_length ) { free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_column_idx_id); *o_row_idx = 0; *o_column_idx = 0; *o_values = 0; fclose( l_csc_file_handle ); /* close mtx file */ LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSC_READ_LEN ); return; } /* check if we are still reading comments header */ if ( l_line[0] == '%' ) { continue; } else { /* if we are the first line after comment header, we allocate our data structures */ if ( l_header_read == 0 ) { if ( sscanf(l_line, "%u %u %u", o_row_count, o_column_count, o_element_count) == 3 ) { /* allocate CSC data structure matching mtx file */ *o_row_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_element_count)); *o_column_idx = (unsigned int*) malloc(sizeof(unsigned int) * ((size_t)(*o_column_count) + 1)); *o_values = (double*) malloc(sizeof(double) * (*o_element_count)); l_column_idx_id = (unsigned int*) malloc(sizeof(unsigned int) * (*o_column_count)); /* check if mallocs were successful */ if ( ( *o_row_idx == NULL ) || ( *o_column_idx == NULL ) || ( *o_values == NULL ) || ( l_column_idx_id == NULL ) ) { free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_column_idx_id); *o_row_idx = 0; *o_column_idx = 0; *o_values = 0; fclose(l_csc_file_handle); /* close mtx file */ LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSC_ALLOC_DATA ); return; } /* set everything to zero for init */ memset(*o_row_idx, 0, sizeof(unsigned int) * (*o_element_count)); memset(*o_column_idx, 0, sizeof(unsigned int) * ((size_t)(*o_column_count) + 1)); memset(*o_values, 0, sizeof(double) * (*o_element_count)); memset(l_column_idx_id, 0, sizeof(unsigned int) * (*o_column_count)); /* init column idx */ for (l_i = 0; l_i <= *o_column_count; ++l_i) { (*o_column_idx)[l_i] = *o_element_count; } /* init */ (*o_column_idx)[0] = 0; l_i = 0; l_header_read = 1; } else { LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSC_READ_DESC ); fclose( l_csc_file_handle ); /* close mtx file */ return; } /* now we read the actual content */ } else { unsigned int l_row = 0, l_column = 0; double l_value = 0; /* read a line of content */ if ( sscanf(l_line, "%u %u %lf", &l_row, &l_column, &l_value) != 3 ) { free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_column_idx_id); *o_row_idx = 0; *o_column_idx = 0; *o_values = 0; fclose(l_csc_file_handle); /* close mtx file */ LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSC_READ_ELEMS ); return; } /* adjust numbers to zero termination */ l_row--; l_column--; /* add these values to row and value structure */ (*o_row_idx)[l_i] = l_row; (*o_values)[l_i] = l_value; l_i++; /* handle columns, set id to own for this column, yeah we need to handle empty columns */ l_column_idx_id[l_column] = 1; (*o_column_idx)[l_column+1] = l_i; } } } /* close mtx file */ fclose( l_csc_file_handle ); /* check if we read a file which was consistent */ if ( l_i != (*o_element_count) ) { free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_column_idx_id); *o_row_idx = 0; *o_column_idx = 0; *o_values = 0; LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSC_LEN ); return; } if ( l_column_idx_id != NULL ) { /* let's handle empty columns */ for ( l_i = 0; l_i < (*o_column_count); l_i++) { if ( l_column_idx_id[l_i] == 0 ) { (*o_column_idx)[l_i+1] = (*o_column_idx)[l_i]; } } /* free helper data structure */ free( l_column_idx_id ); } }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_507_3
crossvul-cpp_data_good_340_1
/* * Support for ePass2003 smart cards * * Copyright (C) 2008, Weitao Sun <weitao@ftsafe.com> * Copyright (C) 2011, Xiaoshuo Wu <xiaoshuo@ftsafe.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #ifdef ENABLE_SM /* empty file without SM enabled */ #ifdef ENABLE_OPENSSL /* empty file without openssl */ #include <ctype.h> #include <stdlib.h> #include <string.h> #include <openssl/evp.h> #include <openssl/sha.h> #include "internal.h" #include "asn1.h" #include <ctype.h> #include <stdlib.h> #include <string.h> #include <openssl/evp.h> #include <openssl/sha.h> #include "internal.h" #include "asn1.h" #include "cardctl.h" static struct sc_atr_table epass2003_atrs[] = { /* This is a FIPS certified card using SCP01 security messaging. */ {"3B:9F:95:81:31:FE:9F:00:66:46:53:05:10:00:11:71:df:00:00:00:6a:82:5e", "FF:FF:FF:FF:FF:00:FF:FF:FF:FF:FF:FF:00:00:00:ff:00:ff:ff:00:00:00:00", "FTCOS/ePass2003", SC_CARD_TYPE_ENTERSAFE_FTCOS_EPASS2003, 0, NULL }, {NULL, NULL, NULL, 0, 0, NULL} }; static struct sc_card_operations *iso_ops = NULL; static struct sc_card_operations epass2003_ops; static struct sc_card_driver epass2003_drv = { "epass2003", "epass2003", &epass2003_ops, NULL, 0, NULL }; #define KEY_TYPE_AES 0x01 /* FIPS mode */ #define KEY_TYPE_DES 0x02 /* Non-FIPS mode */ #define KEY_LEN_AES 16 #define KEY_LEN_DES 8 #define KEY_LEN_DES3 24 #define HASH_LEN 24 static unsigned char PIN_ID[2] = { ENTERSAFE_USER_PIN_ID, ENTERSAFE_SO_PIN_ID }; /*0x00:plain; 0x01:scp01 sm*/ #define SM_PLAIN 0x00 #define SM_SCP01 0x01 static unsigned char g_init_key_enc[16] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10 }; static unsigned char g_init_key_mac[16] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10 }; static unsigned char g_random[8] = { 0xBF, 0xC3, 0x29, 0x11, 0xC7, 0x18, 0xC3, 0x40 }; typedef struct epass2003_exdata_st { unsigned char sm; /* SM_PLAIN or SM_SCP01 */ unsigned char smtype; /* KEY_TYPE_AES or KEY_TYPE_DES */ unsigned char sk_enc[16]; /* encrypt session key */ unsigned char sk_mac[16]; /* mac session key */ unsigned char icv_mac[16]; /* instruction counter vector(for sm) */ unsigned char currAlg; /* current Alg */ unsigned int ecAlgFlags; /* Ec Alg mechanism type*/ } epass2003_exdata; #define REVERSE_ORDER4(x) ( \ ((unsigned long)x & 0xFF000000)>> 24 | \ ((unsigned long)x & 0x00FF0000)>> 8 | \ ((unsigned long)x & 0x0000FF00)<< 8 | \ ((unsigned long)x & 0x000000FF)<< 24) static const struct sc_card_error epass2003_errors[] = { { 0x6200, SC_ERROR_CARD_CMD_FAILED, "Warning: no information given, non-volatile memory is unchanged" }, { 0x6281, SC_ERROR_CORRUPTED_DATA, "Part of returned data may be corrupted" }, { 0x6282, SC_ERROR_FILE_END_REACHED, "End of file/record reached before reading Le bytes" }, { 0x6283, SC_ERROR_CARD_CMD_FAILED, "Selected file invalidated" }, { 0x6284, SC_ERROR_CARD_CMD_FAILED, "FCI not formatted according to ISO 7816-4" }, { 0x6300, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C1, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed. One tries left"}, { 0x63C2, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed. Two tries left"}, { 0x63C3, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C4, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C5, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C6, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C7, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C8, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C9, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63CA, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x6381, SC_ERROR_CARD_CMD_FAILED, "Warning: file filled up by last write" }, { 0x6581, SC_ERROR_MEMORY_FAILURE, "Memory failure" }, { 0x6700, SC_ERROR_WRONG_LENGTH, "Wrong length" }, { 0x6800, SC_ERROR_NO_CARD_SUPPORT, "Functions in CLA not supported" }, { 0x6881, SC_ERROR_NO_CARD_SUPPORT, "Logical channel not supported" }, { 0x6882, SC_ERROR_NO_CARD_SUPPORT, "Secure messaging not supported" }, { 0x6900, SC_ERROR_NOT_ALLOWED, "Command not allowed" }, { 0x6981, SC_ERROR_CARD_CMD_FAILED, "Command incompatible with file structure" }, { 0x6982, SC_ERROR_SECURITY_STATUS_NOT_SATISFIED, "Security status not satisfied" }, { 0x6983, SC_ERROR_AUTH_METHOD_BLOCKED, "Authentication method blocked" }, { 0x6984, SC_ERROR_REF_DATA_NOT_USABLE, "Referenced data not usable" }, { 0x6985, SC_ERROR_NOT_ALLOWED, "Conditions of use not satisfied" }, { 0x6986, SC_ERROR_NOT_ALLOWED, "Command not allowed (no current EF)" }, { 0x6987, SC_ERROR_INCORRECT_PARAMETERS,"Expected SM data objects missing" }, { 0x6988, SC_ERROR_INCORRECT_PARAMETERS,"SM data objects incorrect" }, { 0x6A00, SC_ERROR_INCORRECT_PARAMETERS,"Wrong parameter(s) P1-P2" }, { 0x6A80, SC_ERROR_INCORRECT_PARAMETERS,"Incorrect parameters in the data field" }, { 0x6A81, SC_ERROR_NO_CARD_SUPPORT, "Function not supported" }, { 0x6A82, SC_ERROR_FILE_NOT_FOUND, "File not found" }, { 0x6A83, SC_ERROR_RECORD_NOT_FOUND, "Record not found" }, { 0x6A84, SC_ERROR_NOT_ENOUGH_MEMORY, "Not enough memory space in the file" }, { 0x6A85, SC_ERROR_INCORRECT_PARAMETERS,"Lc inconsistent with TLV structure" }, { 0x6A86, SC_ERROR_INCORRECT_PARAMETERS,"Incorrect parameters P1-P2" }, { 0x6A87, SC_ERROR_INCORRECT_PARAMETERS,"Lc inconsistent with P1-P2" }, { 0x6A88, SC_ERROR_DATA_OBJECT_NOT_FOUND,"Referenced data not found" }, { 0x6A89, SC_ERROR_FILE_ALREADY_EXISTS, "File already exists"}, { 0x6A8A, SC_ERROR_FILE_ALREADY_EXISTS, "DF name already exists"}, { 0x6B00, SC_ERROR_INCORRECT_PARAMETERS,"Wrong parameter(s) P1-P2" }, { 0x6D00, SC_ERROR_INS_NOT_SUPPORTED, "Instruction code not supported or invalid" }, { 0x6E00, SC_ERROR_CLASS_NOT_SUPPORTED, "Class not supported" }, { 0x6F00, SC_ERROR_CARD_CMD_FAILED, "No precise diagnosis" }, { 0x9000,SC_SUCCESS, NULL } }; static int epass2003_transmit_apdu(struct sc_card *card, struct sc_apdu *apdu); static int epass2003_select_file(struct sc_card *card, const sc_path_t * in_path, sc_file_t ** file_out); int epass2003_refresh(struct sc_card *card); static int hash_data(const unsigned char *data, size_t datalen, unsigned char *hash, unsigned int mechanismType); static int epass2003_check_sw(struct sc_card *card, unsigned int sw1, unsigned int sw2) { const int err_count = sizeof(epass2003_errors)/sizeof(epass2003_errors[0]); int i; /* Handle special cases here */ if (sw1 == 0x6C) { sc_log(card->ctx, "Wrong length; correct length is %d", sw2); return SC_ERROR_WRONG_LENGTH; } for (i = 0; i < err_count; i++) { if (epass2003_errors[i].SWs == ((sw1 << 8) | sw2)) { sc_log(card->ctx, "%s", epass2003_errors[i].errorstr); return epass2003_errors[i].errorno; } } sc_log(card->ctx, "Unknown SWs; SW1=%02X, SW2=%02X", sw1, sw2); return SC_ERROR_CARD_CMD_FAILED; } static int sc_transmit_apdu_t(sc_card_t *card, sc_apdu_t *apdu) { int r = sc_transmit_apdu(card, apdu); if ( ((0x69 == apdu->sw1) && (0x85 == apdu->sw2)) || ((0x69 == apdu->sw1) && (0x88 == apdu->sw2))) { epass2003_refresh(card); r = sc_transmit_apdu(card, apdu); } return r; } static int openssl_enc(const EVP_CIPHER * cipher, const unsigned char *key, const unsigned char *iv, const unsigned char *input, size_t length, unsigned char *output) { int r = SC_ERROR_INTERNAL; EVP_CIPHER_CTX * ctx = NULL; int outl = 0; int outl_tmp = 0; unsigned char iv_tmp[EVP_MAX_IV_LENGTH] = { 0 }; memcpy(iv_tmp, iv, EVP_MAX_IV_LENGTH); ctx = EVP_CIPHER_CTX_new(); if (ctx == NULL) goto out; EVP_EncryptInit_ex(ctx, cipher, NULL, key, iv_tmp); EVP_CIPHER_CTX_set_padding(ctx, 0); if (!EVP_EncryptUpdate(ctx, output, &outl, input, length)) goto out; if (!EVP_EncryptFinal_ex(ctx, output + outl, &outl_tmp)) goto out; r = SC_SUCCESS; out: if (ctx) EVP_CIPHER_CTX_free(ctx); return r; } static int openssl_dec(const EVP_CIPHER * cipher, const unsigned char *key, const unsigned char *iv, const unsigned char *input, size_t length, unsigned char *output) { int r = SC_ERROR_INTERNAL; EVP_CIPHER_CTX * ctx = NULL; int outl = 0; int outl_tmp = 0; unsigned char iv_tmp[EVP_MAX_IV_LENGTH] = { 0 }; memcpy(iv_tmp, iv, EVP_MAX_IV_LENGTH); ctx = EVP_CIPHER_CTX_new(); if (ctx == NULL) goto out; EVP_DecryptInit_ex(ctx, cipher, NULL, key, iv_tmp); EVP_CIPHER_CTX_set_padding(ctx, 0); if (!EVP_DecryptUpdate(ctx, output, &outl, input, length)) goto out; if (!EVP_DecryptFinal_ex(ctx, output + outl, &outl_tmp)) goto out; r = SC_SUCCESS; out: if (ctx) EVP_CIPHER_CTX_free(ctx); return r; } static int aes128_encrypt_ecb(const unsigned char *key, int keysize, const unsigned char *input, size_t length, unsigned char *output) { unsigned char iv[EVP_MAX_IV_LENGTH] = { 0 }; return openssl_enc(EVP_aes_128_ecb(), key, iv, input, length, output); } static int aes128_encrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[16], const unsigned char *input, size_t length, unsigned char *output) { return openssl_enc(EVP_aes_128_cbc(), key, iv, input, length, output); } static int aes128_decrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[16], const unsigned char *input, size_t length, unsigned char *output) { return openssl_dec(EVP_aes_128_cbc(), key, iv, input, length, output); } static int des3_encrypt_ecb(const unsigned char *key, int keysize, const unsigned char *input, int length, unsigned char *output) { unsigned char iv[EVP_MAX_IV_LENGTH] = { 0 }; unsigned char bKey[24] = { 0 }; if (keysize == 16) { memcpy(&bKey[0], key, 16); memcpy(&bKey[16], key, 8); } else { memcpy(&bKey[0], key, 24); } return openssl_enc(EVP_des_ede3(), bKey, iv, input, length, output); } static int des3_encrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH], const unsigned char *input, size_t length, unsigned char *output) { unsigned char bKey[24] = { 0 }; if (keysize == 16) { memcpy(&bKey[0], key, 16); memcpy(&bKey[16], key, 8); } else { memcpy(&bKey[0], key, 24); } return openssl_enc(EVP_des_ede3_cbc(), bKey, iv, input, length, output); } static int des3_decrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH], const unsigned char *input, size_t length, unsigned char *output) { unsigned char bKey[24] = { 0 }; if (keysize == 16) { memcpy(&bKey[0], key, 16); memcpy(&bKey[16], key, 8); } else { memcpy(&bKey[0], key, 24); } return openssl_dec(EVP_des_ede3_cbc(), bKey, iv, input, length, output); } static int des_encrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH], const unsigned char *input, size_t length, unsigned char *output) { return openssl_enc(EVP_des_cbc(), key, iv, input, length, output); } static int des_decrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH], const unsigned char *input, size_t length, unsigned char *output) { return openssl_dec(EVP_des_cbc(), key, iv, input, length, output); } static int openssl_dig(const EVP_MD * digest, const unsigned char *input, size_t length, unsigned char *output) { int r = 0; EVP_MD_CTX *ctx = NULL; unsigned outl = 0; ctx = EVP_MD_CTX_create(); if (ctx == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto err; } EVP_MD_CTX_init(ctx); EVP_DigestInit_ex(ctx, digest, NULL); if (!EVP_DigestUpdate(ctx, input, length)) { r = SC_ERROR_INTERNAL; goto err; } if (!EVP_DigestFinal_ex(ctx, output, &outl)) { r = SC_ERROR_INTERNAL; goto err; } r = SC_SUCCESS; err: if (ctx) EVP_MD_CTX_destroy(ctx); return r; } static int sha1_digest(const unsigned char *input, size_t length, unsigned char *output) { return openssl_dig(EVP_sha1(), input, length, output); } static int sha256_digest(const unsigned char *input, size_t length, unsigned char *output) { return openssl_dig(EVP_sha256(), input, length, output); } static int gen_init_key(struct sc_card *card, unsigned char *key_enc, unsigned char *key_mac, unsigned char *result, unsigned char key_type) { int r; struct sc_apdu apdu; unsigned char data[256] = { 0 }; unsigned char tmp_sm; unsigned long blocksize = 0; unsigned char cryptogram[256] = { 0 }; /* host cryptogram */ unsigned char iv[16] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x50, 0x00, 0x00); apdu.cla = 0x80; apdu.lc = apdu.datalen = sizeof(g_random); apdu.data = g_random; /* host random */ apdu.le = apdu.resplen = 28; apdu.resp = result; /* card random is result[12~19] */ tmp_sm = exdata->sm; exdata->sm = SM_PLAIN; r = epass2003_transmit_apdu(card, &apdu); exdata->sm = tmp_sm; LOG_TEST_RET(card->ctx, r, "APDU gen_init_key failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "gen_init_key failed"); /* Step 1 - Generate Derivation data */ memcpy(data, &result[16], 4); memcpy(&data[4], g_random, 4); memcpy(&data[8], &result[12], 4); memcpy(&data[12], &g_random[4], 4); /* Step 2,3 - Create S-ENC/S-MAC Session Key */ if (KEY_TYPE_AES == key_type) { aes128_encrypt_ecb(key_enc, 16, data, 16, exdata->sk_enc); aes128_encrypt_ecb(key_mac, 16, data, 16, exdata->sk_mac); } else { des3_encrypt_ecb(key_enc, 16, data, 16, exdata->sk_enc); des3_encrypt_ecb(key_mac, 16, data, 16, exdata->sk_mac); } memcpy(data, g_random, 8); memcpy(&data[8], &result[12], 8); data[16] = 0x80; blocksize = (key_type == KEY_TYPE_AES ? 16 : 8); memset(&data[17], 0x00, blocksize - 1); /* calculate host cryptogram */ if (KEY_TYPE_AES == key_type) aes128_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize, cryptogram); else des3_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize, cryptogram); /* verify card cryptogram */ if (0 != memcmp(&cryptogram[16], &result[20], 8)) LOG_FUNC_RETURN(card->ctx, SC_ERROR_CARD_CMD_FAILED); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int verify_init_key(struct sc_card *card, unsigned char *ran_key, unsigned char key_type) { int r; struct sc_apdu apdu; unsigned long blocksize = (key_type == KEY_TYPE_AES ? 16 : 8); unsigned char data[256] = { 0 }; unsigned char cryptogram[256] = { 0 }; /* host cryptogram */ unsigned char iv[16] = { 0 }; unsigned char mac[256] = { 0 }; unsigned long i; unsigned char tmp_sm; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); memcpy(data, ran_key, 8); memcpy(&data[8], g_random, 8); data[16] = 0x80; memset(&data[17], 0x00, blocksize - 1); memset(iv, 0, 16); /* calculate host cryptogram */ if (KEY_TYPE_AES == key_type) { aes128_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize, cryptogram); } else { des3_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize, cryptogram); } memset(data, 0, sizeof(data)); memcpy(data, "\x84\x82\x03\x00\x10", 5); memcpy(&data[5], &cryptogram[16], 8); memcpy(&data[13], "\x80\x00\x00", 3); /* calculate mac icv */ memset(iv, 0x00, 16); if (KEY_TYPE_AES == key_type) { aes128_encrypt_cbc(exdata->sk_mac, 16, iv, data, 16, mac); i = 0; } else { des3_encrypt_cbc(exdata->sk_mac, 16, iv, data, 16, mac); i = 8; } /* save mac icv */ memset(exdata->icv_mac, 0x00, 16); memcpy(exdata->icv_mac, &mac[i], 8); /* verify host cryptogram */ memcpy(data, &cryptogram[16], 8); memcpy(&data[8], &mac[i], 8); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x82, 0x03, 0x00); apdu.cla = 0x84; apdu.lc = apdu.datalen = 16; apdu.data = data; tmp_sm = exdata->sm; exdata->sm = SM_PLAIN; r = epass2003_transmit_apdu(card, &apdu); exdata->sm = tmp_sm; LOG_TEST_RET(card->ctx, r, "APDU verify_init_key failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "verify_init_key failed"); return r; } static int mutual_auth(struct sc_card *card, unsigned char *key_enc, unsigned char *key_mac) { struct sc_context *ctx = card->ctx; int r; unsigned char result[256] = { 0 }; unsigned char ran_key[8] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(ctx); r = gen_init_key(card, key_enc, key_mac, result, exdata->smtype); LOG_TEST_RET(ctx, r, "gen_init_key failed"); memcpy(ran_key, &result[12], 8); r = verify_init_key(card, ran_key, exdata->smtype); LOG_TEST_RET(ctx, r, "verify_init_key failed"); LOG_FUNC_RETURN(ctx, r); } int epass2003_refresh(struct sc_card *card) { int r = SC_SUCCESS; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; if (exdata->sm) { card->sm_ctx.sm_mode = 0; r = mutual_auth(card, g_init_key_enc, g_init_key_mac); card->sm_ctx.sm_mode = SM_MODE_TRANSMIT; LOG_TEST_RET(card->ctx, r, "mutual_auth failed"); } return r; } /* Data(TLV)=0x87|L|0x01+Cipher */ static int construct_data_tlv(struct sc_card *card, struct sc_apdu *apdu, unsigned char *apdu_buf, unsigned char *data_tlv, size_t * data_tlv_len, const unsigned char key_type) { size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8); unsigned char pad[4096] = { 0 }; size_t pad_len; size_t tlv_more; /* increased tlv length */ unsigned char iv[16] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; /* padding */ apdu_buf[block_size] = 0x87; memcpy(pad, apdu->data, apdu->lc); pad[apdu->lc] = 0x80; if ((apdu->lc + 1) % block_size) pad_len = ((apdu->lc + 1) / block_size + 1) * block_size; else pad_len = apdu->lc + 1; /* encode Lc' */ if (pad_len > 0x7E) { /* Lc' > 0x7E, use extended APDU */ apdu_buf[block_size + 1] = 0x82; apdu_buf[block_size + 2] = (unsigned char)((pad_len + 1) / 0x100); apdu_buf[block_size + 3] = (unsigned char)((pad_len + 1) % 0x100); apdu_buf[block_size + 4] = 0x01; tlv_more = 5; } else { apdu_buf[block_size + 1] = (unsigned char)pad_len + 1; apdu_buf[block_size + 2] = 0x01; tlv_more = 3; } memcpy(data_tlv, &apdu_buf[block_size], tlv_more); /* encrypt Data */ if (KEY_TYPE_AES == key_type) aes128_encrypt_cbc(exdata->sk_enc, 16, iv, pad, pad_len, apdu_buf + block_size + tlv_more); else des3_encrypt_cbc(exdata->sk_enc, 16, iv, pad, pad_len, apdu_buf + block_size + tlv_more); memcpy(data_tlv + tlv_more, apdu_buf + block_size + tlv_more, pad_len); *data_tlv_len = tlv_more + pad_len; return 0; } /* Le(TLV)=0x97|L|Le */ static int construct_le_tlv(struct sc_apdu *apdu, unsigned char *apdu_buf, size_t data_tlv_len, unsigned char *le_tlv, size_t * le_tlv_len, const unsigned char key_type) { size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8); *(apdu_buf + block_size + data_tlv_len) = 0x97; if (apdu->le > 0x7F) { /* Le' > 0x7E, use extended APDU */ *(apdu_buf + block_size + data_tlv_len + 1) = 2; *(apdu_buf + block_size + data_tlv_len + 2) = (unsigned char)(apdu->le / 0x100); *(apdu_buf + block_size + data_tlv_len + 3) = (unsigned char)(apdu->le % 0x100); memcpy(le_tlv, apdu_buf + block_size + data_tlv_len, 4); *le_tlv_len = 4; } else { *(apdu_buf + block_size + data_tlv_len + 1) = 1; *(apdu_buf + block_size + data_tlv_len + 2) = (unsigned char)apdu->le; memcpy(le_tlv, apdu_buf + block_size + data_tlv_len, 3); *le_tlv_len = 3; } return 0; } /* MAC(TLV)=0x8e|0x08|MAC */ static int construct_mac_tlv(struct sc_card *card, unsigned char *apdu_buf, size_t data_tlv_len, size_t le_tlv_len, unsigned char *mac_tlv, size_t * mac_tlv_len, const unsigned char key_type) { size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8); unsigned char mac[4096] = { 0 }; size_t mac_len; unsigned char icv[16] = { 0 }; int i = (KEY_TYPE_AES == key_type ? 15 : 7); epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; if (0 == data_tlv_len && 0 == le_tlv_len) { mac_len = block_size; } else { /* padding */ *(apdu_buf + block_size + data_tlv_len + le_tlv_len) = 0x80; if ((data_tlv_len + le_tlv_len + 1) % block_size) mac_len = (((data_tlv_len + le_tlv_len + 1) / block_size) + 1) * block_size + block_size; else mac_len = data_tlv_len + le_tlv_len + 1 + block_size; memset((apdu_buf + block_size + data_tlv_len + le_tlv_len + 1), 0, (mac_len - (data_tlv_len + le_tlv_len + 1))); } /* increase icv */ for (; i >= 0; i--) { if (exdata->icv_mac[i] == 0xff) { exdata->icv_mac[i] = 0; } else { exdata->icv_mac[i]++; break; } } /* calculate MAC */ memset(icv, 0, sizeof(icv)); memcpy(icv, exdata->icv_mac, 16); if (KEY_TYPE_AES == key_type) { aes128_encrypt_cbc(exdata->sk_mac, 16, icv, apdu_buf, mac_len, mac); memcpy(mac_tlv + 2, &mac[mac_len - 16], 8); } else { unsigned char iv[EVP_MAX_IV_LENGTH] = { 0 }; unsigned char tmp[8] = { 0 }; des_encrypt_cbc(exdata->sk_mac, 8, icv, apdu_buf, mac_len, mac); des_decrypt_cbc(&exdata->sk_mac[8], 8, iv, &mac[mac_len - 8], 8, tmp); memset(iv, 0x00, sizeof iv); des_encrypt_cbc(exdata->sk_mac, 8, iv, tmp, 8, mac_tlv + 2); } *mac_tlv_len = 2 + 8; return 0; } /* According to GlobalPlatform Card Specification's SCP01 * encode APDU from * CLA INS P1 P2 [Lc] Data [Le] * to * CLA INS P1 P2 Lc' Data' [Le] * where * Data'=Data(TLV)+Le(TLV)+MAC(TLV) */ static int encode_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu *sm, unsigned char *apdu_buf, size_t * apdu_buf_len) { size_t block_size = 0; unsigned char dataTLV[4096] = { 0 }; size_t data_tlv_len = 0; unsigned char le_tlv[256] = { 0 }; size_t le_tlv_len = 0; size_t mac_tlv_len = 10; size_t tmp_lc = 0; size_t tmp_le = 0; unsigned char mac_tlv[256] = { 0 }; epass2003_exdata *exdata = NULL; mac_tlv[0] = 0x8E; mac_tlv[1] = 8; /* size_t plain_le = 0; */ if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata*)card->drv_data; block_size = (KEY_TYPE_DES == exdata->smtype ? 16 : 8); sm->cse = SC_APDU_CASE_4_SHORT; apdu_buf[0] = (unsigned char)plain->cla; apdu_buf[1] = (unsigned char)plain->ins; apdu_buf[2] = (unsigned char)plain->p1; apdu_buf[3] = (unsigned char)plain->p2; /* plain_le = plain->le; */ /* padding */ apdu_buf[4] = 0x80; memset(&apdu_buf[5], 0x00, block_size - 5); /* Data -> Data' */ if (plain->lc != 0) if (0 != construct_data_tlv(card, plain, apdu_buf, dataTLV, &data_tlv_len, exdata->smtype)) return -1; if (plain->le != 0 || (plain->le == 0 && plain->resplen != 0)) if (0 != construct_le_tlv(plain, apdu_buf, data_tlv_len, le_tlv, &le_tlv_len, exdata->smtype)) return -1; if (0 != construct_mac_tlv(card, apdu_buf, data_tlv_len, le_tlv_len, mac_tlv, &mac_tlv_len, exdata->smtype)) return -1; memset(apdu_buf + 4, 0, *apdu_buf_len - 4); sm->lc = sm->datalen = data_tlv_len + le_tlv_len + mac_tlv_len; if (sm->lc > 0xFF) { sm->cse = SC_APDU_CASE_4_EXT; apdu_buf[4] = (unsigned char)((sm->lc) / 0x10000); apdu_buf[5] = (unsigned char)(((sm->lc) / 0x100) % 0x100); apdu_buf[6] = (unsigned char)((sm->lc) % 0x100); tmp_lc = 3; } else { apdu_buf[4] = (unsigned char)sm->lc; tmp_lc = 1; } memcpy(apdu_buf + 4 + tmp_lc, dataTLV, data_tlv_len); memcpy(apdu_buf + 4 + tmp_lc + data_tlv_len, le_tlv, le_tlv_len); memcpy(apdu_buf + 4 + tmp_lc + data_tlv_len + le_tlv_len, mac_tlv, mac_tlv_len); memcpy((unsigned char *)sm->data, apdu_buf + 4 + tmp_lc, sm->datalen); *apdu_buf_len = 0; if (4 == le_tlv_len) { sm->cse = SC_APDU_CASE_4_EXT; *(apdu_buf + 4 + tmp_lc + sm->lc) = (unsigned char)(plain->le / 0x100); *(apdu_buf + 4 + tmp_lc + sm->lc + 1) = (unsigned char)(plain->le % 0x100); tmp_le = 2; } else if (3 == le_tlv_len) { *(apdu_buf + 4 + tmp_lc + sm->lc) = (unsigned char)plain->le; tmp_le = 1; } *apdu_buf_len += 4 + tmp_lc + data_tlv_len + le_tlv_len + mac_tlv_len + tmp_le; /* sm->le = calc_le(plain_le); */ return 0; } static int epass2003_sm_wrap_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu *sm) { unsigned char buf[4096] = { 0 }; /* APDU buffer */ size_t buf_len = sizeof(buf); epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); if (exdata->sm) plain->cla |= 0x0C; sm->cse = plain->cse; sm->cla = plain->cla; sm->ins = plain->ins; sm->p1 = plain->p1; sm->p2 = plain->p2; sm->lc = plain->lc; sm->le = plain->le; sm->control = plain->control; sm->flags = plain->flags; switch (sm->cla & 0x0C) { case 0x00: case 0x04: sm->datalen = plain->datalen; memcpy((void *)sm->data, plain->data, plain->datalen); sm->resplen = plain->resplen; memcpy(sm->resp, plain->resp, plain->resplen); break; case 0x0C: memset(buf, 0, sizeof(buf)); if (0 != encode_apdu(card, plain, sm, buf, &buf_len)) return SC_ERROR_CARD_CMD_FAILED; break; default: return SC_ERROR_INCORRECT_PARAMETERS; } return SC_SUCCESS; } /* According to GlobalPlatform Card Specification's SCP01 * decrypt APDU response from * ResponseData' SW1 SW2 * to * ResponseData SW1 SW2 * where * ResponseData'=Data(TLV)+SW12(TLV)+MAC(TLV) * where * Data(TLV)=0x87|L|Cipher * SW12(TLV)=0x99|0x02|SW1+SW2 * MAC(TLV)=0x8e|0x08|MAC */ static int decrypt_response(struct sc_card *card, unsigned char *in, size_t inlen, unsigned char *out, size_t * out_len) { size_t cipher_len; size_t i; unsigned char iv[16] = { 0 }; unsigned char plaintext[4096] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; /* no cipher */ if (in[0] == 0x99) return 0; /* parse cipher length */ if (0x01 == in[2] && 0x82 != in[1]) { cipher_len = in[1]; i = 3; } else if (0x01 == in[3] && 0x81 == in[1]) { cipher_len = in[2]; i = 4; } else if (0x01 == in[4] && 0x82 == in[1]) { cipher_len = in[2] * 0x100; cipher_len += in[3]; i = 5; } else { return -1; } if (cipher_len < 2 || i+cipher_len > inlen || cipher_len > sizeof plaintext) return -1; /* decrypt */ if (KEY_TYPE_AES == exdata->smtype) aes128_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext); else des3_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext); /* unpadding */ while (0x80 != plaintext[cipher_len - 2] && (cipher_len - 2 > 0)) cipher_len--; if (2 == cipher_len || *out_len < cipher_len - 2) return -1; memcpy(out, plaintext, cipher_len - 2); *out_len = cipher_len - 2; return 0; } static int epass2003_sm_unwrap_apdu(struct sc_card *card, struct sc_apdu *sm, struct sc_apdu *plain) { int r; size_t len = 0; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); r = sc_check_sw(card, sm->sw1, sm->sw2); if (r == SC_SUCCESS) { if (exdata->sm) { len = plain->resplen; if (0 != decrypt_response(card, sm->resp, sm->resplen, plain->resp, &len)) return SC_ERROR_CARD_CMD_FAILED; } else { memcpy(plain->resp, sm->resp, sm->resplen); len = sm->resplen; } } plain->resplen = len; plain->sw1 = sm->sw1; plain->sw2 = sm->sw2; sc_log(card->ctx, "unwrapped APDU: resplen %"SC_FORMAT_LEN_SIZE_T"u, SW %02X%02X", plain->resplen, plain->sw1, plain->sw2); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_sm_free_wrapped_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu **sm_apdu) { struct sc_context *ctx = card->ctx; int rv = SC_SUCCESS; LOG_FUNC_CALLED(ctx); if (!sm_apdu) LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); if (!(*sm_apdu)) LOG_FUNC_RETURN(ctx, SC_SUCCESS); if (plain) rv = epass2003_sm_unwrap_apdu(card, *sm_apdu, plain); if ((*sm_apdu)->data) { unsigned char * p = (unsigned char *)((*sm_apdu)->data); free(p); } if ((*sm_apdu)->resp) { free((*sm_apdu)->resp); } free(*sm_apdu); *sm_apdu = NULL; LOG_FUNC_RETURN(ctx, rv); } static int epass2003_sm_get_wrapped_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu **sm_apdu) { struct sc_context *ctx = card->ctx; struct sc_apdu *apdu = NULL; int rv; LOG_FUNC_CALLED(ctx); if (!plain || !sm_apdu) LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); *sm_apdu = NULL; //construct new SM apdu from original apdu apdu = calloc(1, sizeof(struct sc_apdu)); if (!apdu) { rv = SC_ERROR_OUT_OF_MEMORY; goto err; } apdu->data = calloc (1, SC_MAX_EXT_APDU_BUFFER_SIZE); if (!apdu->data) { rv = SC_ERROR_OUT_OF_MEMORY; goto err; } apdu->resp = calloc (1, SC_MAX_EXT_APDU_BUFFER_SIZE); if (!apdu->resp) { rv = SC_ERROR_OUT_OF_MEMORY; goto err; } apdu->datalen = SC_MAX_EXT_APDU_BUFFER_SIZE; apdu->resplen = SC_MAX_EXT_APDU_BUFFER_SIZE; rv = epass2003_sm_wrap_apdu(card, plain, apdu); if (rv) { rv = epass2003_sm_free_wrapped_apdu(card, NULL, &apdu); if (rv < 0) goto err; } *sm_apdu = apdu; apdu = NULL; err: if (apdu) { free((unsigned char *) apdu->data); free(apdu->resp); free(apdu); apdu = NULL; } LOG_FUNC_RETURN(ctx, rv); } static int epass2003_transmit_apdu(struct sc_card *card, struct sc_apdu *apdu) { int r; LOG_FUNC_CALLED(card->ctx); r = sc_transmit_apdu_t(card, apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); return r; } static int get_data(struct sc_card *card, unsigned char type, unsigned char *data, size_t datalen) { int r; struct sc_apdu apdu; unsigned char resp[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; size_t resplen = SC_MAX_APDU_BUFFER_SIZE; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xca, 0x01, type); apdu.resp = resp; apdu.le = 0; apdu.resplen = resplen; if (0x86 == type) { /* No SM temporarily */ unsigned char tmp_sm = exdata->sm; exdata->sm = SM_PLAIN; r = sc_transmit_apdu(card, &apdu); exdata->sm = tmp_sm; } else { r = sc_transmit_apdu_t(card, &apdu); } LOG_TEST_RET(card->ctx, r, "APDU get_data failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "get_data failed"); memcpy(data, resp, datalen); return r; } /* card driver functions */ static int epass2003_match_card(struct sc_card *card) { int r; LOG_FUNC_CALLED(card->ctx); r = _sc_match_atr(card, epass2003_atrs, &card->type); if (r < 0) return 0; return 1; } static int epass2003_init(struct sc_card *card) { unsigned int flags; unsigned int ext_flags; unsigned char data[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; size_t datalen = SC_MAX_APDU_BUFFER_SIZE; epass2003_exdata *exdata = NULL; LOG_FUNC_CALLED(card->ctx); card->name = "epass2003"; card->cla = 0x00; exdata = (epass2003_exdata *)calloc(1, sizeof(epass2003_exdata)); if (!exdata) return SC_ERROR_OUT_OF_MEMORY; card->drv_data = exdata; exdata->sm = SM_SCP01; /* decide FIPS/Non-FIPS mode */ if (SC_SUCCESS != get_data(card, 0x86, data, datalen)) return SC_ERROR_INVALID_CARD; if (0x01 == data[2]) exdata->smtype = KEY_TYPE_AES; else exdata->smtype = KEY_TYPE_DES; if (0x84 == data[14]) { if (0x00 == data[16]) { exdata->sm = SM_PLAIN; } } /* mutual authentication */ card->max_recv_size = 0xD8; card->max_send_size = 0xE8; card->sm_ctx.ops.open = epass2003_refresh; card->sm_ctx.ops.get_sm_apdu = epass2003_sm_get_wrapped_apdu; card->sm_ctx.ops.free_sm_apdu = epass2003_sm_free_wrapped_apdu; /* FIXME (VT): rather then set/unset 'g_sm', better to implement filter for APDUs to be wrapped */ epass2003_refresh(card); card->sm_ctx.sm_mode = SM_MODE_TRANSMIT; flags = SC_ALGORITHM_ONBOARD_KEY_GEN | SC_ALGORITHM_RSA_RAW | SC_ALGORITHM_RSA_HASH_NONE; _sc_card_add_rsa_alg(card, 512, flags, 0); _sc_card_add_rsa_alg(card, 768, flags, 0); _sc_card_add_rsa_alg(card, 1024, flags, 0); _sc_card_add_rsa_alg(card, 2048, flags, 0); //set EC Alg Flags flags = SC_ALGORITHM_ONBOARD_KEY_GEN|SC_ALGORITHM_ECDSA_HASH_SHA1|SC_ALGORITHM_ECDSA_HASH_SHA256|SC_ALGORITHM_ECDSA_HASH_NONE|SC_ALGORITHM_ECDSA_RAW; ext_flags = 0; _sc_card_add_ec_alg(card, 256, flags, ext_flags, NULL); card->caps = SC_CARD_CAP_RNG | SC_CARD_CAP_APDU_EXT; LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_finish(sc_card_t *card) { epass2003_exdata *exdata = (epass2003_exdata *)card->drv_data; if (exdata) free(exdata); return SC_SUCCESS; } /* COS implement SFI as lower 5 bits of FID, and not allow same SFI at the * same DF, so use hook functions to increase/decrease FID by 0x20 */ static int epass2003_hook_path(struct sc_path *path, int inc) { u8 fid_h = path->value[path->len - 2]; u8 fid_l = path->value[path->len - 1]; switch (fid_h) { case 0x29: case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: if (inc) fid_l = fid_l * FID_STEP; else fid_l = fid_l / FID_STEP; path->value[path->len - 1] = fid_l; return 1; default: break; } return 0; } static void epass2003_hook_file(struct sc_file *file, int inc) { int fidl = file->id & 0xff; int fidh = file->id & 0xff00; if (epass2003_hook_path(&file->path, inc)) { if (inc) file->id = fidh + fidl * FID_STEP; else file->id = fidh + fidl / FID_STEP; } } static int epass2003_select_fid_(struct sc_card *card, sc_path_t * in_path, sc_file_t ** file_out) { struct sc_apdu apdu; u8 buf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; u8 pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf; int r, pathlen; sc_file_t *file = NULL; epass2003_hook_path(in_path, 1); memcpy(path, in_path->value, in_path->len); pathlen = in_path->len; sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0x00, 0x00); switch (in_path->type) { case SC_PATH_TYPE_FILE_ID: apdu.p1 = 0; if (pathlen != 2) return SC_ERROR_INVALID_ARGUMENTS; break; default: LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); } apdu.p2 = 0; /* first record, return FCI */ apdu.lc = pathlen; apdu.data = path; apdu.datalen = pathlen; if (file_out != NULL) { apdu.resp = buf; apdu.resplen = sizeof(buf); apdu.le = 0; } else { apdu.cse = (apdu.lc == 0) ? SC_APDU_CASE_1 : SC_APDU_CASE_3_SHORT; } if (path[0] == 0x29) { /* TODO:0x29 accords with FID prefix in profile */ /* Not allowed to select private key file, so fake fci. */ /* 62 16 82 02 11 00 83 02 29 00 85 02 08 00 86 08 FF 90 90 90 FF FF FF FF */ apdu.resplen = 0x18; memcpy(apdu.resp, "\x6f\x16\x82\x02\x11\x00\x83\x02\x29\x00\x85\x02\x08\x00\x86\x08\xff\x90\x90\x90\xff\xff\xff\xff", apdu.resplen); apdu.resp[9] = path[1]; apdu.sw1 = 0x90; apdu.sw2 = 0x00; } else { r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); } if (file_out == NULL) { if (apdu.sw1 == 0x61) LOG_FUNC_RETURN(card->ctx, 0); LOG_FUNC_RETURN(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2)); } r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r) LOG_FUNC_RETURN(card->ctx, r); if (apdu.resplen < 2) LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED); switch (apdu.resp[0]) { case 0x6F: file = sc_file_new(); if (file == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); file->path = *in_path; if (card->ops->process_fci == NULL) { sc_file_free(file); LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); } if ((size_t) apdu.resp[1] + 2 <= apdu.resplen) card->ops->process_fci(card, file, apdu.resp + 2, apdu.resp[1]); epass2003_hook_file(file, 0); *file_out = file; break; case 0x00: /* proprietary coding */ LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED); break; default: LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED); } return 0; } static int epass2003_select_fid(struct sc_card *card, unsigned int id_hi, unsigned int id_lo, sc_file_t ** file_out) { int r; sc_file_t *file = 0; sc_path_t path; memset(&path, 0, sizeof(path)); path.type = SC_PATH_TYPE_FILE_ID; path.value[0] = id_hi; path.value[1] = id_lo; path.len = 2; r = epass2003_select_fid_(card, &path, &file); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); /* update cache */ if (file && file->type == SC_FILE_TYPE_DF) { card->cache.current_path.type = SC_PATH_TYPE_PATH; card->cache.current_path.value[0] = 0x3f; card->cache.current_path.value[1] = 0x00; if (id_hi == 0x3f && id_lo == 0x00) { card->cache.current_path.len = 2; } else { card->cache.current_path.len = 4; card->cache.current_path.value[2] = id_hi; card->cache.current_path.value[3] = id_lo; } } if (file_out) *file_out = file; LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_select_aid(struct sc_card *card, const sc_path_t * in_path, sc_file_t ** file_out) { int r = 0; if (card->cache.valid && card->cache.current_path.type == SC_PATH_TYPE_DF_NAME && card->cache.current_path.len == in_path->len && memcmp(card->cache.current_path.value, in_path->value, in_path->len) == 0) { if (file_out) { *file_out = sc_file_new(); if (!file_out) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); } } else { r = iso_ops->select_file(card, in_path, file_out); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); /* update cache */ card->cache.current_path.type = SC_PATH_TYPE_DF_NAME; card->cache.current_path.len = in_path->len; memcpy(card->cache.current_path.value, in_path->value, in_path->len); } if (file_out) { sc_file_t *file = *file_out; file->type = SC_FILE_TYPE_DF; file->ef_structure = SC_FILE_EF_UNKNOWN; file->path.len = 0; file->size = 0; /* AID */ memcpy(file->name, in_path->value, in_path->len); file->namelen = in_path->len; file->id = 0x0000; } LOG_FUNC_RETURN(card->ctx, r); } static int epass2003_select_path(struct sc_card *card, const u8 pathbuf[16], const size_t len, sc_file_t ** file_out) { u8 n_pathbuf[SC_MAX_PATH_SIZE]; const u8 *path = pathbuf; size_t pathlen = len; int bMatch = -1; unsigned int i; int r; if (pathlen % 2 != 0 || pathlen > 6 || pathlen <= 0) LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); /* if pathlen == 6 then the first FID must be MF (== 3F00) */ if (pathlen == 6 && (path[0] != 0x3f || path[1] != 0x00)) LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); /* unify path (the first FID should be MF) */ if (path[0] != 0x3f || path[1] != 0x00) { n_pathbuf[0] = 0x3f; n_pathbuf[1] = 0x00; for (i = 0; i < pathlen; i++) n_pathbuf[i + 2] = pathbuf[i]; path = n_pathbuf; pathlen += 2; } /* check current working directory */ if (card->cache.valid && card->cache.current_path.type == SC_PATH_TYPE_PATH && card->cache.current_path.len >= 2 && card->cache.current_path.len <= pathlen) { bMatch = 0; for (i = 0; i < card->cache.current_path.len; i += 2) if (card->cache.current_path.value[i] == path[i] && card->cache.current_path.value[i + 1] == path[i + 1]) bMatch += 2; } if (card->cache.valid && bMatch > 2) { if (pathlen - bMatch == 2) { /* we are in the right directory */ return epass2003_select_fid(card, path[bMatch], path[bMatch + 1], file_out); } else if (pathlen - bMatch > 2) { /* two more steps to go */ sc_path_t new_path; /* first step: change directory */ r = epass2003_select_fid(card, path[bMatch], path[bMatch + 1], NULL); LOG_TEST_RET(card->ctx, r, "SELECT FILE (DF-ID) failed"); new_path.type = SC_PATH_TYPE_PATH; new_path.len = pathlen - bMatch - 2; memcpy(new_path.value, &(path[bMatch + 2]), new_path.len); /* final step: select file */ return epass2003_select_file(card, &new_path, file_out); } else { /* if (bMatch - pathlen == 0) */ /* done: we are already in the * requested directory */ sc_log(card->ctx, "cache hit\n"); /* copy file info (if necessary) */ if (file_out) { sc_file_t *file = sc_file_new(); if (!file) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); file->id = (path[pathlen - 2] << 8) + path[pathlen - 1]; file->path = card->cache.current_path; file->type = SC_FILE_TYPE_DF; file->ef_structure = SC_FILE_EF_UNKNOWN; file->size = 0; file->namelen = 0; file->magic = SC_FILE_MAGIC; *file_out = file; } /* nothing left to do */ return SC_SUCCESS; } } else { /* no usable cache */ for (i = 0; i < pathlen - 2; i += 2) { r = epass2003_select_fid(card, path[i], path[i + 1], NULL); LOG_TEST_RET(card->ctx, r, "SELECT FILE (DF-ID) failed"); } return epass2003_select_fid(card, path[pathlen - 2], path[pathlen - 1], file_out); } } static int epass2003_select_file(struct sc_card *card, const sc_path_t * in_path, sc_file_t ** file_out) { int r; char pbuf[SC_MAX_PATH_STRING_SIZE]; LOG_FUNC_CALLED(card->ctx); r = sc_path_print(pbuf, sizeof(pbuf), &card->cache.current_path); if (r != SC_SUCCESS) pbuf[0] = '\0'; sc_log(card->ctx, "current path (%s, %s): %s (len: %"SC_FORMAT_LEN_SIZE_T"u)\n", card->cache.current_path.type == SC_PATH_TYPE_DF_NAME ? "aid" : "path", card->cache.valid ? "valid" : "invalid", pbuf, card->cache.current_path.len); switch (in_path->type) { case SC_PATH_TYPE_FILE_ID: if (in_path->len != 2) LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); return epass2003_select_fid(card, in_path->value[0], in_path->value[1], file_out); case SC_PATH_TYPE_DF_NAME: return epass2003_select_aid(card, in_path, file_out); case SC_PATH_TYPE_PATH: return epass2003_select_path(card, in_path->value, in_path->len, file_out); default: LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); } } static int epass2003_set_security_env(struct sc_card *card, const sc_security_env_t * env, int se_num) { struct sc_apdu apdu; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; u8 *p; unsigned short fid = 0; int r, locked = 0; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x41, 0); p = sbuf; *p++ = 0x80; /* algorithm reference */ *p++ = 0x01; *p++ = 0x84; *p++ = 0x81; *p++ = 0x02; fid = 0x2900; fid += (unsigned short)(0x20 * (env->key_ref[0] & 0xff)); *p++ = fid >> 8; *p++ = fid & 0xff; r = p - sbuf; apdu.lc = r; apdu.datalen = r; apdu.data = sbuf; if (env->algorithm == SC_ALGORITHM_EC) { apdu.p2 = 0xB6; exdata->currAlg = SC_ALGORITHM_EC; if(env->algorithm_flags & SC_ALGORITHM_ECDSA_HASH_SHA1) { sbuf[2] = 0x91; exdata->ecAlgFlags = SC_ALGORITHM_ECDSA_HASH_SHA1; } else if (env->algorithm_flags & SC_ALGORITHM_ECDSA_HASH_SHA256) { sbuf[2] = 0x92; exdata->ecAlgFlags = SC_ALGORITHM_ECDSA_HASH_SHA256; } else { sc_log(card->ctx, "%0x Alg Not Support! ", env->algorithm_flags); goto err; } } else if(env->algorithm == SC_ALGORITHM_RSA) { exdata->currAlg = SC_ALGORITHM_RSA; apdu.p2 = 0xB8; sc_log(card->ctx, "setenv RSA Algorithm alg_flags = %0x\n",env->algorithm_flags); } else { sc_log(card->ctx, "%0x Alg Not Support! ", env->algorithm); } if (se_num > 0) { r = sc_lock(card); LOG_TEST_RET(card->ctx, r, "sc_lock() failed"); locked = 1; } if (apdu.datalen != 0) { r = sc_transmit_apdu_t(card, &apdu); if (r) { sc_log(card->ctx, "%s: APDU transmit failed", sc_strerror(r)); goto err; } r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r) { sc_log(card->ctx, "%s: Card returned error", sc_strerror(r)); goto err; } } if (se_num <= 0) return 0; sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0xF2, se_num); r = sc_transmit_apdu_t(card, &apdu); sc_unlock(card); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); return sc_check_sw(card, apdu.sw1, apdu.sw2); err: if (locked) sc_unlock(card); return r; } static int epass2003_restore_security_env(struct sc_card *card, int se_num) { LOG_FUNC_CALLED(card->ctx); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_decipher(struct sc_card *card, const u8 * data, size_t datalen, u8 * out, size_t outlen) { int r; struct sc_apdu apdu; u8 rbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; epass2003_exdata *exdata = NULL; LOG_FUNC_CALLED(card->ctx); if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; if(exdata->currAlg == SC_ALGORITHM_EC) { if(exdata->ecAlgFlags & SC_ALGORITHM_ECDSA_HASH_SHA1) { r = hash_data(data, datalen, sbuf, SC_ALGORITHM_ECDSA_HASH_SHA1); LOG_TEST_RET(card->ctx, r, "hash_data failed"); sc_format_apdu(card, &apdu, SC_APDU_CASE_3,0x2A, 0x9E, 0x9A); apdu.data = sbuf; apdu.lc = 0x14; apdu.datalen = 0x14; } else if (exdata->ecAlgFlags & SC_ALGORITHM_ECDSA_HASH_SHA256) { r = hash_data(data, datalen, sbuf, SC_ALGORITHM_ECDSA_HASH_SHA256); LOG_TEST_RET(card->ctx, r, "hash_data failed"); sc_format_apdu(card, &apdu, SC_APDU_CASE_3,0x2A, 0x9E, 0x9A); apdu.data = sbuf; apdu.lc = 0x20; apdu.datalen = 0x20; } else { return SC_ERROR_NOT_SUPPORTED; } apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 0; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); if (apdu.sw1 == 0x90 && apdu.sw2 == 0x00) { size_t len = apdu.resplen > outlen ? outlen : apdu.resplen; memcpy(out, apdu.resp, len); LOG_FUNC_RETURN(card->ctx, len); } LOG_FUNC_RETURN(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2)); } else if(exdata->currAlg == SC_ALGORITHM_RSA) { sc_format_apdu(card, &apdu, SC_APDU_CASE_4_EXT, 0x2A, 0x80, 0x86); apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 0; memcpy(sbuf, data, datalen); apdu.data = sbuf; apdu.lc = datalen; apdu.datalen = datalen; } else { sc_format_apdu(card, &apdu, SC_APDU_CASE_4_EXT, 0x2A, 0x80, 0x86); apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 256; memcpy(sbuf, data, datalen); apdu.data = sbuf; apdu.lc = datalen; apdu.datalen = datalen; } r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); if (apdu.sw1 == 0x90 && apdu.sw2 == 0x00) { size_t len = apdu.resplen > outlen ? outlen : apdu.resplen; memcpy(out, apdu.resp, len); LOG_FUNC_RETURN(card->ctx, len); } LOG_FUNC_RETURN(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2)); } static int acl_to_ac_byte(struct sc_card *card, const struct sc_acl_entry *e) { if (e == NULL) return SC_ERROR_OBJECT_NOT_FOUND; switch (e->method) { case SC_AC_NONE: LOG_FUNC_RETURN(card->ctx, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE); case SC_AC_NEVER: LOG_FUNC_RETURN(card->ctx, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_NOONE); default: LOG_FUNC_RETURN(card->ctx, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_USER); } LOG_FUNC_RETURN(card->ctx, SC_ERROR_INCORRECT_PARAMETERS); } static int epass2003_process_fci(struct sc_card *card, sc_file_t * file, const u8 * buf, size_t buflen) { sc_context_t *ctx = card->ctx; size_t taglen, len = buflen; const u8 *tag = NULL, *p = buf; sc_log(ctx, "processing FCI bytes"); tag = sc_asn1_find_tag(ctx, p, len, 0x83, &taglen); if (tag != NULL && taglen == 2) { file->id = (tag[0] << 8) | tag[1]; sc_log(ctx, " file identifier: 0x%02X%02X", tag[0], tag[1]); } tag = sc_asn1_find_tag(ctx, p, len, 0x80, &taglen); if (tag != NULL && taglen > 0 && taglen < 3) { file->size = tag[0]; if (taglen == 2) file->size = (file->size << 8) + tag[1]; sc_log(ctx, " bytes in file: %"SC_FORMAT_LEN_SIZE_T"u", file->size); } if (tag == NULL) { tag = sc_asn1_find_tag(ctx, p, len, 0x81, &taglen); if (tag != NULL && taglen >= 2) { int bytes = (tag[0] << 8) + tag[1]; sc_log(ctx, " bytes in file: %d", bytes); file->size = bytes; } } tag = sc_asn1_find_tag(ctx, p, len, 0x82, &taglen); if (tag != NULL) { if (taglen > 0) { unsigned char byte = tag[0]; const char *type; if (byte == 0x38) { type = "DF"; file->type = SC_FILE_TYPE_DF; } else if (0x01 <= byte && byte <= 0x07) { type = "working EF"; file->type = SC_FILE_TYPE_WORKING_EF; switch (byte) { case 0x01: file->ef_structure = SC_FILE_EF_TRANSPARENT; break; case 0x02: file->ef_structure = SC_FILE_EF_LINEAR_FIXED; break; case 0x04: file->ef_structure = SC_FILE_EF_LINEAR_FIXED; break; case 0x03: case 0x05: case 0x06: case 0x07: break; default: break; } } else if (0x10 == byte) { type = "BSO"; file->type = SC_FILE_TYPE_BSO; } else if (0x11 <= byte) { type = "internal EF"; file->type = SC_FILE_TYPE_INTERNAL_EF; switch (byte) { case 0x11: break; case 0x12: break; default: break; } } else { type = "unknown"; file->type = SC_FILE_TYPE_INTERNAL_EF; } sc_log(ctx, "type %s, EF structure %d", type, byte); } } tag = sc_asn1_find_tag(ctx, p, len, 0x84, &taglen); if (tag != NULL && taglen > 0 && taglen <= 16) { memcpy(file->name, tag, taglen); file->namelen = taglen; sc_log_hex(ctx, "File name", file->name, file->namelen); if (!file->type) file->type = SC_FILE_TYPE_DF; } tag = sc_asn1_find_tag(ctx, p, len, 0x85, &taglen); if (tag != NULL && taglen) sc_file_set_prop_attr(file, tag, taglen); else file->prop_attr_len = 0; tag = sc_asn1_find_tag(ctx, p, len, 0xA5, &taglen); if (tag != NULL && taglen) sc_file_set_prop_attr(file, tag, taglen); tag = sc_asn1_find_tag(ctx, p, len, 0x86, &taglen); if (tag != NULL && taglen) sc_file_set_sec_attr(file, tag, taglen); tag = sc_asn1_find_tag(ctx, p, len, 0x8A, &taglen); if (tag != NULL && taglen == 1) { if (tag[0] == 0x01) file->status = SC_FILE_STATUS_CREATION; else if (tag[0] == 0x07 || tag[0] == 0x05) file->status = SC_FILE_STATUS_ACTIVATED; else if (tag[0] == 0x06 || tag[0] == 0x04) file->status = SC_FILE_STATUS_INVALIDATED; } file->magic = SC_FILE_MAGIC; return 0; } static int epass2003_construct_fci(struct sc_card *card, const sc_file_t * file, u8 * out, size_t * outlen) { u8 *p = out; u8 buf[64]; unsigned char ops[8] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; int rv; unsigned ii; if (*outlen < 2) return SC_ERROR_BUFFER_TOO_SMALL; *p++ = 0x62; p++; if (file->type == SC_FILE_TYPE_WORKING_EF) { if (file->ef_structure == SC_FILE_EF_TRANSPARENT) { buf[0] = (file->size >> 8) & 0xFF; buf[1] = file->size & 0xFF; sc_asn1_put_tag(0x80, buf, 2, p, *outlen - (p - out), &p); } } if (file->type == SC_FILE_TYPE_DF) { buf[0] = 0x38; buf[1] = 0x00; sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p); } else if (file->type == SC_FILE_TYPE_WORKING_EF) { buf[0] = file->ef_structure & 7; if (file->ef_structure == SC_FILE_EF_TRANSPARENT) { buf[1] = 0x00; sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p); } else if (file->ef_structure == SC_FILE_EF_LINEAR_FIXED || file->ef_structure == SC_FILE_EF_LINEAR_VARIABLE) { buf[1] = 0x00; buf[2] = 0x00; buf[3] = 0x40; /* record length */ buf[4] = 0x00; /* record count */ sc_asn1_put_tag(0x82, buf, 5, p, *outlen - (p - out), &p); } else { return SC_ERROR_NOT_SUPPORTED; } } else if (file->type == SC_FILE_TYPE_INTERNAL_EF) { if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_CRT || file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_CRT) { buf[0] = 0x11; buf[1] = 0x00; } else if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC || file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) { buf[0] = 0x12; buf[1] = 0x00; } else { return SC_ERROR_NOT_SUPPORTED; } sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p); } else if (file->type == SC_FILE_TYPE_BSO) { buf[0] = 0x10; buf[1] = 0x00; sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p); } buf[0] = (file->id >> 8) & 0xFF; buf[1] = file->id & 0xFF; sc_asn1_put_tag(0x83, buf, 2, p, *outlen - (p - out), &p); if (file->type == SC_FILE_TYPE_DF) { if (file->namelen != 0) { sc_asn1_put_tag(0x84, file->name, file->namelen, p, *outlen - (p - out), &p); } else { return SC_ERROR_INVALID_ARGUMENTS; } } if (file->type == SC_FILE_TYPE_DF) { unsigned char data[2] = {0x00, 0x7F}; /* 127 files at most */ sc_asn1_put_tag(0x85, data, sizeof(data), p, *outlen - (p - out), &p); } else if (file->type == SC_FILE_TYPE_BSO) { buf[0] = file->size & 0xff; sc_asn1_put_tag(0x85, buf, 1, p, *outlen - (p - out), &p); } else if (file->type == SC_FILE_TYPE_INTERNAL_EF) { if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_CRT || file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC|| file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_CRT|| file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) { buf[0] = (file->size >> 8) & 0xFF; buf[1] = file->size & 0xFF; sc_asn1_put_tag(0x85, buf, 2, p, *outlen - (p - out), &p); } } if (file->sec_attr_len) { memcpy(buf, file->sec_attr, file->sec_attr_len); sc_asn1_put_tag(0x86, buf, file->sec_attr_len, p, *outlen - (p - out), &p); } else { sc_log(card->ctx, "SC_FILE_ACL"); if (file->type == SC_FILE_TYPE_DF) { ops[0] = SC_AC_OP_LIST_FILES; ops[1] = SC_AC_OP_CREATE; ops[3] = SC_AC_OP_DELETE; } else if (file->type == SC_FILE_TYPE_WORKING_EF) { if (file->ef_structure == SC_FILE_EF_TRANSPARENT) { ops[0] = SC_AC_OP_READ; ops[1] = SC_AC_OP_UPDATE; ops[3] = SC_AC_OP_DELETE; } else if (file->ef_structure == SC_FILE_EF_LINEAR_FIXED || file->ef_structure == SC_FILE_EF_LINEAR_VARIABLE) { ops[0] = SC_AC_OP_READ; ops[1] = SC_AC_OP_UPDATE; ops[2] = SC_AC_OP_WRITE; ops[3] = SC_AC_OP_DELETE; } else { return SC_ERROR_NOT_SUPPORTED; } } else if (file->type == SC_FILE_TYPE_BSO) { ops[0] = SC_AC_OP_UPDATE; ops[3] = SC_AC_OP_DELETE; } else if (file->type == SC_FILE_TYPE_INTERNAL_EF) { if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_CRT || file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_CRT) { ops[1] = SC_AC_OP_UPDATE; ops[2] = SC_AC_OP_CRYPTO; ops[3] = SC_AC_OP_DELETE; } else if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC|| file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) { ops[0] = SC_AC_OP_READ; ops[1] = SC_AC_OP_UPDATE; ops[2] = SC_AC_OP_CRYPTO; ops[3] = SC_AC_OP_DELETE; } } else { return SC_ERROR_NOT_SUPPORTED; } for (ii = 0; ii < sizeof(ops); ii++) { const struct sc_acl_entry *entry; buf[ii] = 0xFF; if (ops[ii] == 0xFF) continue; entry = sc_file_get_acl_entry(file, ops[ii]); rv = acl_to_ac_byte(card, entry); LOG_TEST_RET(card->ctx, rv, "Invalid ACL"); buf[ii] = rv; } sc_asn1_put_tag(0x86, buf, sizeof(ops), p, *outlen - (p - out), &p); if(file->size == 256) { out[4]= 0x13; } } /* VT ??? */ if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC|| file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) { unsigned char data[2] = {0x00, 0x66}; sc_asn1_put_tag(0x87, data, sizeof(data), p, *outlen - (p - out), &p); if(file->size == 256) { out[4]= 0x14; } } out[1] = p - out - 2; *outlen = p - out; return 0; } static int epass2003_create_file(struct sc_card *card, sc_file_t * file) { int r; size_t len; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; struct sc_apdu apdu; len = SC_MAX_APDU_BUFFER_SIZE; epass2003_hook_file(file, 1); if (card->ops->construct_fci == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); r = epass2003_construct_fci(card, file, sbuf, &len); LOG_TEST_RET(card->ctx, r, "construct_fci() failed"); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE0, 0x00, 0x00); apdu.lc = len; apdu.datalen = len; apdu.data = sbuf; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "APDU sw1/2 wrong"); epass2003_hook_file(file, 0); return r; } static int epass2003_delete_file(struct sc_card *card, const sc_path_t * path) { int r; u8 sbuf[2]; struct sc_apdu apdu; LOG_FUNC_CALLED(card->ctx); r = sc_select_file(card, path, NULL); epass2003_hook_path((struct sc_path *)path, 1); if (r == SC_SUCCESS) { sbuf[0] = path->value[path->len - 2]; sbuf[1] = path->value[path->len - 1]; sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE4, 0x00, 0x00); apdu.lc = 2; apdu.datalen = 2; apdu.data = sbuf; } else { LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); } r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "Delete file failed"); LOG_FUNC_RETURN(card->ctx, r); } static int epass2003_list_files(struct sc_card *card, unsigned char *buf, size_t buflen) { struct sc_apdu apdu; unsigned char rbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x34, 0x00, 0x00); apdu.cla = 0x80; apdu.le = 0; apdu.resplen = sizeof(rbuf); apdu.resp = rbuf; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "Card returned error"); if (apdu.resplen == 0x100 && rbuf[0] == 0 && rbuf[1] == 0) LOG_FUNC_RETURN(card->ctx, 0); buflen = buflen < apdu.resplen ? buflen : apdu.resplen; memcpy(buf, rbuf, buflen); LOG_FUNC_RETURN(card->ctx, buflen); } static int internal_write_rsa_key_factor(struct sc_card *card, unsigned short fid, u8 factor, sc_pkcs15_bignum_t data) { int r; struct sc_apdu apdu; u8 sbuff[SC_MAX_EXT_APDU_BUFFER_SIZE] = { 0 }; LOG_FUNC_CALLED(card->ctx); sbuff[0] = ((fid & 0xff00) >> 8); sbuff[1] = (fid & 0x00ff); memcpy(&sbuff[2], data.data, data.len); // sc_mem_reverse(&sbuff[2], data.len); sc_format_apdu(card, &apdu, SC_APDU_CASE_3, 0xe7, factor, 0x00); apdu.cla = 0x80; apdu.lc = apdu.datalen = 2 + data.len; apdu.data = sbuff; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "Write rsa key factor failed"); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int internal_write_rsa_key(struct sc_card *card, unsigned short fid, struct sc_pkcs15_prkey_rsa *rsa) { int r; LOG_FUNC_CALLED(card->ctx); r = internal_write_rsa_key_factor(card, fid, 0x02, rsa->modulus); LOG_TEST_RET(card->ctx, r, "write n failed"); r = internal_write_rsa_key_factor(card, fid, 0x03, rsa->d); LOG_TEST_RET(card->ctx, r, "write d failed"); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int hash_data(const unsigned char *data, size_t datalen, unsigned char *hash, unsigned int mechanismType) { if ((NULL == data) || (NULL == hash)) return SC_ERROR_INVALID_ARGUMENTS; if(mechanismType & SC_ALGORITHM_ECDSA_HASH_SHA1) { unsigned char data_hash[24] = { 0 }; size_t len = 0; sha1_digest(data, datalen, data_hash); len = REVERSE_ORDER4(datalen); memcpy(&data_hash[20], &len, 4); memcpy(hash, data_hash, 24); } else if(mechanismType & SC_ALGORITHM_ECDSA_HASH_SHA256) { unsigned char data_hash[36] = { 0 }; size_t len = 0; sha256_digest(data, datalen, data_hash); len = REVERSE_ORDER4(datalen); memcpy(&data_hash[32], &len, 4); memcpy(hash, data_hash, 36); } else { return SC_ERROR_NOT_SUPPORTED; } return SC_SUCCESS; } static int install_secret_key(struct sc_card *card, unsigned char ktype, unsigned char kid, unsigned char useac, unsigned char modifyac, unsigned char EC, unsigned char *data, unsigned long dataLen) { int r; struct sc_apdu apdu; unsigned char isapp = 0x00; /* appendable */ unsigned char tmp_data[256] = { 0 }; tmp_data[0] = ktype; tmp_data[1] = kid; tmp_data[2] = useac; tmp_data[3] = modifyac; tmp_data[8] = 0xFF; if (0x04 == ktype || 0x06 == ktype) { tmp_data[4] = EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_SO; tmp_data[5] = EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_SO; tmp_data[7] = (kid == PIN_ID[0] ? EPASS2003_AC_USER : EPASS2003_AC_SO); tmp_data[9] = (EC << 4) | EC; } memcpy(&tmp_data[10], data, dataLen); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xe3, isapp, 0x00); apdu.cla = 0x80; apdu.lc = apdu.datalen = 10 + dataLen; apdu.data = tmp_data; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU install_secret_key failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "install_secret_key failed"); return r; } static int internal_install_pre(struct sc_card *card) { int r; /* init key for enc */ r = install_secret_key(card, 0x01, 0x00, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE, 0, g_init_key_enc, 16); LOG_TEST_RET(card->ctx, r, "Install init key failed"); /* init key for mac */ r = install_secret_key(card, 0x02, 0x00, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE, 0, g_init_key_mac, 16); LOG_TEST_RET(card->ctx, r, "Install init key failed"); return r; } /* use external auth secret as pin */ static int internal_install_pin(struct sc_card *card, sc_epass2003_wkey_data * pin) { int r; unsigned char hash[HASH_LEN] = { 0 }; r = hash_data(pin->key_data.es_secret.key_val, pin->key_data.es_secret.key_len, hash, SC_ALGORITHM_ECDSA_HASH_SHA1); LOG_TEST_RET(card->ctx, r, "hash data failed"); r = install_secret_key(card, 0x04, pin->key_data.es_secret.kid, pin->key_data.es_secret.ac[0], pin->key_data.es_secret.ac[1], pin->key_data.es_secret.EC, hash, HASH_LEN); LOG_TEST_RET(card->ctx, r, "Install failed"); return r; } static int epass2003_write_key(struct sc_card *card, sc_epass2003_wkey_data * data) { LOG_FUNC_CALLED(card->ctx); if (data->type & SC_EPASS2003_KEY) { if (data->type == SC_EPASS2003_KEY_RSA) return internal_write_rsa_key(card, data->key_data.es_key.fid, data->key_data.es_key.rsa); else LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); } else if (data->type & SC_EPASS2003_SECRET) { if (data->type == SC_EPASS2003_SECRET_PRE) return internal_install_pre(card); else if (data->type == SC_EPASS2003_SECRET_PIN) return internal_install_pin(card, data); else LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); } else { LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); } LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_gen_key(struct sc_card *card, sc_epass2003_gen_key_data * data) { int r; size_t len = data->key_length; struct sc_apdu apdu; u8 rbuf[SC_MAX_EXT_APDU_BUFFER_SIZE] = { 0 }; u8 sbuf[SC_MAX_EXT_APDU_BUFFER_SIZE] = { 0 }; LOG_FUNC_CALLED(card->ctx); if(len == 256) { sbuf[0] = 0x02; } else { sbuf[0] = 0x01; } sbuf[1] = (u8) ((len >> 8) & 0xff); sbuf[2] = (u8) (len & 0xff); sbuf[3] = (u8) ((data->prkey_id >> 8) & 0xFF); sbuf[4] = (u8) ((data->prkey_id) & 0xFF); sbuf[5] = (u8) ((data->pukey_id >> 8) & 0xFF); sbuf[6] = (u8) ((data->pukey_id) & 0xFF); /* generate key */ sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x46, 0x00, 0x00); apdu.lc = apdu.datalen = 7; apdu.data = sbuf; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "generate keypair failed"); /* read public key */ sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xb4, 0x02, 0x00); if(len == 256) { apdu.p1 = 0x00; } apdu.cla = 0x80; apdu.lc = apdu.datalen = 2; apdu.data = &sbuf[5]; apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 0x00; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "get pukey failed"); if (len < apdu.resplen) LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); data->modulus = (u8 *) malloc(len); if (!data->modulus) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); memcpy(data->modulus, rbuf, len); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_erase_card(struct sc_card *card) { int r; LOG_FUNC_CALLED(card->ctx); sc_invalidate_cache(card); r = sc_delete_file(card, sc_get_mf_path()); LOG_TEST_RET(card->ctx, r, "delete MF failed"); LOG_FUNC_RETURN(card->ctx, r); } static int epass2003_get_serialnr(struct sc_card *card, sc_serial_number_t * serial) { u8 rbuf[8]; size_t rbuf_len = sizeof(rbuf); LOG_FUNC_CALLED(card->ctx); if (SC_SUCCESS != get_data(card, 0x80, rbuf, rbuf_len)) return SC_ERROR_CARD_CMD_FAILED; card->serialnr.len = serial->len = 8; memcpy(card->serialnr.value, rbuf, 8); memcpy(serial->value, rbuf, 8); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_card_ctl(struct sc_card *card, unsigned long cmd, void *ptr) { LOG_FUNC_CALLED(card->ctx); sc_log(card->ctx, "cmd is %0lx", cmd); switch (cmd) { case SC_CARDCTL_ENTERSAFE_WRITE_KEY: return epass2003_write_key(card, (sc_epass2003_wkey_data *) ptr); case SC_CARDCTL_ENTERSAFE_GENERATE_KEY: return epass2003_gen_key(card, (sc_epass2003_gen_key_data *) ptr); case SC_CARDCTL_ERASE_CARD: return epass2003_erase_card(card); case SC_CARDCTL_GET_SERIALNR: return epass2003_get_serialnr(card, (sc_serial_number_t *) ptr); default: return SC_ERROR_NOT_SUPPORTED; } } static void internal_sanitize_pin_info(struct sc_pin_cmd_pin *pin, unsigned int num) { pin->encoding = SC_PIN_ENCODING_ASCII; pin->min_length = 4; pin->max_length = 16; pin->pad_length = 16; pin->offset = 5 + num * 16; pin->pad_char = 0x00; } static int get_external_key_maxtries(struct sc_card *card, unsigned char *maxtries) { unsigned char maxcounter[2] = { 0 }; static const sc_path_t file_path = { {0x3f, 0x00, 0x50, 0x15, 0x9f, 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 6, 0, 0, SC_PATH_TYPE_PATH, {{0}, 0} }; int ret; ret = sc_select_file(card, &file_path, NULL); LOG_TEST_RET(card->ctx, ret, "select max counter file failed"); ret = sc_read_binary(card, 0, maxcounter, 2, 0); LOG_TEST_RET(card->ctx, ret, "read max counter file failed"); *maxtries = maxcounter[0]; return SC_SUCCESS; } static int get_external_key_retries(struct sc_card *card, unsigned char kid, unsigned char *retries) { int r; struct sc_apdu apdu; unsigned char random[16] = { 0 }; r = sc_get_challenge(card, random, 8); LOG_TEST_RET(card->ctx, r, "get challenge get_external_key_retries failed"); sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x82, 0x01, 0x80 | kid); apdu.resp = NULL; apdu.resplen = 0; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU get_external_key_retries failed"); if (retries && ((0x63 == (apdu.sw1 & 0xff)) && (0xC0 == (apdu.sw2 & 0xf0)))) { *retries = (apdu.sw2 & 0x0f); r = SC_SUCCESS; } else { LOG_TEST_RET(card->ctx, r, "get_external_key_retries failed"); r = SC_ERROR_CARD_CMD_FAILED; } return r; } static int epass2003_get_challenge(sc_card_t *card, u8 *rnd, size_t len) { u8 rbuf[16]; size_t out_len; int r; LOG_FUNC_CALLED(card->ctx); r = iso_ops->get_challenge(card, rbuf, sizeof rbuf); LOG_TEST_RET(card->ctx, r, "GET CHALLENGE cmd failed"); if (len < (size_t) r) { out_len = len; } else { out_len = (size_t) r; } memcpy(rnd, rbuf, out_len); LOG_FUNC_RETURN(card->ctx, (int) out_len); } static int external_key_auth(struct sc_card *card, unsigned char kid, unsigned char *data, size_t datalen) { int r; struct sc_apdu apdu; unsigned char random[16] = { 0 }; unsigned char tmp_data[16] = { 0 }; unsigned char hash[HASH_LEN] = { 0 }; unsigned char iv[16] = { 0 }; r = sc_get_challenge(card, random, 8); LOG_TEST_RET(card->ctx, r, "get challenge external_key_auth failed"); r = hash_data(data, datalen, hash, SC_ALGORITHM_ECDSA_HASH_SHA1); LOG_TEST_RET(card->ctx, r, "hash data failed"); des3_encrypt_cbc(hash, HASH_LEN, iv, random, 8, tmp_data); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x82, 0x01, 0x80 | kid); apdu.lc = apdu.datalen = 8; apdu.data = tmp_data; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU external_key_auth failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "external_key_auth failed"); return r; } static int update_secret_key(struct sc_card *card, unsigned char ktype, unsigned char kid, const unsigned char *data, unsigned long datalen) { int r; struct sc_apdu apdu; unsigned char hash[HASH_LEN] = { 0 }; unsigned char tmp_data[256] = { 0 }; unsigned char maxtries = 0; r = hash_data(data, datalen, hash, SC_ALGORITHM_ECDSA_HASH_SHA1); LOG_TEST_RET(card->ctx, r, "hash data failed"); r = get_external_key_maxtries(card, &maxtries); LOG_TEST_RET(card->ctx, r, "get max counter failed"); tmp_data[0] = (maxtries << 4) | maxtries; memcpy(&tmp_data[1], hash, HASH_LEN); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xe5, ktype, kid); apdu.cla = 0x80; apdu.lc = apdu.datalen = 1 + HASH_LEN; apdu.data = tmp_data; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU update_secret_key failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "update_secret_key failed"); return r; } /* use external auth secret as pin */ static int epass2003_pin_cmd(struct sc_card *card, struct sc_pin_cmd_data *data, int *tries_left) { int r; u8 kid; u8 retries = 0; u8 pin_low = 3; unsigned char maxtries = 0; LOG_FUNC_CALLED(card->ctx); internal_sanitize_pin_info(&data->pin1, 0); internal_sanitize_pin_info(&data->pin2, 1); data->flags |= SC_PIN_CMD_NEED_PADDING; kid = data->pin_reference; /* get pin retries */ if (data->cmd == SC_PIN_CMD_GET_INFO) { r = get_external_key_retries(card, 0x80 | kid, &retries); if (r == SC_SUCCESS) { data->pin1.tries_left = retries; if (tries_left) *tries_left = retries; r = get_external_key_maxtries(card, &maxtries); LOG_TEST_RET(card->ctx, r, "get max counter failed"); data->pin1.max_tries = maxtries; } //remove below code, because the old implement only return PIN retries, now modify the code and return PIN status // return r; } else if (data->cmd == SC_PIN_CMD_UNBLOCK) { /* verify */ r = external_key_auth(card, (kid + 1), (unsigned char *)data->pin1.data, data->pin1.len); LOG_TEST_RET(card->ctx, r, "verify pin failed"); } else if (data->cmd == SC_PIN_CMD_CHANGE || data->cmd == SC_PIN_CMD_UNBLOCK) { /* change */ r = update_secret_key(card, 0x04, kid, data->pin2.data, (unsigned long)data->pin2.len); LOG_TEST_RET(card->ctx, r, "verify pin failed"); } else { r = external_key_auth(card, kid, (unsigned char *)data->pin1.data, data->pin1.len); get_external_key_retries(card, 0x80 | kid, &retries); if (retries < pin_low) sc_log(card->ctx, "Verification failed (remaining tries: %d)", retries); } LOG_TEST_RET(card->ctx, r, "verify pin failed"); if (r == SC_SUCCESS) { data->pin1.logged_in = SC_PIN_STATE_LOGGED_IN; } return r; } static struct sc_card_driver *sc_get_driver(void) { struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); if (iso_ops == NULL) iso_ops = iso_drv->ops; epass2003_ops = *iso_ops; epass2003_ops.match_card = epass2003_match_card; epass2003_ops.init = epass2003_init; epass2003_ops.finish = epass2003_finish; epass2003_ops.write_binary = NULL; epass2003_ops.write_record = NULL; epass2003_ops.select_file = epass2003_select_file; epass2003_ops.get_response = NULL; epass2003_ops.restore_security_env = epass2003_restore_security_env; epass2003_ops.set_security_env = epass2003_set_security_env; epass2003_ops.decipher = epass2003_decipher; epass2003_ops.compute_signature = epass2003_decipher; epass2003_ops.create_file = epass2003_create_file; epass2003_ops.delete_file = epass2003_delete_file; epass2003_ops.list_files = epass2003_list_files; epass2003_ops.card_ctl = epass2003_card_ctl; epass2003_ops.process_fci = epass2003_process_fci; epass2003_ops.construct_fci = epass2003_construct_fci; epass2003_ops.pin_cmd = epass2003_pin_cmd; epass2003_ops.check_sw = epass2003_check_sw; epass2003_ops.get_challenge = epass2003_get_challenge; return &epass2003_drv; } struct sc_card_driver *sc_get_epass2003_driver(void) { return sc_get_driver(); } #endif /* #ifdef ENABLE_OPENSSL */ #endif /* #ifdef ENABLE_SM */
./CrossVul/dataset_final_sorted/CWE-119/c/good_340_1
crossvul-cpp_data_bad_4787_5
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % BBBB M M PPPP % % B B MM MM P P % % BBBB M M M PPPP % % B B M M P % % BBBB M M P % % % % % % Read/Write Microsoft Windows Bitmap Image Format % % % % Software Design % % Cristy % % Glenn Randers-Pehrson % % December 2001 % % % % % % Copyright 1999-2015 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/colormap-private.h" #include "magick/color-private.h" #include "magick/colormap.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/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/monitor.h" #include "magick/monitor-private.h" #include "magick/option.h" #include "magick/pixel-accessor.h" #include "magick/profile.h" #include "magick/quantum-private.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/module.h" #include "magick/transform.h" /* Macro definitions (from Windows wingdi.h). */ #undef BI_JPEG #define BI_JPEG 4 #undef BI_PNG #define BI_PNG 5 #if !defined(MAGICKCORE_WINDOWS_SUPPORT) || defined(__MINGW32__) || defined(__MINGW64__) #undef BI_RGB #define BI_RGB 0 #undef BI_RLE8 #define BI_RLE8 1 #undef BI_RLE4 #define BI_RLE4 2 #undef BI_BITFIELDS #define BI_BITFIELDS 3 #undef LCS_CALIBRATED_RBG #define LCS_CALIBRATED_RBG 0 #undef LCS_sRGB #define LCS_sRGB 1 #undef LCS_WINDOWS_COLOR_SPACE #define LCS_WINDOWS_COLOR_SPACE 2 #undef PROFILE_LINKED #define PROFILE_LINKED 3 #undef PROFILE_EMBEDDED #define PROFILE_EMBEDDED 4 #undef LCS_GM_BUSINESS #define LCS_GM_BUSINESS 1 /* Saturation */ #undef LCS_GM_GRAPHICS #define LCS_GM_GRAPHICS 2 /* Relative */ #undef LCS_GM_IMAGES #define LCS_GM_IMAGES 4 /* Perceptual */ #undef LCS_GM_ABS_COLORIMETRIC #define LCS_GM_ABS_COLORIMETRIC 8 /* Absolute */ #endif /* Typedef declarations. */ typedef struct _BMPInfo { unsigned int file_size, ba_offset, offset_bits, size; ssize_t width, height; unsigned short planes, bits_per_pixel; unsigned int compression, image_size, x_pixels, y_pixels, number_colors, red_mask, green_mask, blue_mask, alpha_mask, colors_important; int colorspace; PrimaryInfo red_primary, green_primary, blue_primary, gamma_scale; } BMPInfo; /* Forward declarations. */ static MagickBooleanType WriteBMPImage(const ImageInfo *,Image *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e c o d e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DecodeImage unpacks the packed image pixels into runlength-encoded % pixel packets. % % The format of the DecodeImage method is: % % MagickBooleanType DecodeImage(Image *image, % const size_t compression,unsigned char *pixels) % % A description of each parameter follows: % % o image: the address of a structure of type Image. % % o compression: Zero means uncompressed. A value of 1 means the % compressed pixels are runlength encoded for a 256-color bitmap. % A value of 2 means a 16-color bitmap. A value of 3 means bitfields % encoding. % % o pixels: The address of a byte (8 bits) array of pixel data created by % the decoding process. % */ static inline ssize_t MagickAbsoluteValue(const ssize_t x) { if (x < 0) return(-x); return(x); } static inline size_t MagickMax(const size_t x,const size_t y) { if (x > y) return(x); return(y); } static inline ssize_t MagickMin(const ssize_t x,const ssize_t y) { if (x < y) return(x); return(y); } static MagickBooleanType DecodeImage(Image *image,const size_t compression, unsigned char *pixels) { int count; register ssize_t i, x; register unsigned char *p, *q; ssize_t y; unsigned char byte; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(pixels != (unsigned char *) NULL); (void) ResetMagickMemory(pixels,0,(size_t) image->columns*image->rows* sizeof(*pixels)); byte=0; x=0; p=pixels; q=pixels+(size_t) image->columns*image->rows; for (y=0; y < (ssize_t) image->rows; ) { if ((p < pixels) || (p >= q)) break; count=ReadBlobByte(image); if (count == EOF) break; if (count != 0) { /* Encoded mode. */ count=(int) MagickMin((ssize_t) count,(ssize_t) (q-p)); byte=(unsigned char) ReadBlobByte(image); if (compression == BI_RLE8) { for (i=0; i < (ssize_t) count; i++) *p++=(unsigned char) byte; } else { for (i=0; i < (ssize_t) count; i++) *p++=(unsigned char) ((i & 0x01) != 0 ? (byte & 0x0f) : ((byte >> 4) & 0x0f)); } x+=count; } else { /* Escape mode. */ count=ReadBlobByte(image); if (count == 0x01) return(MagickTrue); switch (count) { case 0x00: { /* End of line. */ x=0; y++; p=pixels+y*image->columns; break; } case 0x02: { /* Delta mode. */ x+=ReadBlobByte(image); y+=ReadBlobByte(image); p=pixels+y*image->columns+x; break; } default: { /* Absolute mode. */ count=(int) MagickMin((ssize_t) count,(ssize_t) (q-p)); if (compression == BI_RLE8) for (i=0; i < (ssize_t) count; i++) *p++=(unsigned char) ReadBlobByte(image); else for (i=0; i < (ssize_t) count; i++) { if ((i & 0x01) == 0) byte=(unsigned char) ReadBlobByte(image); *p++=(unsigned char) ((i & 0x01) != 0 ? (byte & 0x0f) : ((byte >> 4) & 0x0f)); } x+=count; /* Read pad byte. */ if (compression == BI_RLE8) { if ((count & 0x01) != 0) (void) ReadBlobByte(image); } else if (((count & 0x03) == 1) || ((count & 0x03) == 2)) (void) ReadBlobByte(image); break; } } } if (SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows) == MagickFalse) break; } (void) ReadBlobByte(image); /* end of line */ (void) ReadBlobByte(image); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E n c o d e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % EncodeImage compresses pixels using a runlength encoded format. % % The format of the EncodeImage method is: % % static MagickBooleanType EncodeImage(Image *image, % const size_t bytes_per_line,const unsigned char *pixels, % unsigned char *compressed_pixels) % % A description of each parameter follows: % % o image: The image. % % o bytes_per_line: the number of bytes in a scanline of compressed pixels % % o pixels: The address of a byte (8 bits) array of pixel data created by % the compression process. % % o compressed_pixels: The address of a byte (8 bits) array of compressed % pixel data. % */ static size_t EncodeImage(Image *image,const size_t bytes_per_line, const unsigned char *pixels,unsigned char *compressed_pixels) { MagickBooleanType status; register const unsigned char *p; register ssize_t i, x; register unsigned char *q; ssize_t y; /* Runlength encode pixels. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(pixels != (const unsigned char *) NULL); assert(compressed_pixels != (unsigned char *) NULL); p=pixels; q=compressed_pixels; i=0; for (y=0; y < (ssize_t) image->rows; y++) { for (x=0; x < (ssize_t) bytes_per_line; x+=i) { /* Determine runlength. */ for (i=1; ((x+i) < (ssize_t) bytes_per_line); i++) if ((i == 255) || (*(p+i) != *p)) break; *q++=(unsigned char) i; *q++=(*p); p+=i; } /* End of line. */ *q++=(unsigned char) 0x00; *q++=(unsigned char) 0x00; status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } /* End of bitmap. */ *q++=(unsigned char) 0x00; *q++=(unsigned char) 0x01; return((size_t) (q-compressed_pixels)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s B M P % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsBMP() returns MagickTrue if the image format type, identified by the % magick string, is BMP. % % The format of the IsBMP method is: % % MagickBooleanType IsBMP(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 IsBMP(const unsigned char *magick,const size_t length) { if (length < 2) return(MagickFalse); if ((LocaleNCompare((char *) magick,"BA",2) == 0) || (LocaleNCompare((char *) magick,"BM",2) == 0) || (LocaleNCompare((char *) magick,"IC",2) == 0) || (LocaleNCompare((char *) magick,"PI",2) == 0) || (LocaleNCompare((char *) magick,"CI",2) == 0) || (LocaleNCompare((char *) magick,"CP",2) == 0)) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d B M P I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadBMPImage() reads a Microsoft Windows bitmap image file, Version % 2, 3 (for Windows or NT), or 4, 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 ReadBMPImage method is: % % image=ReadBMPImage(image_info) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadBMPImage(const ImageInfo *image_info,ExceptionInfo *exception) { BMPInfo bmp_info; Image *image; IndexPacket index; MagickBooleanType status; MagickOffsetType offset, start_position; MemoryInfo *pixel_info; register IndexPacket *indexes; register PixelPacket *q; register ssize_t i, x; register unsigned char *p; size_t bit, blue, bytes_per_line, green, length, red; ssize_t count, y; unsigned char magick[12], *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Determine if this a BMP file. */ (void) ResetMagickMemory(&bmp_info,0,sizeof(bmp_info)); bmp_info.ba_offset=0; start_position=0; count=ReadBlob(image,2,magick); do { LongPixelPacket shift; PixelPacket quantum_bits; size_t profile_data, profile_size; /* Verify BMP identifier. */ if (bmp_info.ba_offset == 0) start_position=TellBlob(image)-2; bmp_info.ba_offset=0; while (LocaleNCompare((char *) magick,"BA",2) == 0) { bmp_info.file_size=ReadBlobLSBLong(image); bmp_info.ba_offset=ReadBlobLSBLong(image); bmp_info.offset_bits=ReadBlobLSBLong(image); count=ReadBlob(image,2,magick); if (count != 2) break; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," Magick: %c%c", magick[0],magick[1]); if ((count == 0) || ((LocaleNCompare((char *) magick,"BM",2) != 0) && (LocaleNCompare((char *) magick,"CI",2) != 0))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); bmp_info.file_size=ReadBlobLSBLong(image); (void) ReadBlobLSBLong(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " File_size in header: %u bytes",bmp_info.file_size); bmp_info.offset_bits=ReadBlobLSBLong(image); bmp_info.size=ReadBlobLSBLong(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," BMP size: %u", bmp_info.size); if (bmp_info.size == 12) { /* OS/2 BMP image file. */ (void) CopyMagickString(image->magick,"BMP2",MaxTextExtent); bmp_info.width=(ssize_t) ((short) ReadBlobLSBShort(image)); bmp_info.height=(ssize_t) ((short) ReadBlobLSBShort(image)); bmp_info.planes=ReadBlobLSBShort(image); bmp_info.bits_per_pixel=ReadBlobLSBShort(image); bmp_info.x_pixels=0; bmp_info.y_pixels=0; bmp_info.number_colors=0; bmp_info.compression=BI_RGB; bmp_info.image_size=0; bmp_info.alpha_mask=0; if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Format: OS/2 Bitmap"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Geometry: %.20gx%.20g",(double) bmp_info.width,(double) bmp_info.height); } } else { /* Microsoft Windows BMP image file. */ if (bmp_info.size < 40) ThrowReaderException(CorruptImageError,"NonOS2HeaderSizeError"); bmp_info.width=(ssize_t) ((int) ReadBlobLSBLong(image)); bmp_info.height=(ssize_t) ((int) ReadBlobLSBLong(image)); bmp_info.planes=ReadBlobLSBShort(image); bmp_info.bits_per_pixel=ReadBlobLSBShort(image); bmp_info.compression=ReadBlobLSBLong(image); bmp_info.image_size=ReadBlobLSBLong(image); bmp_info.x_pixels=ReadBlobLSBLong(image); bmp_info.y_pixels=ReadBlobLSBLong(image); bmp_info.number_colors=ReadBlobLSBLong(image); bmp_info.colors_important=ReadBlobLSBLong(image); profile_data=0; profile_size=0; if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Format: MS Windows bitmap"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Geometry: %.20gx%.20g",(double) bmp_info.width,(double) bmp_info.height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Bits per pixel: %.20g",(double) bmp_info.bits_per_pixel); switch ((int) bmp_info.compression) { case BI_RGB: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_RGB"); break; } case BI_RLE4: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_RLE4"); break; } case BI_RLE8: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_RLE8"); break; } case BI_BITFIELDS: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_BITFIELDS"); break; } case BI_PNG: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_PNG"); break; } case BI_JPEG: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_JPEG"); break; } default: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: UNKNOWN (%u)",bmp_info.compression); } } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number of colors: %u",bmp_info.number_colors); } bmp_info.red_mask=ReadBlobLSBLong(image); bmp_info.green_mask=ReadBlobLSBLong(image); bmp_info.blue_mask=ReadBlobLSBLong(image); if (bmp_info.size > 40) { double sum; /* Read color management information. */ bmp_info.alpha_mask=ReadBlobLSBLong(image); bmp_info.colorspace=(int) ReadBlobLSBLong(image); /* Decode 2^30 fixed point formatted CIE primaries. */ # define BMP_DENOM ((double) 0x40000000) bmp_info.red_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.red_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.red_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; sum=bmp_info.red_primary.x+bmp_info.red_primary.y+ bmp_info.red_primary.z; bmp_info.red_primary.x/=sum; bmp_info.red_primary.y/=sum; image->chromaticity.red_primary.x=bmp_info.red_primary.x; image->chromaticity.red_primary.y=bmp_info.red_primary.y; sum=bmp_info.green_primary.x+bmp_info.green_primary.y+ bmp_info.green_primary.z; bmp_info.green_primary.x/=sum; bmp_info.green_primary.y/=sum; image->chromaticity.green_primary.x=bmp_info.green_primary.x; image->chromaticity.green_primary.y=bmp_info.green_primary.y; sum=bmp_info.blue_primary.x+bmp_info.blue_primary.y+ bmp_info.blue_primary.z; bmp_info.blue_primary.x/=sum; bmp_info.blue_primary.y/=sum; image->chromaticity.blue_primary.x=bmp_info.blue_primary.x; image->chromaticity.blue_primary.y=bmp_info.blue_primary.y; /* Decode 16^16 fixed point formatted gamma_scales. */ bmp_info.gamma_scale.x=(double) ReadBlobLSBLong(image)/0x10000; bmp_info.gamma_scale.y=(double) ReadBlobLSBLong(image)/0x10000; bmp_info.gamma_scale.z=(double) ReadBlobLSBLong(image)/0x10000; /* Compute a single gamma from the BMP 3-channel gamma. */ image->gamma=(bmp_info.gamma_scale.x+bmp_info.gamma_scale.y+ bmp_info.gamma_scale.z)/3.0; } else (void) CopyMagickString(image->magick,"BMP3",MaxTextExtent); if (bmp_info.size > 108) { size_t intent; /* Read BMP Version 5 color management information. */ intent=ReadBlobLSBLong(image); switch ((int) intent) { case LCS_GM_BUSINESS: { image->rendering_intent=SaturationIntent; break; } case LCS_GM_GRAPHICS: { image->rendering_intent=RelativeIntent; break; } case LCS_GM_IMAGES: { image->rendering_intent=PerceptualIntent; break; } case LCS_GM_ABS_COLORIMETRIC: { image->rendering_intent=AbsoluteIntent; break; } } profile_data=ReadBlobLSBLong(image); profile_size=ReadBlobLSBLong(image); (void) profile_data; (void) profile_size; (void) ReadBlobLSBLong(image); /* Reserved byte */ } } if ((MagickSizeType) bmp_info.file_size > GetBlobSize(image)) (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError, "LengthAndFilesizeDoNotMatch","`%s'",image->filename); else if ((MagickSizeType) bmp_info.file_size < GetBlobSize(image)) (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageWarning,"LengthAndFilesizeDoNotMatch","`%s'", image->filename); if (bmp_info.width <= 0) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); if (bmp_info.height == 0) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); if (bmp_info.planes != 1) ThrowReaderException(CorruptImageError,"StaticPlanesValueNotEqualToOne"); if ((bmp_info.bits_per_pixel != 1) && (bmp_info.bits_per_pixel != 4) && (bmp_info.bits_per_pixel != 8) && (bmp_info.bits_per_pixel != 16) && (bmp_info.bits_per_pixel != 24) && (bmp_info.bits_per_pixel != 32)) ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel"); if (bmp_info.bits_per_pixel < 16 && bmp_info.number_colors > (1U << bmp_info.bits_per_pixel)) { ThrowReaderException(CorruptImageError, "UnrecognizedNumberOfColors"); } if ((bmp_info.compression == 1) && (bmp_info.bits_per_pixel != 8)) ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel"); if ((bmp_info.compression == 2) && (bmp_info.bits_per_pixel != 4)) ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel"); if ((bmp_info.compression == 3) && (bmp_info.bits_per_pixel < 16)) ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel"); switch (bmp_info.compression) { case BI_RGB: case BI_RLE8: case BI_RLE4: case BI_BITFIELDS: break; case BI_JPEG: ThrowReaderException(CoderError,"JPEGCompressNotSupported"); case BI_PNG: ThrowReaderException(CoderError,"PNGCompressNotSupported"); default: ThrowReaderException(CorruptImageError,"UnrecognizedImageCompression"); } image->columns=(size_t) MagickAbsoluteValue(bmp_info.width); image->rows=(size_t) MagickAbsoluteValue(bmp_info.height); image->depth=bmp_info.bits_per_pixel <= 8 ? bmp_info.bits_per_pixel : 8; image->matte=((bmp_info.alpha_mask != 0) && (bmp_info.compression == BI_BITFIELDS)) || (bmp_info.bits_per_pixel == 32) ? MagickTrue : MagickFalse; if (bmp_info.bits_per_pixel < 16) { size_t one; image->storage_class=PseudoClass; image->colors=bmp_info.number_colors; one=1; if (image->colors == 0) image->colors=one << bmp_info.bits_per_pixel; } if (image->storage_class == PseudoClass) { unsigned char *bmp_colormap; size_t packet_size; /* Read BMP raster colormap. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading colormap of %.20g colors",(double) image->colors); if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); bmp_colormap=(unsigned char *) AcquireQuantumMemory((size_t) image->colors,4*sizeof(*bmp_colormap)); if (bmp_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if ((bmp_info.size == 12) || (bmp_info.size == 64)) packet_size=3; else packet_size=4; offset=SeekBlob(image,start_position+14+bmp_info.size,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); count=ReadBlob(image,packet_size*image->colors,bmp_colormap); if (count != (ssize_t) (packet_size*image->colors)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); p=bmp_colormap; for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].blue=ScaleCharToQuantum(*p++); image->colormap[i].green=ScaleCharToQuantum(*p++); image->colormap[i].red=ScaleCharToQuantum(*p++); if (packet_size == 4) p++; } bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); } image->x_resolution=(double) bmp_info.x_pixels/100.0; image->y_resolution=(double) bmp_info.y_pixels/100.0; image->units=PixelsPerCentimeterResolution; if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; /* Read image data. */ offset=SeekBlob(image,start_position+bmp_info.offset_bits,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (bmp_info.compression == BI_RLE4) bmp_info.bits_per_pixel<<=1; bytes_per_line=4*((image->columns*bmp_info.bits_per_pixel+31)/32); length=(size_t) bytes_per_line*image->rows; pixel_info=AcquireVirtualMemory((size_t) image->rows, MagickMax(bytes_per_line,image->columns+256UL)*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); if ((bmp_info.compression == BI_RGB) || (bmp_info.compression == BI_BITFIELDS)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading pixels (%.20g bytes)",(double) length); count=ReadBlob(image,length,pixels); if (count != (ssize_t) length) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); } } else { /* Convert run-length encoded raster pixels. */ status=DecodeImage(image,bmp_info.compression,pixels); if (status == MagickFalse) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "UnableToRunlengthDecodeImage"); } } /* Convert BMP raster image to pixel packets. */ if (bmp_info.compression == BI_RGB) { bmp_info.alpha_mask=image->matte != MagickFalse ? 0xff000000U : 0U; bmp_info.red_mask=0x00ff0000U; bmp_info.green_mask=0x0000ff00U; bmp_info.blue_mask=0x000000ffU; if (bmp_info.bits_per_pixel == 16) { /* RGB555. */ bmp_info.red_mask=0x00007c00U; bmp_info.green_mask=0x000003e0U; bmp_info.blue_mask=0x0000001fU; } } if ((bmp_info.bits_per_pixel == 16) || (bmp_info.bits_per_pixel == 32)) { register size_t sample; /* Get shift and quantum bits info from bitfield masks. */ (void) ResetMagickMemory(&shift,0,sizeof(shift)); (void) ResetMagickMemory(&quantum_bits,0,sizeof(quantum_bits)); if (bmp_info.red_mask != 0) while (((bmp_info.red_mask << shift.red) & 0x80000000UL) == 0) shift.red++; if (bmp_info.green_mask != 0) while (((bmp_info.green_mask << shift.green) & 0x80000000UL) == 0) shift.green++; if (bmp_info.blue_mask != 0) while (((bmp_info.blue_mask << shift.blue) & 0x80000000UL) == 0) shift.blue++; if (bmp_info.alpha_mask != 0) while (((bmp_info.alpha_mask << shift.opacity) & 0x80000000UL) == 0) shift.opacity++; sample=shift.red; while (((bmp_info.red_mask << sample) & 0x80000000UL) != 0) sample++; quantum_bits.red=ClampToQuantum((MagickRealType) sample-shift.red); sample=shift.green; while (((bmp_info.green_mask << sample) & 0x80000000UL) != 0) sample++; quantum_bits.green=ClampToQuantum((MagickRealType) sample-shift.green); sample=shift.blue; while (((bmp_info.blue_mask << sample) & 0x80000000UL) != 0) sample++; quantum_bits.blue=ClampToQuantum((MagickRealType) sample-shift.blue); sample=shift.opacity; while (((bmp_info.alpha_mask << sample) & 0x80000000UL) != 0) sample++; quantum_bits.opacity=ClampToQuantum((MagickRealType) sample- shift.opacity); } switch (bmp_info.bits_per_pixel) { case 1: { /* Convert bitmap scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < ((ssize_t) image->columns-7); x+=8) { for (bit=0; bit < 8; bit++) { index=(IndexPacket) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00); SetPixelIndex(indexes+x+bit,index); q++; } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (image->columns % 8); bit++) { index=(IndexPacket) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00); SetPixelIndex(indexes+x+bit,index); } p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image); break; } case 4: { /* Convert PseudoColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < ((ssize_t) image->columns-1); x+=2) { index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f); SetPixelIndex(indexes+x,index); index=ConstrainColormapIndex(image,*p & 0x0f); SetPixelIndex(indexes+x+1,index); p++; } if ((image->columns % 2) != 0) { index=ConstrainColormapIndex(image,(*p >> 4) & 0xf); SetPixelIndex(indexes+x,index); p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image); break; } case 8: { /* Convert PseudoColor scanline. */ if ((bmp_info.compression == BI_RLE8) || (bmp_info.compression == BI_RLE4)) bytes_per_line=image->columns; for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=(ssize_t) image->columns; x != 0; --x) { index=ConstrainColormapIndex(image,*p); SetPixelIndex(indexes,index); indexes++; p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image); break; } case 16: { size_t alpha, pixel; /* Convert bitfield encoded 16-bit PseudoColor scanline. */ if (bmp_info.compression != BI_RGB && bmp_info.compression != BI_BITFIELDS) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "UnrecognizedImageCompression"); } bytes_per_line=2*(image->columns+image->columns % 2); image->storage_class=DirectClass; for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=(size_t) (*p++); pixel|=(*p++) << 8; red=((pixel & bmp_info.red_mask) << shift.red) >> 16; if (quantum_bits.red == 5) red|=((red & 0xe000) >> 5); if (quantum_bits.red <= 8) red|=((red & 0xff00) >> 8); green=((pixel & bmp_info.green_mask) << shift.green) >> 16; if (quantum_bits.green == 5) green|=((green & 0xe000) >> 5); if (quantum_bits.green == 6) green|=((green & 0xc000) >> 6); if (quantum_bits.green <= 8) green|=((green & 0xff00) >> 8); blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16; if (quantum_bits.blue == 5) blue|=((blue & 0xe000) >> 5); if (quantum_bits.blue <= 8) blue|=((blue & 0xff00) >> 8); alpha=((pixel & bmp_info.alpha_mask) << shift.opacity) >> 16; if (quantum_bits.opacity <= 8) alpha|=((alpha & 0xff00) >> 8); SetPixelRed(q,ScaleShortToQuantum((unsigned short) red)); SetPixelGreen(q,ScaleShortToQuantum((unsigned short) green)); SetPixelBlue(q,ScaleShortToQuantum((unsigned short) blue)); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) SetPixelAlpha(q,ScaleShortToQuantum((unsigned short) alpha)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } case 24: { /* Convert DirectColor scanline. */ bytes_per_line=4*((image->columns*24+31)/32); for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelRed(q,ScaleCharToQuantum(*p++)); SetPixelOpacity(q,OpaqueOpacity); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } case 32: { /* Convert bitfield encoded DirectColor scanline. */ if ((bmp_info.compression != BI_RGB) && (bmp_info.compression != BI_BITFIELDS)) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "UnrecognizedImageCompression"); } bytes_per_line=4*(image->columns); for (y=(ssize_t) image->rows-1; y >= 0; y--) { size_t alpha, pixel; p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=(size_t) (*p++); pixel|=((size_t) *p++ << 8); pixel|=((size_t) *p++ << 16); pixel|=((size_t) *p++ << 24); red=((pixel & bmp_info.red_mask) << shift.red) >> 16; if (quantum_bits.red == 8) red|=(red >> 8); green=((pixel & bmp_info.green_mask) << shift.green) >> 16; if (quantum_bits.green == 8) green|=(green >> 8); blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16; if (quantum_bits.blue == 8) blue|=(blue >> 8); alpha=((pixel & bmp_info.alpha_mask) << shift.opacity) >> 16; if (quantum_bits.opacity == 8) alpha|=(alpha >> 8); SetPixelRed(q,ScaleShortToQuantum((unsigned short) red)); SetPixelGreen(q,ScaleShortToQuantum((unsigned short) green)); SetPixelBlue(q,ScaleShortToQuantum((unsigned short) blue)); SetPixelAlpha(q,OpaqueOpacity); if (image->matte != MagickFalse) SetPixelAlpha(q,ScaleShortToQuantum((unsigned short) alpha)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } default: { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } } pixel_info=RelinquishVirtualMemory(pixel_info); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } if (bmp_info.height < 0) { Image *flipped_image; /* Correct image orientation. */ flipped_image=FlipImage(image,exception); if (flipped_image != (Image *) NULL) { DuplicateBlob(flipped_image,image); image=DestroyImage(image); image=flipped_image; } } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; *magick='\0'; if (bmp_info.ba_offset != 0) { offset=SeekBlob(image,(MagickOffsetType) bmp_info.ba_offset,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } count=ReadBlob(image,2,magick); if ((count == 2) && (IsBMP(magick,2) != MagickFalse)) { /* Acquire next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (IsBMP(magick,2) != MagickFalse); (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r B M P I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterBMPImage() adds attributes for the BMP 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 RegisterBMPImage method is: % % size_t RegisterBMPImage(void) % */ ModuleExport size_t RegisterBMPImage(void) { MagickInfo *entry; entry=SetMagickInfo("BMP"); entry->decoder=(DecodeImageHandler *) ReadBMPImage; entry->encoder=(EncodeImageHandler *) WriteBMPImage; entry->magick=(IsImageFormatHandler *) IsBMP; entry->description=ConstantString("Microsoft Windows bitmap image"); entry->module=ConstantString("BMP"); entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; (void) RegisterMagickInfo(entry); entry=SetMagickInfo("BMP2"); entry->encoder=(EncodeImageHandler *) WriteBMPImage; entry->magick=(IsImageFormatHandler *) IsBMP; entry->description=ConstantString("Microsoft Windows bitmap image (V2)"); entry->module=ConstantString("BMP"); entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; (void) RegisterMagickInfo(entry); entry=SetMagickInfo("BMP3"); entry->encoder=(EncodeImageHandler *) WriteBMPImage; entry->magick=(IsImageFormatHandler *) IsBMP; entry->description=ConstantString("Microsoft Windows bitmap image (V3)"); entry->module=ConstantString("BMP"); entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r B M P I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterBMPImage() removes format registrations made by the % BMP module from the list of supported formats. % % The format of the UnregisterBMPImage method is: % % UnregisterBMPImage(void) % */ ModuleExport void UnregisterBMPImage(void) { (void) UnregisterMagickInfo("BMP"); (void) UnregisterMagickInfo("BMP2"); (void) UnregisterMagickInfo("BMP3"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e B M P I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteBMPImage() writes an image in Microsoft Windows bitmap encoded % image format, version 3 for Windows or (if the image has a matte channel) % version 4. % % The format of the WriteBMPImage method is: % % MagickBooleanType WriteBMPImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % */ static MagickBooleanType WriteBMPImage(const ImageInfo *image_info,Image *image) { BMPInfo bmp_info; const char *value; const StringInfo *profile; MagickBooleanType have_color_info, status; MemoryInfo *pixel_info; MagickOffsetType scene; register const IndexPacket *indexes; register const PixelPacket *p; register ssize_t i, x; register unsigned char *q; size_t bytes_per_line, type; ssize_t y; unsigned char *bmp_data, *pixels; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); type=4; if (LocaleCompare(image_info->magick,"BMP2") == 0) type=2; else if (LocaleCompare(image_info->magick,"BMP3") == 0) type=3; value=GetImageOption(image_info,"bmp:format"); if (value != (char *) NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Format=%s",value); if (LocaleCompare(value,"bmp2") == 0) type=2; if (LocaleCompare(value,"bmp3") == 0) type=3; if (LocaleCompare(value,"bmp4") == 0) type=4; } scene=0; do { /* Initialize BMP raster file header. */ (void) TransformImageColorspace(image,sRGBColorspace); (void) ResetMagickMemory(&bmp_info,0,sizeof(bmp_info)); bmp_info.file_size=14+12; if (type > 2) bmp_info.file_size+=28; bmp_info.offset_bits=bmp_info.file_size; bmp_info.compression=BI_RGB; if ((image->storage_class == PseudoClass) && (image->colors > 256)) (void) SetImageStorageClass(image,DirectClass); if (image->storage_class != DirectClass) { /* Colormapped BMP raster. */ bmp_info.bits_per_pixel=8; if (image->colors <= 2) bmp_info.bits_per_pixel=1; else if (image->colors <= 16) bmp_info.bits_per_pixel=4; else if (image->colors <= 256) bmp_info.bits_per_pixel=8; if (image_info->compression == RLECompression) bmp_info.bits_per_pixel=8; bmp_info.number_colors=1U << bmp_info.bits_per_pixel; if (image->matte != MagickFalse) (void) SetImageStorageClass(image,DirectClass); else if ((size_t) bmp_info.number_colors < image->colors) (void) SetImageStorageClass(image,DirectClass); else { bmp_info.file_size+=3*(1UL << bmp_info.bits_per_pixel); bmp_info.offset_bits+=3*(1UL << bmp_info.bits_per_pixel); if (type > 2) { bmp_info.file_size+=(1UL << bmp_info.bits_per_pixel); bmp_info.offset_bits+=(1UL << bmp_info.bits_per_pixel); } } } if (image->storage_class == DirectClass) { /* Full color BMP raster. */ bmp_info.number_colors=0; bmp_info.bits_per_pixel=(unsigned short) ((type > 3) && (image->matte != MagickFalse) ? 32 : 24); bmp_info.compression=(unsigned int) ((type > 3) && (image->matte != MagickFalse) ? BI_BITFIELDS : BI_RGB); } bytes_per_line=4*((image->columns*bmp_info.bits_per_pixel+31)/32); bmp_info.ba_offset=0; profile=GetImageProfile(image,"icc"); have_color_info=(image->rendering_intent != UndefinedIntent) || (profile != (StringInfo *) NULL) || (image->gamma != 0.0) ? MagickTrue : MagickFalse; if (type == 2) bmp_info.size=12; else if ((type == 3) || ((image->matte == MagickFalse) && (have_color_info == MagickFalse))) { type=3; bmp_info.size=40; } else { int extra_size; bmp_info.size=108; extra_size=68; if ((image->rendering_intent != UndefinedIntent) || (profile != (StringInfo *) NULL)) { bmp_info.size=124; extra_size+=16; } bmp_info.file_size+=extra_size; bmp_info.offset_bits+=extra_size; } bmp_info.width=(ssize_t) image->columns; bmp_info.height=(ssize_t) image->rows; bmp_info.planes=1; bmp_info.image_size=(unsigned int) (bytes_per_line*image->rows); bmp_info.file_size+=bmp_info.image_size; bmp_info.x_pixels=75*39; bmp_info.y_pixels=75*39; switch (image->units) { case UndefinedResolution: case PixelsPerInchResolution: { bmp_info.x_pixels=(unsigned int) (100.0*image->x_resolution/2.54); bmp_info.y_pixels=(unsigned int) (100.0*image->y_resolution/2.54); break; } case PixelsPerCentimeterResolution: { bmp_info.x_pixels=(unsigned int) (100.0*image->x_resolution); bmp_info.y_pixels=(unsigned int) (100.0*image->y_resolution); break; } } bmp_info.colors_important=bmp_info.number_colors; /* Convert MIFF to BMP raster pixels. */ pixel_info=AcquireVirtualMemory((size_t) bmp_info.image_size, sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); (void) ResetMagickMemory(pixels,0,(size_t) bmp_info.image_size); switch (bmp_info.bits_per_pixel) { case 1: { size_t bit, byte; /* Convert PseudoClass image to a BMP monochrome image. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); q=pixels+(image->rows-y-1)*bytes_per_line; bit=0; byte=0; for (x=0; x < (ssize_t) image->columns; x++) { byte<<=1; byte|=GetPixelIndex(indexes+x) != 0 ? 0x01 : 0x00; bit++; if (bit == 8) { *q++=(unsigned char) byte; bit=0; byte=0; } } if (bit != 0) { *q++=(unsigned char) (byte << (8-bit)); x++; } for (x=(ssize_t) (image->columns+7)/8; x < (ssize_t) bytes_per_line; x++) *q++=0x00; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case 4: { size_t nibble, byte; /* Convert PseudoClass image to a BMP monochrome image. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); q=pixels+(image->rows-y-1)*bytes_per_line; nibble=0; byte=0; for (x=0; x < (ssize_t) image->columns; x++) { byte<<=4; byte|=((size_t) GetPixelIndex(indexes+x) & 0x0f); nibble++; if (nibble == 2) { *q++=(unsigned char) byte; nibble=0; byte=0; } } if (nibble != 0) { *q++=(unsigned char) (byte << 4); x++; } for (x=(ssize_t) (image->columns+1)/2; x < (ssize_t) bytes_per_line; x++) *q++=0x00; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case 8: { /* Convert PseudoClass packet to BMP pixel. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); q=pixels+(image->rows-y-1)*bytes_per_line; for (x=0; x < (ssize_t) image->columns; x++) *q++=(unsigned char) GetPixelIndex(indexes+x); for ( ; x < (ssize_t) bytes_per_line; x++) *q++=0x00; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case 24: { /* Convert DirectClass packet to BMP BGR888. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; q=pixels+(image->rows-y-1)*bytes_per_line; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelBlue(p)); *q++=ScaleQuantumToChar(GetPixelGreen(p)); *q++=ScaleQuantumToChar(GetPixelRed(p)); p++; } for (x=3L*(ssize_t) image->columns; x < (ssize_t) bytes_per_line; x++) *q++=0x00; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case 32: { /* Convert DirectClass packet to ARGB8888 pixel. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; q=pixels+(image->rows-y-1)*bytes_per_line; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelBlue(p)); *q++=ScaleQuantumToChar(GetPixelGreen(p)); *q++=ScaleQuantumToChar(GetPixelRed(p)); *q++=ScaleQuantumToChar(GetPixelAlpha(p)); p++; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } } if ((type > 2) && (bmp_info.bits_per_pixel == 8)) if (image_info->compression != NoCompression) { MemoryInfo *rle_info; /* Convert run-length encoded raster pixels. */ rle_info=AcquireVirtualMemory((size_t) (2*(bytes_per_line+2)+2), (image->rows+2)*sizeof(*pixels)); if (rle_info == (MemoryInfo *) NULL) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } bmp_data=(unsigned char *) GetVirtualMemoryBlob(rle_info); bmp_info.file_size-=bmp_info.image_size; bmp_info.image_size=(unsigned int) EncodeImage(image,bytes_per_line, pixels,bmp_data); bmp_info.file_size+=bmp_info.image_size; pixel_info=RelinquishVirtualMemory(pixel_info); pixel_info=rle_info; pixels=bmp_data; bmp_info.compression=BI_RLE8; } /* Write BMP for Windows, all versions, 14-byte header. */ if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing BMP version %.20g datastream",(double) type); if (image->storage_class == DirectClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Storage class=DirectClass"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Storage class=PseudoClass"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image depth=%.20g",(double) image->depth); if (image->matte != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Matte=True"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Matte=MagickFalse"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " BMP bits_per_pixel=%.20g",(double) bmp_info.bits_per_pixel); switch ((int) bmp_info.compression) { case BI_RGB: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression=BI_RGB"); break; } case BI_RLE8: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression=BI_RLE8"); break; } case BI_BITFIELDS: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression=BI_BITFIELDS"); break; } default: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression=UNKNOWN (%u)",bmp_info.compression); break; } } if (bmp_info.number_colors == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number_colors=unspecified"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number_colors=%u",bmp_info.number_colors); } (void) WriteBlob(image,2,(unsigned char *) "BM"); (void) WriteBlobLSBLong(image,bmp_info.file_size); (void) WriteBlobLSBLong(image,bmp_info.ba_offset); /* always 0 */ (void) WriteBlobLSBLong(image,bmp_info.offset_bits); if (type == 2) { /* Write 12-byte version 2 bitmap header. */ (void) WriteBlobLSBLong(image,bmp_info.size); (void) WriteBlobLSBShort(image,(unsigned short) bmp_info.width); (void) WriteBlobLSBShort(image,(unsigned short) bmp_info.height); (void) WriteBlobLSBShort(image,bmp_info.planes); (void) WriteBlobLSBShort(image,bmp_info.bits_per_pixel); } else { /* Write 40-byte version 3+ bitmap header. */ (void) WriteBlobLSBLong(image,bmp_info.size); (void) WriteBlobLSBLong(image,(unsigned int) bmp_info.width); (void) WriteBlobLSBLong(image,(unsigned int) bmp_info.height); (void) WriteBlobLSBShort(image,bmp_info.planes); (void) WriteBlobLSBShort(image,bmp_info.bits_per_pixel); (void) WriteBlobLSBLong(image,bmp_info.compression); (void) WriteBlobLSBLong(image,bmp_info.image_size); (void) WriteBlobLSBLong(image,bmp_info.x_pixels); (void) WriteBlobLSBLong(image,bmp_info.y_pixels); (void) WriteBlobLSBLong(image,bmp_info.number_colors); (void) WriteBlobLSBLong(image,bmp_info.colors_important); } if ((type > 3) && ((image->matte != MagickFalse) || (have_color_info != MagickFalse))) { /* Write the rest of the 108-byte BMP Version 4 header. */ (void) WriteBlobLSBLong(image,0x00ff0000U); /* Red mask */ (void) WriteBlobLSBLong(image,0x0000ff00U); /* Green mask */ (void) WriteBlobLSBLong(image,0x000000ffU); /* Blue mask */ (void) WriteBlobLSBLong(image,0xff000000U); /* Alpha mask */ (void) WriteBlobLSBLong(image,0x73524742U); /* sRGB */ (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.red_primary.x*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.red_primary.y*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) ((1.000f-(image->chromaticity.red_primary.x+ image->chromaticity.red_primary.y))*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.green_primary.x*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.green_primary.y*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) ((1.000f-(image->chromaticity.green_primary.x+ image->chromaticity.green_primary.y))*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.blue_primary.x*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.blue_primary.y*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) ((1.000f-(image->chromaticity.blue_primary.x+ image->chromaticity.blue_primary.y))*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (bmp_info.gamma_scale.x*0x10000)); (void) WriteBlobLSBLong(image,(unsigned int) (bmp_info.gamma_scale.y*0x10000)); (void) WriteBlobLSBLong(image,(unsigned int) (bmp_info.gamma_scale.z*0x10000)); if ((image->rendering_intent != UndefinedIntent) || (profile != (StringInfo *) NULL)) { ssize_t intent; switch ((int) image->rendering_intent) { case SaturationIntent: { intent=LCS_GM_BUSINESS; break; } case RelativeIntent: { intent=LCS_GM_GRAPHICS; break; } case PerceptualIntent: { intent=LCS_GM_IMAGES; break; } case AbsoluteIntent: { intent=LCS_GM_ABS_COLORIMETRIC; break; } default: { intent=0; break; } } (void) WriteBlobLSBLong(image,(unsigned int) intent); (void) WriteBlobLSBLong(image,0x00); /* dummy profile data */ (void) WriteBlobLSBLong(image,0x00); /* dummy profile length */ (void) WriteBlobLSBLong(image,0x00); /* reserved */ } } if (image->storage_class == PseudoClass) { unsigned char *bmp_colormap; /* Dump colormap to file. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Colormap: %.20g entries",(double) image->colors); bmp_colormap=(unsigned char *) AcquireQuantumMemory((size_t) (1UL << bmp_info.bits_per_pixel),4*sizeof(*bmp_colormap)); if (bmp_colormap == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); q=bmp_colormap; for (i=0; i < (ssize_t) MagickMin((ssize_t) image->colors,(ssize_t) bmp_info.number_colors); i++) { *q++=ScaleQuantumToChar(image->colormap[i].blue); *q++=ScaleQuantumToChar(image->colormap[i].green); *q++=ScaleQuantumToChar(image->colormap[i].red); if (type > 2) *q++=(unsigned char) 0x0; } for ( ; i < (ssize_t) (1UL << bmp_info.bits_per_pixel); i++) { *q++=(unsigned char) 0x00; *q++=(unsigned char) 0x00; *q++=(unsigned char) 0x00; if (type > 2) *q++=(unsigned char) 0x00; } if (type <= 2) (void) WriteBlob(image,(size_t) (3*(1L << bmp_info.bits_per_pixel)), bmp_colormap); else (void) WriteBlob(image,(size_t) (4*(1L << bmp_info.bits_per_pixel)), bmp_colormap); bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Pixels: %u bytes",bmp_info.image_size); (void) WriteBlob(image,(size_t) bmp_info.image_size,pixels); pixel_info=RelinquishVirtualMemory(pixel_info); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " File_size: %u bytes",bmp_info.file_size); (void) CloseBlob(image); return(MagickTrue); }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_4787_5
crossvul-cpp_data_good_5826_0
/* * Go2Webinar decoder * Copyright (c) 2012 Konstantin Shishkov * * 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 * Go2Webinar decoder */ #include <zlib.h> #include "libavutil/intreadwrite.h" #include "avcodec.h" #include "bytestream.h" #include "dsputil.h" #include "get_bits.h" #include "internal.h" #include "mjpeg.h" enum ChunkType { FRAME_INFO = 0xC8, TILE_DATA, CURSOR_POS, CURSOR_SHAPE, CHUNK_CC, CHUNK_CD }; enum Compression { COMPR_EPIC_J_B = 2, COMPR_KEMPF_J_B, }; static const uint8_t luma_quant[64] = { 8, 6, 5, 8, 12, 20, 26, 31, 6, 6, 7, 10, 13, 29, 30, 28, 7, 7, 8, 12, 20, 29, 35, 28, 7, 9, 11, 15, 26, 44, 40, 31, 9, 11, 19, 28, 34, 55, 52, 39, 12, 18, 28, 32, 41, 52, 57, 46, 25, 32, 39, 44, 52, 61, 60, 51, 36, 46, 48, 49, 56, 50, 52, 50 }; static const uint8_t chroma_quant[64] = { 9, 9, 12, 24, 50, 50, 50, 50, 9, 11, 13, 33, 50, 50, 50, 50, 12, 13, 28, 50, 50, 50, 50, 50, 24, 33, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, }; typedef struct JPGContext { DSPContext dsp; ScanTable scantable; VLC dc_vlc[2], ac_vlc[2]; int prev_dc[3]; DECLARE_ALIGNED(16, int16_t, block)[6][64]; uint8_t *buf; } JPGContext; typedef struct G2MContext { JPGContext jc; int version; int compression; int width, height, bpp; int tile_width, tile_height; int tiles_x, tiles_y, tile_x, tile_y; int got_header; uint8_t *framebuf; int framebuf_stride, old_width, old_height; uint8_t *synth_tile, *jpeg_tile; int tile_stride, old_tile_w, old_tile_h; uint8_t *kempf_buf, *kempf_flags; uint8_t *cursor; int cursor_stride; int cursor_fmt; int cursor_w, cursor_h, cursor_x, cursor_y; int cursor_hot_x, cursor_hot_y; } G2MContext; static av_cold int build_vlc(VLC *vlc, const uint8_t *bits_table, const uint8_t *val_table, int nb_codes, int is_ac) { uint8_t huff_size[256] = { 0 }; uint16_t huff_code[256]; uint16_t huff_sym[256]; int i; ff_mjpeg_build_huffman_codes(huff_size, huff_code, bits_table, val_table); for (i = 0; i < 256; i++) huff_sym[i] = i + 16 * is_ac; if (is_ac) huff_sym[0] = 16 * 256; return ff_init_vlc_sparse(vlc, 9, nb_codes, huff_size, 1, 1, huff_code, 2, 2, huff_sym, 2, 2, 0); } static av_cold int jpg_init(AVCodecContext *avctx, JPGContext *c) { int ret; ret = build_vlc(&c->dc_vlc[0], avpriv_mjpeg_bits_dc_luminance, avpriv_mjpeg_val_dc, 12, 0); if (ret) return ret; ret = build_vlc(&c->dc_vlc[1], avpriv_mjpeg_bits_dc_chrominance, avpriv_mjpeg_val_dc, 12, 0); if (ret) return ret; ret = build_vlc(&c->ac_vlc[0], avpriv_mjpeg_bits_ac_luminance, avpriv_mjpeg_val_ac_luminance, 251, 1); if (ret) return ret; ret = build_vlc(&c->ac_vlc[1], avpriv_mjpeg_bits_ac_chrominance, avpriv_mjpeg_val_ac_chrominance, 251, 1); if (ret) return ret; ff_dsputil_init(&c->dsp, avctx); ff_init_scantable(c->dsp.idct_permutation, &c->scantable, ff_zigzag_direct); return 0; } static av_cold void jpg_free_context(JPGContext *ctx) { int i; for (i = 0; i < 2; i++) { ff_free_vlc(&ctx->dc_vlc[i]); ff_free_vlc(&ctx->ac_vlc[i]); } av_freep(&ctx->buf); } static void jpg_unescape(const uint8_t *src, int src_size, uint8_t *dst, int *dst_size) { const uint8_t *src_end = src + src_size; uint8_t *dst_start = dst; while (src < src_end) { uint8_t x = *src++; *dst++ = x; if (x == 0xFF && !*src) src++; } *dst_size = dst - dst_start; } static int jpg_decode_block(JPGContext *c, GetBitContext *gb, int plane, int16_t *block) { int dc, val, pos; const int is_chroma = !!plane; const uint8_t *qmat = is_chroma ? chroma_quant : luma_quant; c->dsp.clear_block(block); dc = get_vlc2(gb, c->dc_vlc[is_chroma].table, 9, 3); if (dc < 0) return AVERROR_INVALIDDATA; if (dc) dc = get_xbits(gb, dc); dc = dc * qmat[0] + c->prev_dc[plane]; block[0] = dc; c->prev_dc[plane] = dc; pos = 0; while (pos < 63) { val = get_vlc2(gb, c->ac_vlc[is_chroma].table, 9, 3); if (val < 0) return AVERROR_INVALIDDATA; pos += val >> 4; val &= 0xF; if (pos > 63) return val ? AVERROR_INVALIDDATA : 0; if (val) { int nbits = val; val = get_xbits(gb, nbits); val *= qmat[ff_zigzag_direct[pos]]; block[c->scantable.permutated[pos]] = val; } } return 0; } static inline void yuv2rgb(uint8_t *out, int Y, int U, int V) { out[0] = av_clip_uint8(Y + ( 91881 * V + 32768 >> 16)); out[1] = av_clip_uint8(Y + (-22554 * U - 46802 * V + 32768 >> 16)); out[2] = av_clip_uint8(Y + (116130 * U + 32768 >> 16)); } static int jpg_decode_data(JPGContext *c, int width, int height, const uint8_t *src, int src_size, uint8_t *dst, int dst_stride, const uint8_t *mask, int mask_stride, int num_mbs, int swapuv) { GetBitContext gb; uint8_t *tmp; int mb_w, mb_h, mb_x, mb_y, i, j; int bx, by; int unesc_size; int ret; tmp = av_realloc(c->buf, src_size + FF_INPUT_BUFFER_PADDING_SIZE); if (!tmp) return AVERROR(ENOMEM); c->buf = tmp; jpg_unescape(src, src_size, c->buf, &unesc_size); memset(c->buf + unesc_size, 0, FF_INPUT_BUFFER_PADDING_SIZE); init_get_bits(&gb, c->buf, unesc_size * 8); width = FFALIGN(width, 16); mb_w = width >> 4; mb_h = (height + 15) >> 4; if (!num_mbs) num_mbs = mb_w * mb_h; for (i = 0; i < 3; i++) c->prev_dc[i] = 1024; bx = by = 0; for (mb_y = 0; mb_y < mb_h; mb_y++) { for (mb_x = 0; mb_x < mb_w; mb_x++) { if (mask && !mask[mb_x]) { bx += 16; continue; } for (j = 0; j < 2; j++) { for (i = 0; i < 2; i++) { if ((ret = jpg_decode_block(c, &gb, 0, c->block[i + j * 2])) != 0) return ret; c->dsp.idct(c->block[i + j * 2]); } } for (i = 1; i < 3; i++) { if ((ret = jpg_decode_block(c, &gb, i, c->block[i + 3])) != 0) return ret; c->dsp.idct(c->block[i + 3]); } for (j = 0; j < 16; j++) { uint8_t *out = dst + bx * 3 + (by + j) * dst_stride; for (i = 0; i < 16; i++) { int Y, U, V; Y = c->block[(j >> 3) * 2 + (i >> 3)][(i & 7) + (j & 7) * 8]; U = c->block[4 ^ swapuv][(i >> 1) + (j >> 1) * 8] - 128; V = c->block[5 ^ swapuv][(i >> 1) + (j >> 1) * 8] - 128; yuv2rgb(out + i * 3, Y, U, V); } } if (!--num_mbs) return 0; bx += 16; } bx = 0; by += 16; if (mask) mask += mask_stride; } return 0; } static void kempf_restore_buf(const uint8_t *src, int len, uint8_t *dst, int stride, const uint8_t *jpeg_tile, int tile_stride, int width, int height, const uint8_t *pal, int npal, int tidx) { GetBitContext gb; int i, j, nb, col; init_get_bits(&gb, src, len * 8); if (npal <= 2) nb = 1; else if (npal <= 4) nb = 2; else if (npal <= 16) nb = 4; else nb = 8; for (j = 0; j < height; j++, dst += stride, jpeg_tile += tile_stride) { if (get_bits(&gb, 8)) continue; for (i = 0; i < width; i++) { col = get_bits(&gb, nb); if (col != tidx) memcpy(dst + i * 3, pal + col * 3, 3); else memcpy(dst + i * 3, jpeg_tile + i * 3, 3); } } } static int kempf_decode_tile(G2MContext *c, int tile_x, int tile_y, const uint8_t *src, int src_size) { int width, height; int hdr, zsize, npal, tidx = -1, ret; int i, j; const uint8_t *src_end = src + src_size; uint8_t pal[768], transp[3]; uLongf dlen = (c->tile_width + 1) * c->tile_height; int sub_type; int nblocks, cblocks, bstride; int bits, bitbuf, coded; uint8_t *dst = c->framebuf + tile_x * c->tile_width * 3 + tile_y * c->tile_height * c->framebuf_stride; if (src_size < 2) return AVERROR_INVALIDDATA; width = FFMIN(c->width - tile_x * c->tile_width, c->tile_width); height = FFMIN(c->height - tile_y * c->tile_height, c->tile_height); hdr = *src++; sub_type = hdr >> 5; if (sub_type == 0) { int j; memcpy(transp, src, 3); src += 3; for (j = 0; j < height; j++, dst += c->framebuf_stride) for (i = 0; i < width; i++) memcpy(dst + i * 3, transp, 3); return 0; } else if (sub_type == 1) { return jpg_decode_data(&c->jc, width, height, src, src_end - src, dst, c->framebuf_stride, NULL, 0, 0, 0); } if (sub_type != 2) { memcpy(transp, src, 3); src += 3; } npal = *src++ + 1; memcpy(pal, src, npal * 3); src += npal * 3; if (sub_type != 2) { for (i = 0; i < npal; i++) { if (!memcmp(pal + i * 3, transp, 3)) { tidx = i; break; } } } if (src_end - src < 2) return 0; zsize = (src[0] << 8) | src[1]; src += 2; if (src_end - src < zsize + (sub_type != 2)) return AVERROR_INVALIDDATA; ret = uncompress(c->kempf_buf, &dlen, src, zsize); if (ret) return AVERROR_INVALIDDATA; src += zsize; if (sub_type == 2) { kempf_restore_buf(c->kempf_buf, dlen, dst, c->framebuf_stride, NULL, 0, width, height, pal, npal, tidx); return 0; } nblocks = *src++ + 1; cblocks = 0; bstride = FFALIGN(width, 16) >> 4; // blocks are coded LSB and we need normal bitreader for JPEG data bits = 0; for (i = 0; i < (FFALIGN(height, 16) >> 4); i++) { for (j = 0; j < (FFALIGN(width, 16) >> 4); j++) { if (!bits) { if (src >= src_end) return AVERROR_INVALIDDATA; bitbuf = *src++; bits = 8; } coded = bitbuf & 1; bits--; bitbuf >>= 1; cblocks += coded; if (cblocks > nblocks) return AVERROR_INVALIDDATA; c->kempf_flags[j + i * bstride] = coded; } } memset(c->jpeg_tile, 0, c->tile_stride * height); jpg_decode_data(&c->jc, width, height, src, src_end - src, c->jpeg_tile, c->tile_stride, c->kempf_flags, bstride, nblocks, 0); kempf_restore_buf(c->kempf_buf, dlen, dst, c->framebuf_stride, c->jpeg_tile, c->tile_stride, width, height, pal, npal, tidx); return 0; } static int g2m_init_buffers(G2MContext *c) { int aligned_height; if (!c->framebuf || c->old_width < c->width || c->old_height < c->height) { c->framebuf_stride = FFALIGN(c->width + 15, 16) * 3; aligned_height = c->height + 15; av_free(c->framebuf); c->framebuf = av_mallocz(c->framebuf_stride * aligned_height); if (!c->framebuf) return AVERROR(ENOMEM); } if (!c->synth_tile || !c->jpeg_tile || c->old_tile_w < c->tile_width || c->old_tile_h < c->tile_height) { c->tile_stride = FFALIGN(c->tile_width, 16) * 3; aligned_height = FFALIGN(c->tile_height, 16); av_free(c->synth_tile); av_free(c->jpeg_tile); av_free(c->kempf_buf); av_free(c->kempf_flags); c->synth_tile = av_mallocz(c->tile_stride * aligned_height); c->jpeg_tile = av_mallocz(c->tile_stride * aligned_height); c->kempf_buf = av_mallocz((c->tile_width + 1) * aligned_height + FF_INPUT_BUFFER_PADDING_SIZE); c->kempf_flags = av_mallocz( c->tile_width * aligned_height); if (!c->synth_tile || !c->jpeg_tile || !c->kempf_buf || !c->kempf_flags) return AVERROR(ENOMEM); } return 0; } static int g2m_load_cursor(AVCodecContext *avctx, G2MContext *c, GetByteContext *gb) { int i, j, k; uint8_t *dst; uint32_t bits; uint32_t cur_size, cursor_w, cursor_h, cursor_stride; uint32_t cursor_hot_x, cursor_hot_y; int cursor_fmt; uint8_t *tmp; cur_size = bytestream2_get_be32(gb); cursor_w = bytestream2_get_byte(gb); cursor_h = bytestream2_get_byte(gb); cursor_hot_x = bytestream2_get_byte(gb); cursor_hot_y = bytestream2_get_byte(gb); cursor_fmt = bytestream2_get_byte(gb); cursor_stride = FFALIGN(cursor_w, 32) * 4; if (cursor_w < 1 || cursor_w > 256 || cursor_h < 1 || cursor_h > 256) { av_log(avctx, AV_LOG_ERROR, "Invalid cursor dimensions %dx%d\n", cursor_w, cursor_h); return AVERROR_INVALIDDATA; } if (cursor_hot_x > cursor_w || cursor_hot_y > cursor_h) { av_log(avctx, AV_LOG_WARNING, "Invalid hotspot position %d,%d\n", cursor_hot_x, cursor_hot_y); cursor_hot_x = FFMIN(cursor_hot_x, cursor_w - 1); cursor_hot_y = FFMIN(cursor_hot_y, cursor_h - 1); } if (cur_size - 9 > bytestream2_get_bytes_left(gb) || c->cursor_w * c->cursor_h / 4 > cur_size) { av_log(avctx, AV_LOG_ERROR, "Invalid cursor data size %d/%d\n", cur_size, bytestream2_get_bytes_left(gb)); return AVERROR_INVALIDDATA; } if (cursor_fmt != 1 && cursor_fmt != 32) { avpriv_report_missing_feature(avctx, "Cursor format %d", cursor_fmt); return AVERROR_PATCHWELCOME; } tmp = av_realloc(c->cursor, cursor_stride * cursor_h); if (!tmp) { av_log(avctx, AV_LOG_ERROR, "Cannot allocate cursor buffer\n"); return AVERROR(ENOMEM); } c->cursor = tmp; c->cursor_w = cursor_w; c->cursor_h = cursor_h; c->cursor_hot_x = cursor_hot_x; c->cursor_hot_y = cursor_hot_y; c->cursor_fmt = cursor_fmt; c->cursor_stride = cursor_stride; dst = c->cursor; switch (c->cursor_fmt) { case 1: // old monochrome for (j = 0; j < c->cursor_h; j++) { for (i = 0; i < c->cursor_w; i += 32) { bits = bytestream2_get_be32(gb); for (k = 0; k < 32; k++) { dst[0] = !!(bits & 0x80000000); dst += 4; bits <<= 1; } } } dst = c->cursor; for (j = 0; j < c->cursor_h; j++) { for (i = 0; i < c->cursor_w; i += 32) { bits = bytestream2_get_be32(gb); for (k = 0; k < 32; k++) { int mask_bit = !!(bits & 0x80000000); switch (dst[0] * 2 + mask_bit) { case 0: dst[0] = 0xFF; dst[1] = 0x00; dst[2] = 0x00; dst[3] = 0x00; break; case 1: dst[0] = 0xFF; dst[1] = 0xFF; dst[2] = 0xFF; dst[3] = 0xFF; break; default: dst[0] = 0x00; dst[1] = 0x00; dst[2] = 0x00; dst[3] = 0x00; } dst += 4; bits <<= 1; } } } break; case 32: // full colour /* skip monochrome version of the cursor and decode RGBA instead */ bytestream2_skip(gb, c->cursor_h * (FFALIGN(c->cursor_w, 32) >> 3)); for (j = 0; j < c->cursor_h; j++) { for (i = 0; i < c->cursor_w; i++) { int val = bytestream2_get_be32(gb); *dst++ = val >> 0; *dst++ = val >> 8; *dst++ = val >> 16; *dst++ = val >> 24; } } break; default: return AVERROR_PATCHWELCOME; } return 0; } #define APPLY_ALPHA(src, new, alpha) \ src = (src * (256 - alpha) + new * alpha) >> 8 static void g2m_paint_cursor(G2MContext *c, uint8_t *dst, int stride) { int i, j; int x, y, w, h; const uint8_t *cursor; if (!c->cursor) return; x = c->cursor_x - c->cursor_hot_x; y = c->cursor_y - c->cursor_hot_y; cursor = c->cursor; w = c->cursor_w; h = c->cursor_h; if (x + w > c->width) w = c->width - x; if (y + h > c->height) h = c->height - y; if (x < 0) { w += x; cursor += -x * 4; } else { dst += x * 3; } if (y < 0) { h += y; cursor += -y * c->cursor_stride; } else { dst += y * stride; } if (w < 0 || h < 0) return; for (j = 0; j < h; j++) { for (i = 0; i < w; i++) { uint8_t alpha = cursor[i * 4]; APPLY_ALPHA(dst[i * 3 + 0], cursor[i * 4 + 1], alpha); APPLY_ALPHA(dst[i * 3 + 1], cursor[i * 4 + 2], alpha); APPLY_ALPHA(dst[i * 3 + 2], cursor[i * 4 + 3], alpha); } dst += stride; cursor += c->cursor_stride; } } static int g2m_decode_frame(AVCodecContext *avctx, void *data, int *got_picture_ptr, AVPacket *avpkt) { const uint8_t *buf = avpkt->data; int buf_size = avpkt->size; G2MContext *c = avctx->priv_data; AVFrame *pic = data; GetByteContext bc, tbc; int magic; int got_header = 0; uint32_t chunk_size; int chunk_type; int i; int ret; if (buf_size < 12) { av_log(avctx, AV_LOG_ERROR, "Frame should have at least 12 bytes, got %d instead\n", buf_size); return AVERROR_INVALIDDATA; } bytestream2_init(&bc, buf, buf_size); magic = bytestream2_get_be32(&bc); if ((magic & ~0xF) != MKBETAG('G', '2', 'M', '0') || (magic & 0xF) < 2 || (magic & 0xF) > 4) { av_log(avctx, AV_LOG_ERROR, "Wrong magic %08X\n", magic); return AVERROR_INVALIDDATA; } if ((magic & 0xF) != 4) { av_log(avctx, AV_LOG_ERROR, "G2M2 and G2M3 are not yet supported\n"); return AVERROR(ENOSYS); } while (bytestream2_get_bytes_left(&bc) > 5) { chunk_size = bytestream2_get_le32(&bc) - 1; chunk_type = bytestream2_get_byte(&bc); if (chunk_size > bytestream2_get_bytes_left(&bc)) { av_log(avctx, AV_LOG_ERROR, "Invalid chunk size %d type %02X\n", chunk_size, chunk_type); break; } switch (chunk_type) { case FRAME_INFO: c->got_header = 0; if (chunk_size < 21) { av_log(avctx, AV_LOG_ERROR, "Invalid frame info size %d\n", chunk_size); break; } c->width = bytestream2_get_be32(&bc); c->height = bytestream2_get_be32(&bc); if (c->width < 16 || c->width > avctx->width || c->height < 16 || c->height > avctx->height) { av_log(avctx, AV_LOG_ERROR, "Invalid frame dimensions %dx%d\n", c->width, c->height); ret = AVERROR_INVALIDDATA; goto header_fail; } if (c->width != avctx->width || c->height != avctx->height) avcodec_set_dimensions(avctx, c->width, c->height); c->compression = bytestream2_get_be32(&bc); if (c->compression != 2 && c->compression != 3) { av_log(avctx, AV_LOG_ERROR, "Unknown compression method %d\n", c->compression); return AVERROR_PATCHWELCOME; } c->tile_width = bytestream2_get_be32(&bc); c->tile_height = bytestream2_get_be32(&bc); if (!c->tile_width || !c->tile_height) { av_log(avctx, AV_LOG_ERROR, "Invalid tile dimensions %dx%d\n", c->tile_width, c->tile_height); ret = AVERROR_INVALIDDATA; goto header_fail; } c->tiles_x = (c->width + c->tile_width - 1) / c->tile_width; c->tiles_y = (c->height + c->tile_height - 1) / c->tile_height; c->bpp = bytestream2_get_byte(&bc); chunk_size -= 21; bytestream2_skip(&bc, chunk_size); if (g2m_init_buffers(c)) { ret = AVERROR(ENOMEM); goto header_fail; } got_header = 1; break; case TILE_DATA: if (!c->tiles_x || !c->tiles_y) { av_log(avctx, AV_LOG_WARNING, "No frame header - skipping tile\n"); bytestream2_skip(&bc, bytestream2_get_bytes_left(&bc)); break; } if (chunk_size < 2) { av_log(avctx, AV_LOG_ERROR, "Invalid tile data size %d\n", chunk_size); break; } c->tile_x = bytestream2_get_byte(&bc); c->tile_y = bytestream2_get_byte(&bc); if (c->tile_x >= c->tiles_x || c->tile_y >= c->tiles_y) { av_log(avctx, AV_LOG_ERROR, "Invalid tile pos %d,%d (in %dx%d grid)\n", c->tile_x, c->tile_y, c->tiles_x, c->tiles_y); break; } chunk_size -= 2; ret = 0; switch (c->compression) { case COMPR_EPIC_J_B: av_log(avctx, AV_LOG_ERROR, "ePIC j-b compression is not implemented yet\n"); return AVERROR(ENOSYS); case COMPR_KEMPF_J_B: ret = kempf_decode_tile(c, c->tile_x, c->tile_y, buf + bytestream2_tell(&bc), chunk_size); break; } if (ret && c->framebuf) av_log(avctx, AV_LOG_ERROR, "Error decoding tile %d,%d\n", c->tile_x, c->tile_y); bytestream2_skip(&bc, chunk_size); break; case CURSOR_POS: if (chunk_size < 5) { av_log(avctx, AV_LOG_ERROR, "Invalid cursor pos size %d\n", chunk_size); break; } c->cursor_x = bytestream2_get_be16(&bc); c->cursor_y = bytestream2_get_be16(&bc); bytestream2_skip(&bc, chunk_size - 4); break; case CURSOR_SHAPE: if (chunk_size < 8) { av_log(avctx, AV_LOG_ERROR, "Invalid cursor data size %d\n", chunk_size); break; } bytestream2_init(&tbc, buf + bytestream2_tell(&bc), chunk_size - 4); g2m_load_cursor(avctx, c, &tbc); bytestream2_skip(&bc, chunk_size); break; case CHUNK_CC: case CHUNK_CD: bytestream2_skip(&bc, chunk_size); break; default: av_log(avctx, AV_LOG_WARNING, "Skipping chunk type %02X\n", chunk_type); bytestream2_skip(&bc, chunk_size); } } if (got_header) c->got_header = 1; if (c->width && c->height && c->framebuf) { if ((ret = ff_get_buffer(avctx, pic, 0)) < 0) return ret; pic->key_frame = got_header; pic->pict_type = got_header ? AV_PICTURE_TYPE_I : AV_PICTURE_TYPE_P; for (i = 0; i < avctx->height; i++) memcpy(pic->data[0] + i * pic->linesize[0], c->framebuf + i * c->framebuf_stride, c->width * 3); g2m_paint_cursor(c, pic->data[0], pic->linesize[0]); *got_picture_ptr = 1; } return buf_size; header_fail: c->width = c->height = 0; c->tiles_x = c->tiles_y = 0; return ret; } static av_cold int g2m_decode_init(AVCodecContext *avctx) { G2MContext * const c = avctx->priv_data; int ret; if ((ret = jpg_init(avctx, &c->jc)) != 0) { av_log(avctx, AV_LOG_ERROR, "Cannot initialise VLCs\n"); jpg_free_context(&c->jc); return AVERROR(ENOMEM); } avctx->pix_fmt = AV_PIX_FMT_RGB24; return 0; } static av_cold int g2m_decode_end(AVCodecContext *avctx) { G2MContext * const c = avctx->priv_data; jpg_free_context(&c->jc); av_freep(&c->kempf_buf); av_freep(&c->kempf_flags); av_freep(&c->synth_tile); av_freep(&c->jpeg_tile); av_freep(&c->cursor); av_freep(&c->framebuf); return 0; } AVCodec ff_g2m_decoder = { .name = "g2m", .long_name = NULL_IF_CONFIG_SMALL("Go2Meeting"), .type = AVMEDIA_TYPE_VIDEO, .id = AV_CODEC_ID_G2M, .priv_data_size = sizeof(G2MContext), .init = g2m_decode_init, .close = g2m_decode_end, .decode = g2m_decode_frame, .capabilities = CODEC_CAP_DR1, };
./CrossVul/dataset_final_sorted/CWE-119/c/good_5826_0
crossvul-cpp_data_bad_936_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP N N M M % % P P NN N MM MM % % PPPP N N N M M M % % P N NN M M % % P N N M M % % % % % % Read/Write PBMPlus Portable Anymap Image Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/module.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/property.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" /* Typedef declarations. */ typedef struct _CommentInfo { char *comment; size_t extent; } CommentInfo; /* Forward declarations. */ static MagickBooleanType WritePNMImage(const ImageInfo *,Image *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P N M % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPNM() returns MagickTrue if the image format type, identified by the % magick string, is PNM. % % The format of the IsPNM method is: % % MagickBooleanType IsPNM(const unsigned char *magick,const size_t extent) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o extent: Specifies the extent of the magick string. % */ static MagickBooleanType IsPNM(const unsigned char *magick,const size_t extent) { if (extent < 2) return(MagickFalse); if ((*magick == (unsigned char) 'P') && ((magick[1] == '1') || (magick[1] == '2') || (magick[1] == '3') || (magick[1] == '4') || (magick[1] == '5') || (magick[1] == '6') || (magick[1] == '7') || (magick[1] == 'F') || (magick[1] == 'f'))) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P N M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPNMImage() reads a Portable Anymap image file and returns it. % It allocates the memory necessary for the new Image structure and returns % a pointer to the new image. % % The format of the ReadPNMImage method is: % % Image *ReadPNMImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static int PNMComment(Image *image,CommentInfo *comment_info, ExceptionInfo *exception) { int c; register char *p; /* Read comment. */ p=comment_info->comment+strlen(comment_info->comment); for (c='#'; (c != EOF) && (c != (int) '\n') && (c != (int) '\r'); p++) { if ((size_t) (p-comment_info->comment+1) >= comment_info->extent) { comment_info->extent<<=1; comment_info->comment=(char *) ResizeQuantumMemory( comment_info->comment,comment_info->extent, sizeof(*comment_info->comment)); if (comment_info->comment == (char *) NULL) return(-1); p=comment_info->comment+strlen(comment_info->comment); } c=ReadBlobByte(image); if (c != EOF) { *p=(char) c; *(p+1)='\0'; } } return(c); } static unsigned int PNMInteger(Image *image,CommentInfo *comment_info, const unsigned int base,ExceptionInfo *exception) { int c; unsigned int value; /* Skip any leading whitespace. */ do { c=ReadBlobByte(image); if (c == EOF) return(0); if (c == (int) '#') c=PNMComment(image,comment_info,exception); } while ((c == ' ') || (c == '\t') || (c == '\n') || (c == '\r')); if (base == 2) return((unsigned int) (c-(int) '0')); /* Evaluate number. */ value=0; while (isdigit(c) != 0) { if (value <= (unsigned int) (INT_MAX/10)) { value*=10; if (value <= (unsigned int) (INT_MAX-(c-(int) '0'))) value+=c-(int) '0'; } c=ReadBlobByte(image); if (c == EOF) return(0); } if (c == (int) '#') c=PNMComment(image,comment_info,exception); return(value); } static Image *ReadPNMImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define ThrowPNMException(exception,message) \ { \ if (comment_info.comment != (char *) NULL) \ comment_info.comment=DestroyString(comment_info.comment); \ ThrowReaderException((exception),(message)); \ } char format; CommentInfo comment_info; double quantum_scale; Image *image; MagickBooleanType status; QuantumAny max_value; QuantumInfo *quantum_info; QuantumType quantum_type; size_t depth, extent, packet_size; ssize_t count, row, y; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read PNM image. */ count=ReadBlob(image,1,(unsigned char *) &format); do { /* Initialize image structure. */ comment_info.comment=AcquireString(NULL); comment_info.extent=MagickPathExtent; if ((count != 1) || (format != 'P')) ThrowPNMException(CorruptImageError,"ImproperImageHeader"); max_value=1; quantum_type=RGBQuantum; quantum_scale=1.0; format=(char) ReadBlobByte(image); if (format != '7') { /* PBM, PGM, PPM, and PNM. */ image->columns=(size_t) PNMInteger(image,&comment_info,10,exception); image->rows=(size_t) PNMInteger(image,&comment_info,10,exception); if ((format == 'f') || (format == 'F')) { char scale[MagickPathExtent]; if (ReadBlobString(image,scale) != (char *) NULL) quantum_scale=StringToDouble(scale,(char **) NULL); } else { if ((format == '1') || (format == '4')) max_value=1; /* bitmap */ else max_value=(QuantumAny) PNMInteger(image,&comment_info,10, exception); } } else { char keyword[MagickPathExtent], value[MagickPathExtent]; int c; register char *p; /* PAM. */ for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image)) { while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); if (c == '#') { /* Comment. */ c=PNMComment(image,&comment_info,exception); c=ReadBlobByte(image); while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); } p=keyword; do { if ((size_t) (p-keyword) < (MagickPathExtent-1)) *p++=c; c=ReadBlobByte(image); } while (isalnum(c)); *p='\0'; if (LocaleCompare(keyword,"endhdr") == 0) break; while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); p=value; while (isalnum(c) || (c == '_')) { if ((size_t) (p-value) < (MagickPathExtent-1)) *p++=c; c=ReadBlobByte(image); } *p='\0'; /* Assign a value to the specified keyword. */ if (LocaleCompare(keyword,"depth") == 0) packet_size=StringToUnsignedLong(value); (void) packet_size; if (LocaleCompare(keyword,"height") == 0) image->rows=StringToUnsignedLong(value); if (LocaleCompare(keyword,"maxval") == 0) max_value=StringToUnsignedLong(value); if (LocaleCompare(keyword,"TUPLTYPE") == 0) { if (LocaleCompare(value,"BLACKANDWHITE") == 0) { (void) SetImageColorspace(image,GRAYColorspace,exception); quantum_type=GrayQuantum; } if (LocaleCompare(value,"BLACKANDWHITE_ALPHA") == 0) { (void) SetImageColorspace(image,GRAYColorspace,exception); image->alpha_trait=BlendPixelTrait; quantum_type=GrayAlphaQuantum; } if (LocaleCompare(value,"GRAYSCALE") == 0) { quantum_type=GrayQuantum; (void) SetImageColorspace(image,GRAYColorspace,exception); } if (LocaleCompare(value,"GRAYSCALE_ALPHA") == 0) { (void) SetImageColorspace(image,GRAYColorspace,exception); image->alpha_trait=BlendPixelTrait; quantum_type=GrayAlphaQuantum; } if (LocaleCompare(value,"RGB_ALPHA") == 0) { image->alpha_trait=BlendPixelTrait; quantum_type=RGBAQuantum; } if (LocaleCompare(value,"CMYK") == 0) { (void) SetImageColorspace(image,CMYKColorspace,exception); quantum_type=CMYKQuantum; } if (LocaleCompare(value,"CMYK_ALPHA") == 0) { (void) SetImageColorspace(image,CMYKColorspace,exception); image->alpha_trait=BlendPixelTrait; quantum_type=CMYKAQuantum; } } if (LocaleCompare(keyword,"width") == 0) image->columns=StringToUnsignedLong(value); } } if ((image->columns == 0) || (image->rows == 0)) ThrowPNMException(CorruptImageError,"NegativeOrZeroImageSize"); if ((max_value == 0) || (max_value > 4294967295UL)) ThrowPNMException(CorruptImageError,"ImproperImageHeader"); for (depth=1; GetQuantumRange(depth) < max_value; depth++) ; image->depth=depth; if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if ((MagickSizeType) (image->columns*image->rows/8) > GetBlobSize(image)) ThrowPNMException(CorruptImageError,"InsufficientImageDataInFile"); status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) { comment_info.comment=DestroyString(comment_info.comment); \ return(DestroyImageList(image)); } (void) ResetImagePixels(image,exception); /* Convert PNM pixels to runextent-encoded MIFF packets. */ row=0; y=0; switch (format) { case '1': { /* Convert PBM image to pixel packets. */ (void) SetImageColorspace(image,GRAYColorspace,exception); for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelGray(image,PNMInteger(image,&comment_info,2,exception) == 0 ? QuantumRange : 0,q); if (EOFBlob(image) != MagickFalse) break; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (EOFBlob(image) != MagickFalse) break; } image->type=BilevelType; break; } case '2': { Quantum intensity; /* Convert PGM image to pixel packets. */ (void) SetImageColorspace(image,GRAYColorspace,exception); for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { intensity=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10, exception),max_value); if (EOFBlob(image) != MagickFalse) break; SetPixelGray(image,intensity,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (EOFBlob(image) != MagickFalse) break; } image->type=GrayscaleType; break; } case '3': { /* Convert PNM image to pixel packets. */ for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Quantum pixel; pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10, exception),max_value); if (EOFBlob(image) != MagickFalse) break; SetPixelRed(image,pixel,q); pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10, exception),max_value); SetPixelGreen(image,pixel,q); pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10, exception),max_value); SetPixelBlue(image,pixel,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (EOFBlob(image) != MagickFalse) break; } break; } case '4': { /* Convert PBM raw image to pixel packets. */ (void) SetImageColorspace(image,GRAYColorspace,exception); quantum_type=GrayQuantum; if (image->storage_class == PseudoClass) quantum_type=IndexQuantum; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); SetQuantumMinIsWhite(quantum_info,MagickTrue); extent=GetQuantumExtent(image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register Quantum *magick_restrict q; ssize_t offset; size_t length; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception); if (q == (Quantum *) NULL) break; length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (length != extent) break; sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); SetQuantumImageType(image,quantum_type); break; } case '5': { /* Convert PGM raw image to pixel packets. */ (void) SetImageColorspace(image,GRAYColorspace,exception); quantum_type=GrayQuantum; extent=(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)* image->columns; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register const unsigned char *magick_restrict p; register ssize_t x; register Quantum *magick_restrict q; ssize_t offset; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception); if (q == (Quantum *) NULL) break; p=pixels; switch (image->depth) { case 8: case 16: case 32: { (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } default: { if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value),q); q+=GetPixelChannels(image); } } else if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value),q); q+=GetPixelChannels(image); } } else { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value),q); q+=GetPixelChannels(image); } } break; } } sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); SetQuantumImageType(image,quantum_type); break; } case '6': { /* Convert PNM raster image to pixel packets. */ quantum_type=RGBQuantum; extent=3*(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)* image->columns; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register const unsigned char *magick_restrict p; register ssize_t x; register Quantum *magick_restrict q; ssize_t offset; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception); if (q == (Quantum *) NULL) break; p=pixels; switch (image->depth) { case 8: { for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelBlue(image,ScaleCharToQuantum(*p++),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } break; } case 16: { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleShortToQuantum(pixel),q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleShortToQuantum(pixel),q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleShortToQuantum(pixel),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } break; } case 32: { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleLongToQuantum(pixel),q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleLongToQuantum(pixel),q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleLongToQuantum(pixel),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } break; } default: { if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushCharPixel(p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushCharPixel(p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } } else if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } } else { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } } break; } } sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '7': { size_t channels; /* Convert PAM raster image to pixel packets. */ switch (quantum_type) { case GrayQuantum: case GrayAlphaQuantum: { channels=1; break; } case CMYKQuantum: case CMYKAQuantum: { channels=4; break; } default: { channels=3; break; } } if (image->alpha_trait != UndefinedPixelTrait) channels++; extent=channels*(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)* image->columns; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register const unsigned char *magick_restrict p; register ssize_t x; register Quantum *magick_restrict q; ssize_t offset; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception); if (q == (Quantum *) NULL) break; p=pixels; switch (image->depth) { case 8: case 16: case 32: { (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } default: { switch (quantum_type) { case GrayQuantum: case GrayAlphaQuantum: { if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushCharPixel(p,&pixel); if (image->depth != 1) SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); else SetPixelAlpha(image,QuantumRange- ScaleAnyToQuantum(pixel,max_value),q); } q+=GetPixelChannels(image); } } else if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } else { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } break; } case CMYKQuantum: case CMYKAQuantum: { if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushCharPixel(p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushCharPixel(p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushCharPixel(p,&pixel); SetPixelBlack(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushCharPixel(p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } else if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlack(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } else { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlack(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } break; } default: { if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushCharPixel(p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushCharPixel(p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushCharPixel(p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } else if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } else { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } break; } } } } sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); SetQuantumImageType(image,quantum_type); break; } case 'F': case 'f': { /* Convert PFM raster image to pixel packets. */ if (format == 'f') (void) SetImageColorspace(image,GRAYColorspace,exception); quantum_type=format == 'f' ? GrayQuantum : RGBQuantum; image->endian=quantum_scale < 0.0 ? LSBEndian : MSBEndian; image->depth=32; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); status=SetQuantumDepth(image,quantum_info,32); if (status == MagickFalse) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); SetQuantumScale(quantum_info,(double) QuantumRange*fabs(quantum_scale)); extent=GetQuantumExtent(image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register Quantum *magick_restrict q; ssize_t offset; size_t length; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,(ssize_t) (image->rows-offset-1), image->columns,1,exception); if (q == (Quantum *) NULL) break; length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (length != extent) break; sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); SetQuantumImageType(image,quantum_type); break; } default: ThrowPNMException(CorruptImageError,"ImproperImageHeader"); } if (*comment_info.comment != '\0') (void) SetImageProperty(image,"comment",comment_info.comment,exception); comment_info.comment=DestroyString(comment_info.comment); if (y < (ssize_t) image->rows) ThrowPNMException(CorruptImageError,"UnableToReadImageData"); if (EOFBlob(image) != MagickFalse) { (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageError,"UnexpectedEndOfFile","`%s'",image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if ((format == '1') || (format == '2') || (format == '3')) do { /* Skip to end of line. */ count=ReadBlob(image,1,(unsigned char *) &format); if (count != 1) break; if (format == 'P') break; } while (format != '\n'); count=ReadBlob(image,1,(unsigned char *) &format); if ((count == 1) && (format == 'P')) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { status=MagickFalse; break; } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while ((count == 1) && (format == 'P')); (void) CloseBlob(image); if (status == MagickFalse) return(DestroyImageList(image)); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P N M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPNMImage() adds properties for the PNM image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterPNMImage method is: % % size_t RegisterPNMImage(void) % */ ModuleExport size_t RegisterPNMImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("PNM","PAM","Common 2-dimensional bitmap format"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->mime_type=ConstantString("image/x-portable-pixmap"); entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNM","PBM", "Portable bitmap format (black and white)"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->mime_type=ConstantString("image/x-portable-bitmap"); entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNM","PFM","Portable float format"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->flags|=CoderEndianSupportFlag; entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNM","PGM","Portable graymap format (gray scale)"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->mime_type=ConstantString("image/x-portable-greymap"); entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNM","PNM","Portable anymap"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->magick=(IsImageFormatHandler *) IsPNM; entry->mime_type=ConstantString("image/x-portable-pixmap"); entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNM","PPM","Portable pixmap format (color)"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->mime_type=ConstantString("image/x-portable-pixmap"); entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P N M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPNMImage() removes format registrations made by the % PNM module from the list of supported formats. % % The format of the UnregisterPNMImage method is: % % UnregisterPNMImage(void) % */ ModuleExport void UnregisterPNMImage(void) { (void) UnregisterMagickInfo("PAM"); (void) UnregisterMagickInfo("PBM"); (void) UnregisterMagickInfo("PGM"); (void) UnregisterMagickInfo("PNM"); (void) UnregisterMagickInfo("PPM"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P N M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePNMImage() writes an image to a file in the PNM rasterfile format. % % The format of the WritePNMImage method is: % % MagickBooleanType WritePNMImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WritePNMImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { char buffer[MagickPathExtent], format, magick[MagickPathExtent]; const char *value; MagickBooleanType status; MagickOffsetType scene; Quantum index; QuantumAny pixel; QuantumInfo *quantum_info; QuantumType quantum_type; register unsigned char *q; size_t extent, imageListLength, packet_size; ssize_t count, y; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); scene=0; imageListLength=GetImageListLength(image); do { QuantumAny max_value; /* Write PNM file header. */ packet_size=3; quantum_type=RGBQuantum; (void) CopyMagickString(magick,image_info->magick,MagickPathExtent); max_value=GetQuantumRange(image->depth); switch (magick[1]) { case 'A': case 'a': { format='7'; break; } case 'B': case 'b': { format='4'; if (image_info->compression == NoCompression) format='1'; break; } case 'F': case 'f': { format='F'; if (SetImageGray(image,exception) != MagickFalse) format='f'; break; } case 'G': case 'g': { format='5'; if (image_info->compression == NoCompression) format='2'; break; } case 'N': case 'n': { if ((image_info->type != TrueColorType) && (SetImageGray(image,exception) != MagickFalse)) { format='5'; if (image_info->compression == NoCompression) format='2'; if (SetImageMonochrome(image,exception) != MagickFalse) { format='4'; if (image_info->compression == NoCompression) format='1'; } break; } } default: { format='6'; if (image_info->compression == NoCompression) format='3'; break; } } (void) FormatLocaleString(buffer,MagickPathExtent,"P%c\n",format); (void) WriteBlobString(image,buffer); value=GetImageProperty(image,"comment",exception); if (value != (const char *) NULL) { register const char *p; /* Write comments to file. */ (void) WriteBlobByte(image,'#'); for (p=value; *p != '\0'; p++) { (void) WriteBlobByte(image,(unsigned char) *p); if ((*p == '\n') || (*p == '\r')) (void) WriteBlobByte(image,'#'); } (void) WriteBlobByte(image,'\n'); } if (format != '7') { (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g %.20g\n", (double) image->columns,(double) image->rows); (void) WriteBlobString(image,buffer); } else { char type[MagickPathExtent]; /* PAM header. */ (void) FormatLocaleString(buffer,MagickPathExtent, "WIDTH %.20g\nHEIGHT %.20g\n",(double) image->columns,(double) image->rows); (void) WriteBlobString(image,buffer); quantum_type=GetQuantumType(image,exception); switch (quantum_type) { case CMYKQuantum: case CMYKAQuantum: { packet_size=4; (void) CopyMagickString(type,"CMYK",MagickPathExtent); break; } case GrayQuantum: case GrayAlphaQuantum: { packet_size=1; (void) CopyMagickString(type,"GRAYSCALE",MagickPathExtent); if (IdentifyImageMonochrome(image,exception) != MagickFalse) (void) CopyMagickString(type,"BLACKANDWHITE",MagickPathExtent); break; } default: { quantum_type=RGBQuantum; if (image->alpha_trait != UndefinedPixelTrait) quantum_type=RGBAQuantum; packet_size=3; (void) CopyMagickString(type,"RGB",MagickPathExtent); break; } } if (image->alpha_trait != UndefinedPixelTrait) { packet_size++; (void) ConcatenateMagickString(type,"_ALPHA",MagickPathExtent); } if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MagickPathExtent, "DEPTH %.20g\nMAXVAL %.20g\n",(double) packet_size,(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent, "TUPLTYPE %s\nENDHDR\n",type); (void) WriteBlobString(image,buffer); } /* Convert runextent encoded to PNM raster pixels. */ switch (format) { case '1': { unsigned char pixels[2048]; /* Convert image to a PBM image. */ (void) SetImageType(image,BilevelType,exception); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=(unsigned char) (GetPixelLuma(image,p) >= (QuantumRange/2.0) ? '0' : '1'); *q++=' '; if ((q-pixels+1) >= (ssize_t) sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } p+=GetPixelChannels(image); } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '2': { unsigned char pixels[2048]; /* Convert image to a PGM image. */ if (image->depth <= 8) (void) WriteBlobString(image,"255\n"); else if (image->depth <= 16) (void) WriteBlobString(image,"65535\n"); else (void) WriteBlobString(image,"4294967295\n"); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { index=ClampToQuantum(GetPixelLuma(image,p)); if (image->depth <= 8) count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,"%u ", ScaleQuantumToChar(index)); else if (image->depth <= 16) count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u ",ScaleQuantumToShort(index)); else count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u ",ScaleQuantumToLong(index)); extent=(size_t) count; (void) strncpy((char *) q,buffer,extent); q+=extent; if ((q-pixels+extent+2) >= sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } p+=GetPixelChannels(image); } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '3': { unsigned char pixels[2048]; /* Convert image to a PNM image. */ (void) TransformImageColorspace(image,sRGBColorspace,exception); if (image->depth <= 8) (void) WriteBlobString(image,"255\n"); else if (image->depth <= 16) (void) WriteBlobString(image,"65535\n"); else (void) WriteBlobString(image,"4294967295\n"); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->depth <= 8) count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u %u %u ",ScaleQuantumToChar(GetPixelRed(image,p)), ScaleQuantumToChar(GetPixelGreen(image,p)), ScaleQuantumToChar(GetPixelBlue(image,p))); else if (image->depth <= 16) count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u %u %u ",ScaleQuantumToShort(GetPixelRed(image,p)), ScaleQuantumToShort(GetPixelGreen(image,p)), ScaleQuantumToShort(GetPixelBlue(image,p))); else count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u %u %u ",ScaleQuantumToLong(GetPixelRed(image,p)), ScaleQuantumToLong(GetPixelGreen(image,p)), ScaleQuantumToLong(GetPixelBlue(image,p))); extent=(size_t) count; (void) strncpy((char *) q,buffer,extent); q+=extent; if ((q-pixels+extent+2) >= sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } p+=GetPixelChannels(image); } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '4': { register unsigned char *pixels; /* Convert image to a PBM image. */ (void) SetImageType(image,BilevelType,exception); image->depth=1; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); quantum_info->min_is_white=MagickTrue; pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayQuantum,pixels,exception); count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '5': { register unsigned char *pixels; /* Convert image to a PGM image. */ if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); quantum_info->min_is_white=MagickTrue; pixels=GetQuantumPixels(quantum_info); extent=GetQuantumExtent(image,quantum_info,GrayQuantum); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayQuantum,pixels,exception); break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { if (IsPixelGray(image,p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma( image,p)),max_value); else { if (image->depth == 8) pixel=ScaleQuantumToChar(GetPixelRed(image,p)); else pixel=ScaleQuantumToAny(GetPixelRed(image,p), max_value); } q=PopCharPixel((unsigned char) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { if (IsPixelGray(image,p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image, p)),max_value); else { if (image->depth == 16) pixel=ScaleQuantumToShort(GetPixelRed(image,p)); else pixel=ScaleQuantumToAny(GetPixelRed(image,p), max_value); } q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } for (x=0; x < (ssize_t) image->columns; x++) { if (IsPixelGray(image,p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image,p)), max_value); else { if (image->depth == 16) pixel=ScaleQuantumToLong(GetPixelRed(image,p)); else pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); } q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '6': { register unsigned char *pixels; /* Convert image to a PNM image. */ (void) TransformImageColorspace(image,sRGBColorspace,exception); if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); pixels=GetQuantumPixels(quantum_info); extent=GetQuantumExtent(image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '7': { register unsigned char *pixels; /* Convert image to a PAM. */ if (image->depth > 32) image->depth=32; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } default: { switch (quantum_type) { case GrayQuantum: case GrayAlphaQuantum: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma( image,p)),max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelAlpha(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); } p+=GetPixelChannels(image); } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma( image,p)),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelAlpha(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image, p)),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelAlpha(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p+=GetPixelChannels(image); } break; } case CMYKQuantum: case CMYKAQuantum: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlack(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); } p+=GetPixelChannels(image); } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlack(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlack(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p+=GetPixelChannels(image); } break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); } p+=GetPixelChannels(image); } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p+=GetPixelChannels(image); } break; } } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case 'F': case 'f': { register unsigned char *pixels; (void) WriteBlobString(image,image->endian == LSBEndian ? "-1.0\n" : "1.0\n"); image->depth=32; quantum_type=format == 'f' ? GrayQuantum : RGBQuantum; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); pixels=GetQuantumPixels(quantum_info); for (y=(ssize_t) image->rows-1; y >= 0; y--) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); (void) WriteBlob(image,extent,pixels); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } } if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(MagickTrue); }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_936_0
crossvul-cpp_data_bad_2842_0
/* * Generic hugetlb support. * (C) Nadia Yvette Chambers, April 2004 */ #include <linux/list.h> #include <linux/init.h> #include <linux/mm.h> #include <linux/seq_file.h> #include <linux/sysctl.h> #include <linux/highmem.h> #include <linux/mmu_notifier.h> #include <linux/nodemask.h> #include <linux/pagemap.h> #include <linux/mempolicy.h> #include <linux/compiler.h> #include <linux/cpuset.h> #include <linux/mutex.h> #include <linux/bootmem.h> #include <linux/sysfs.h> #include <linux/slab.h> #include <linux/sched/signal.h> #include <linux/rmap.h> #include <linux/string_helpers.h> #include <linux/swap.h> #include <linux/swapops.h> #include <linux/jhash.h> #include <asm/page.h> #include <asm/pgtable.h> #include <asm/tlb.h> #include <linux/io.h> #include <linux/hugetlb.h> #include <linux/hugetlb_cgroup.h> #include <linux/node.h> #include <linux/userfaultfd_k.h> #include "internal.h" int hugepages_treat_as_movable; int hugetlb_max_hstate __read_mostly; unsigned int default_hstate_idx; struct hstate hstates[HUGE_MAX_HSTATE]; /* * Minimum page order among possible hugepage sizes, set to a proper value * at boot time. */ static unsigned int minimum_order __read_mostly = UINT_MAX; __initdata LIST_HEAD(huge_boot_pages); /* for command line parsing */ static struct hstate * __initdata parsed_hstate; static unsigned long __initdata default_hstate_max_huge_pages; static unsigned long __initdata default_hstate_size; static bool __initdata parsed_valid_hugepagesz = true; /* * Protects updates to hugepage_freelists, hugepage_activelist, nr_huge_pages, * free_huge_pages, and surplus_huge_pages. */ DEFINE_SPINLOCK(hugetlb_lock); /* * Serializes faults on the same logical page. This is used to * prevent spurious OOMs when the hugepage pool is fully utilized. */ static int num_fault_mutexes; struct mutex *hugetlb_fault_mutex_table ____cacheline_aligned_in_smp; /* Forward declaration */ static int hugetlb_acct_memory(struct hstate *h, long delta); static inline void unlock_or_release_subpool(struct hugepage_subpool *spool) { bool free = (spool->count == 0) && (spool->used_hpages == 0); spin_unlock(&spool->lock); /* If no pages are used, and no other handles to the subpool * remain, give up any reservations mased on minimum size and * free the subpool */ if (free) { if (spool->min_hpages != -1) hugetlb_acct_memory(spool->hstate, -spool->min_hpages); kfree(spool); } } struct hugepage_subpool *hugepage_new_subpool(struct hstate *h, long max_hpages, long min_hpages) { struct hugepage_subpool *spool; spool = kzalloc(sizeof(*spool), GFP_KERNEL); if (!spool) return NULL; spin_lock_init(&spool->lock); spool->count = 1; spool->max_hpages = max_hpages; spool->hstate = h; spool->min_hpages = min_hpages; if (min_hpages != -1 && hugetlb_acct_memory(h, min_hpages)) { kfree(spool); return NULL; } spool->rsv_hpages = min_hpages; return spool; } void hugepage_put_subpool(struct hugepage_subpool *spool) { spin_lock(&spool->lock); BUG_ON(!spool->count); spool->count--; unlock_or_release_subpool(spool); } /* * Subpool accounting for allocating and reserving pages. * Return -ENOMEM if there are not enough resources to satisfy the * the request. Otherwise, return the number of pages by which the * global pools must be adjusted (upward). The returned value may * only be different than the passed value (delta) in the case where * a subpool minimum size must be manitained. */ static long hugepage_subpool_get_pages(struct hugepage_subpool *spool, long delta) { long ret = delta; if (!spool) return ret; spin_lock(&spool->lock); if (spool->max_hpages != -1) { /* maximum size accounting */ if ((spool->used_hpages + delta) <= spool->max_hpages) spool->used_hpages += delta; else { ret = -ENOMEM; goto unlock_ret; } } /* minimum size accounting */ if (spool->min_hpages != -1 && spool->rsv_hpages) { if (delta > spool->rsv_hpages) { /* * Asking for more reserves than those already taken on * behalf of subpool. Return difference. */ ret = delta - spool->rsv_hpages; spool->rsv_hpages = 0; } else { ret = 0; /* reserves already accounted for */ spool->rsv_hpages -= delta; } } unlock_ret: spin_unlock(&spool->lock); return ret; } /* * Subpool accounting for freeing and unreserving pages. * Return the number of global page reservations that must be dropped. * The return value may only be different than the passed value (delta) * in the case where a subpool minimum size must be maintained. */ static long hugepage_subpool_put_pages(struct hugepage_subpool *spool, long delta) { long ret = delta; if (!spool) return delta; spin_lock(&spool->lock); if (spool->max_hpages != -1) /* maximum size accounting */ spool->used_hpages -= delta; /* minimum size accounting */ if (spool->min_hpages != -1 && spool->used_hpages < spool->min_hpages) { if (spool->rsv_hpages + delta <= spool->min_hpages) ret = 0; else ret = spool->rsv_hpages + delta - spool->min_hpages; spool->rsv_hpages += delta; if (spool->rsv_hpages > spool->min_hpages) spool->rsv_hpages = spool->min_hpages; } /* * If hugetlbfs_put_super couldn't free spool due to an outstanding * quota reference, free it now. */ unlock_or_release_subpool(spool); return ret; } static inline struct hugepage_subpool *subpool_inode(struct inode *inode) { return HUGETLBFS_SB(inode->i_sb)->spool; } static inline struct hugepage_subpool *subpool_vma(struct vm_area_struct *vma) { return subpool_inode(file_inode(vma->vm_file)); } /* * Region tracking -- allows tracking of reservations and instantiated pages * across the pages in a mapping. * * The region data structures are embedded into a resv_map and protected * by a resv_map's lock. The set of regions within the resv_map represent * reservations for huge pages, or huge pages that have already been * instantiated within the map. The from and to elements are huge page * indicies into the associated mapping. from indicates the starting index * of the region. to represents the first index past the end of the region. * * For example, a file region structure with from == 0 and to == 4 represents * four huge pages in a mapping. It is important to note that the to element * represents the first element past the end of the region. This is used in * arithmetic as 4(to) - 0(from) = 4 huge pages in the region. * * Interval notation of the form [from, to) will be used to indicate that * the endpoint from is inclusive and to is exclusive. */ struct file_region { struct list_head link; long from; long to; }; /* * Add the huge page range represented by [f, t) to the reserve * map. In the normal case, existing regions will be expanded * to accommodate the specified range. Sufficient regions should * exist for expansion due to the previous call to region_chg * with the same range. However, it is possible that region_del * could have been called after region_chg and modifed the map * in such a way that no region exists to be expanded. In this * case, pull a region descriptor from the cache associated with * the map and use that for the new range. * * Return the number of new huge pages added to the map. This * number is greater than or equal to zero. */ static long region_add(struct resv_map *resv, long f, long t) { struct list_head *head = &resv->regions; struct file_region *rg, *nrg, *trg; long add = 0; spin_lock(&resv->lock); /* Locate the region we are either in or before. */ list_for_each_entry(rg, head, link) if (f <= rg->to) break; /* * If no region exists which can be expanded to include the * specified range, the list must have been modified by an * interleving call to region_del(). Pull a region descriptor * from the cache and use it for this range. */ if (&rg->link == head || t < rg->from) { VM_BUG_ON(resv->region_cache_count <= 0); resv->region_cache_count--; nrg = list_first_entry(&resv->region_cache, struct file_region, link); list_del(&nrg->link); nrg->from = f; nrg->to = t; list_add(&nrg->link, rg->link.prev); add += t - f; goto out_locked; } /* Round our left edge to the current segment if it encloses us. */ if (f > rg->from) f = rg->from; /* Check for and consume any regions we now overlap with. */ nrg = rg; list_for_each_entry_safe(rg, trg, rg->link.prev, link) { if (&rg->link == head) break; if (rg->from > t) break; /* If this area reaches higher then extend our area to * include it completely. If this is not the first area * which we intend to reuse, free it. */ if (rg->to > t) t = rg->to; if (rg != nrg) { /* Decrement return value by the deleted range. * Another range will span this area so that by * end of routine add will be >= zero */ add -= (rg->to - rg->from); list_del(&rg->link); kfree(rg); } } add += (nrg->from - f); /* Added to beginning of region */ nrg->from = f; add += t - nrg->to; /* Added to end of region */ nrg->to = t; out_locked: resv->adds_in_progress--; spin_unlock(&resv->lock); VM_BUG_ON(add < 0); return add; } /* * Examine the existing reserve map and determine how many * huge pages in the specified range [f, t) are NOT currently * represented. This routine is called before a subsequent * call to region_add that will actually modify the reserve * map to add the specified range [f, t). region_chg does * not change the number of huge pages represented by the * map. However, if the existing regions in the map can not * be expanded to represent the new range, a new file_region * structure is added to the map as a placeholder. This is * so that the subsequent region_add call will have all the * regions it needs and will not fail. * * Upon entry, region_chg will also examine the cache of region descriptors * associated with the map. If there are not enough descriptors cached, one * will be allocated for the in progress add operation. * * Returns the number of huge pages that need to be added to the existing * reservation map for the range [f, t). This number is greater or equal to * zero. -ENOMEM is returned if a new file_region structure or cache entry * is needed and can not be allocated. */ static long region_chg(struct resv_map *resv, long f, long t) { struct list_head *head = &resv->regions; struct file_region *rg, *nrg = NULL; long chg = 0; retry: spin_lock(&resv->lock); retry_locked: resv->adds_in_progress++; /* * Check for sufficient descriptors in the cache to accommodate * the number of in progress add operations. */ if (resv->adds_in_progress > resv->region_cache_count) { struct file_region *trg; VM_BUG_ON(resv->adds_in_progress - resv->region_cache_count > 1); /* Must drop lock to allocate a new descriptor. */ resv->adds_in_progress--; spin_unlock(&resv->lock); trg = kmalloc(sizeof(*trg), GFP_KERNEL); if (!trg) { kfree(nrg); return -ENOMEM; } spin_lock(&resv->lock); list_add(&trg->link, &resv->region_cache); resv->region_cache_count++; goto retry_locked; } /* Locate the region we are before or in. */ list_for_each_entry(rg, head, link) if (f <= rg->to) break; /* If we are below the current region then a new region is required. * Subtle, allocate a new region at the position but make it zero * size such that we can guarantee to record the reservation. */ if (&rg->link == head || t < rg->from) { if (!nrg) { resv->adds_in_progress--; spin_unlock(&resv->lock); nrg = kmalloc(sizeof(*nrg), GFP_KERNEL); if (!nrg) return -ENOMEM; nrg->from = f; nrg->to = f; INIT_LIST_HEAD(&nrg->link); goto retry; } list_add(&nrg->link, rg->link.prev); chg = t - f; goto out_nrg; } /* Round our left edge to the current segment if it encloses us. */ if (f > rg->from) f = rg->from; chg = t - f; /* Check for and consume any regions we now overlap with. */ list_for_each_entry(rg, rg->link.prev, link) { if (&rg->link == head) break; if (rg->from > t) goto out; /* We overlap with this area, if it extends further than * us then we must extend ourselves. Account for its * existing reservation. */ if (rg->to > t) { chg += rg->to - t; t = rg->to; } chg -= rg->to - rg->from; } out: spin_unlock(&resv->lock); /* We already know we raced and no longer need the new region */ kfree(nrg); return chg; out_nrg: spin_unlock(&resv->lock); return chg; } /* * Abort the in progress add operation. The adds_in_progress field * of the resv_map keeps track of the operations in progress between * calls to region_chg and region_add. Operations are sometimes * aborted after the call to region_chg. In such cases, region_abort * is called to decrement the adds_in_progress counter. * * NOTE: The range arguments [f, t) are not needed or used in this * routine. They are kept to make reading the calling code easier as * arguments will match the associated region_chg call. */ static void region_abort(struct resv_map *resv, long f, long t) { spin_lock(&resv->lock); VM_BUG_ON(!resv->region_cache_count); resv->adds_in_progress--; spin_unlock(&resv->lock); } /* * Delete the specified range [f, t) from the reserve map. If the * t parameter is LONG_MAX, this indicates that ALL regions after f * should be deleted. Locate the regions which intersect [f, t) * and either trim, delete or split the existing regions. * * Returns the number of huge pages deleted from the reserve map. * In the normal case, the return value is zero or more. In the * case where a region must be split, a new region descriptor must * be allocated. If the allocation fails, -ENOMEM will be returned. * NOTE: If the parameter t == LONG_MAX, then we will never split * a region and possibly return -ENOMEM. Callers specifying * t == LONG_MAX do not need to check for -ENOMEM error. */ static long region_del(struct resv_map *resv, long f, long t) { struct list_head *head = &resv->regions; struct file_region *rg, *trg; struct file_region *nrg = NULL; long del = 0; retry: spin_lock(&resv->lock); list_for_each_entry_safe(rg, trg, head, link) { /* * Skip regions before the range to be deleted. file_region * ranges are normally of the form [from, to). However, there * may be a "placeholder" entry in the map which is of the form * (from, to) with from == to. Check for placeholder entries * at the beginning of the range to be deleted. */ if (rg->to <= f && (rg->to != rg->from || rg->to != f)) continue; if (rg->from >= t) break; if (f > rg->from && t < rg->to) { /* Must split region */ /* * Check for an entry in the cache before dropping * lock and attempting allocation. */ if (!nrg && resv->region_cache_count > resv->adds_in_progress) { nrg = list_first_entry(&resv->region_cache, struct file_region, link); list_del(&nrg->link); resv->region_cache_count--; } if (!nrg) { spin_unlock(&resv->lock); nrg = kmalloc(sizeof(*nrg), GFP_KERNEL); if (!nrg) return -ENOMEM; goto retry; } del += t - f; /* New entry for end of split region */ nrg->from = t; nrg->to = rg->to; INIT_LIST_HEAD(&nrg->link); /* Original entry is trimmed */ rg->to = f; list_add(&nrg->link, &rg->link); nrg = NULL; break; } if (f <= rg->from && t >= rg->to) { /* Remove entire region */ del += rg->to - rg->from; list_del(&rg->link); kfree(rg); continue; } if (f <= rg->from) { /* Trim beginning of region */ del += t - rg->from; rg->from = t; } else { /* Trim end of region */ del += rg->to - f; rg->to = f; } } spin_unlock(&resv->lock); kfree(nrg); return del; } /* * A rare out of memory error was encountered which prevented removal of * the reserve map region for a page. The huge page itself was free'ed * and removed from the page cache. This routine will adjust the subpool * usage count, and the global reserve count if needed. By incrementing * these counts, the reserve map entry which could not be deleted will * appear as a "reserved" entry instead of simply dangling with incorrect * counts. */ void hugetlb_fix_reserve_counts(struct inode *inode) { struct hugepage_subpool *spool = subpool_inode(inode); long rsv_adjust; rsv_adjust = hugepage_subpool_get_pages(spool, 1); if (rsv_adjust) { struct hstate *h = hstate_inode(inode); hugetlb_acct_memory(h, 1); } } /* * Count and return the number of huge pages in the reserve map * that intersect with the range [f, t). */ static long region_count(struct resv_map *resv, long f, long t) { struct list_head *head = &resv->regions; struct file_region *rg; long chg = 0; spin_lock(&resv->lock); /* Locate each segment we overlap with, and count that overlap. */ list_for_each_entry(rg, head, link) { long seg_from; long seg_to; if (rg->to <= f) continue; if (rg->from >= t) break; seg_from = max(rg->from, f); seg_to = min(rg->to, t); chg += seg_to - seg_from; } spin_unlock(&resv->lock); return chg; } /* * Convert the address within this vma to the page offset within * the mapping, in pagecache page units; huge pages here. */ static pgoff_t vma_hugecache_offset(struct hstate *h, struct vm_area_struct *vma, unsigned long address) { return ((address - vma->vm_start) >> huge_page_shift(h)) + (vma->vm_pgoff >> huge_page_order(h)); } pgoff_t linear_hugepage_index(struct vm_area_struct *vma, unsigned long address) { return vma_hugecache_offset(hstate_vma(vma), vma, address); } EXPORT_SYMBOL_GPL(linear_hugepage_index); /* * Return the size of the pages allocated when backing a VMA. In the majority * cases this will be same size as used by the page table entries. */ unsigned long vma_kernel_pagesize(struct vm_area_struct *vma) { struct hstate *hstate; if (!is_vm_hugetlb_page(vma)) return PAGE_SIZE; hstate = hstate_vma(vma); return 1UL << huge_page_shift(hstate); } EXPORT_SYMBOL_GPL(vma_kernel_pagesize); /* * Return the page size being used by the MMU to back a VMA. In the majority * of cases, the page size used by the kernel matches the MMU size. On * architectures where it differs, an architecture-specific version of this * function is required. */ #ifndef vma_mmu_pagesize unsigned long vma_mmu_pagesize(struct vm_area_struct *vma) { return vma_kernel_pagesize(vma); } #endif /* * Flags for MAP_PRIVATE reservations. These are stored in the bottom * bits of the reservation map pointer, which are always clear due to * alignment. */ #define HPAGE_RESV_OWNER (1UL << 0) #define HPAGE_RESV_UNMAPPED (1UL << 1) #define HPAGE_RESV_MASK (HPAGE_RESV_OWNER | HPAGE_RESV_UNMAPPED) /* * These helpers are used to track how many pages are reserved for * faults in a MAP_PRIVATE mapping. Only the process that called mmap() * is guaranteed to have their future faults succeed. * * With the exception of reset_vma_resv_huge_pages() which is called at fork(), * the reserve counters are updated with the hugetlb_lock held. It is safe * to reset the VMA at fork() time as it is not in use yet and there is no * chance of the global counters getting corrupted as a result of the values. * * The private mapping reservation is represented in a subtly different * manner to a shared mapping. A shared mapping has a region map associated * with the underlying file, this region map represents the backing file * pages which have ever had a reservation assigned which this persists even * after the page is instantiated. A private mapping has a region map * associated with the original mmap which is attached to all VMAs which * reference it, this region map represents those offsets which have consumed * reservation ie. where pages have been instantiated. */ static unsigned long get_vma_private_data(struct vm_area_struct *vma) { return (unsigned long)vma->vm_private_data; } static void set_vma_private_data(struct vm_area_struct *vma, unsigned long value) { vma->vm_private_data = (void *)value; } struct resv_map *resv_map_alloc(void) { struct resv_map *resv_map = kmalloc(sizeof(*resv_map), GFP_KERNEL); struct file_region *rg = kmalloc(sizeof(*rg), GFP_KERNEL); if (!resv_map || !rg) { kfree(resv_map); kfree(rg); return NULL; } kref_init(&resv_map->refs); spin_lock_init(&resv_map->lock); INIT_LIST_HEAD(&resv_map->regions); resv_map->adds_in_progress = 0; INIT_LIST_HEAD(&resv_map->region_cache); list_add(&rg->link, &resv_map->region_cache); resv_map->region_cache_count = 1; return resv_map; } void resv_map_release(struct kref *ref) { struct resv_map *resv_map = container_of(ref, struct resv_map, refs); struct list_head *head = &resv_map->region_cache; struct file_region *rg, *trg; /* Clear out any active regions before we release the map. */ region_del(resv_map, 0, LONG_MAX); /* ... and any entries left in the cache */ list_for_each_entry_safe(rg, trg, head, link) { list_del(&rg->link); kfree(rg); } VM_BUG_ON(resv_map->adds_in_progress); kfree(resv_map); } static inline struct resv_map *inode_resv_map(struct inode *inode) { return inode->i_mapping->private_data; } static struct resv_map *vma_resv_map(struct vm_area_struct *vma) { VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma); if (vma->vm_flags & VM_MAYSHARE) { struct address_space *mapping = vma->vm_file->f_mapping; struct inode *inode = mapping->host; return inode_resv_map(inode); } else { return (struct resv_map *)(get_vma_private_data(vma) & ~HPAGE_RESV_MASK); } } static void set_vma_resv_map(struct vm_area_struct *vma, struct resv_map *map) { VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma); VM_BUG_ON_VMA(vma->vm_flags & VM_MAYSHARE, vma); set_vma_private_data(vma, (get_vma_private_data(vma) & HPAGE_RESV_MASK) | (unsigned long)map); } static void set_vma_resv_flags(struct vm_area_struct *vma, unsigned long flags) { VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma); VM_BUG_ON_VMA(vma->vm_flags & VM_MAYSHARE, vma); set_vma_private_data(vma, get_vma_private_data(vma) | flags); } static int is_vma_resv_set(struct vm_area_struct *vma, unsigned long flag) { VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma); return (get_vma_private_data(vma) & flag) != 0; } /* Reset counters to 0 and clear all HPAGE_RESV_* flags */ void reset_vma_resv_huge_pages(struct vm_area_struct *vma) { VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma); if (!(vma->vm_flags & VM_MAYSHARE)) vma->vm_private_data = (void *)0; } /* Returns true if the VMA has associated reserve pages */ static bool vma_has_reserves(struct vm_area_struct *vma, long chg) { if (vma->vm_flags & VM_NORESERVE) { /* * This address is already reserved by other process(chg == 0), * so, we should decrement reserved count. Without decrementing, * reserve count remains after releasing inode, because this * allocated page will go into page cache and is regarded as * coming from reserved pool in releasing step. Currently, we * don't have any other solution to deal with this situation * properly, so add work-around here. */ if (vma->vm_flags & VM_MAYSHARE && chg == 0) return true; else return false; } /* Shared mappings always use reserves */ if (vma->vm_flags & VM_MAYSHARE) { /* * We know VM_NORESERVE is not set. Therefore, there SHOULD * be a region map for all pages. The only situation where * there is no region map is if a hole was punched via * fallocate. In this case, there really are no reverves to * use. This situation is indicated if chg != 0. */ if (chg) return false; else return true; } /* * Only the process that called mmap() has reserves for * private mappings. */ if (is_vma_resv_set(vma, HPAGE_RESV_OWNER)) { /* * Like the shared case above, a hole punch or truncate * could have been performed on the private mapping. * Examine the value of chg to determine if reserves * actually exist or were previously consumed. * Very Subtle - The value of chg comes from a previous * call to vma_needs_reserves(). The reserve map for * private mappings has different (opposite) semantics * than that of shared mappings. vma_needs_reserves() * has already taken this difference in semantics into * account. Therefore, the meaning of chg is the same * as in the shared case above. Code could easily be * combined, but keeping it separate draws attention to * subtle differences. */ if (chg) return false; else return true; } return false; } static void enqueue_huge_page(struct hstate *h, struct page *page) { int nid = page_to_nid(page); list_move(&page->lru, &h->hugepage_freelists[nid]); h->free_huge_pages++; h->free_huge_pages_node[nid]++; } static struct page *dequeue_huge_page_node_exact(struct hstate *h, int nid) { struct page *page; list_for_each_entry(page, &h->hugepage_freelists[nid], lru) if (!PageHWPoison(page)) break; /* * if 'non-isolated free hugepage' not found on the list, * the allocation fails. */ if (&h->hugepage_freelists[nid] == &page->lru) return NULL; list_move(&page->lru, &h->hugepage_activelist); set_page_refcounted(page); h->free_huge_pages--; h->free_huge_pages_node[nid]--; return page; } static struct page *dequeue_huge_page_nodemask(struct hstate *h, gfp_t gfp_mask, int nid, nodemask_t *nmask) { unsigned int cpuset_mems_cookie; struct zonelist *zonelist; struct zone *zone; struct zoneref *z; int node = -1; zonelist = node_zonelist(nid, gfp_mask); retry_cpuset: cpuset_mems_cookie = read_mems_allowed_begin(); for_each_zone_zonelist_nodemask(zone, z, zonelist, gfp_zone(gfp_mask), nmask) { struct page *page; if (!cpuset_zone_allowed(zone, gfp_mask)) continue; /* * no need to ask again on the same node. Pool is node rather than * zone aware */ if (zone_to_nid(zone) == node) continue; node = zone_to_nid(zone); page = dequeue_huge_page_node_exact(h, node); if (page) return page; } if (unlikely(read_mems_allowed_retry(cpuset_mems_cookie))) goto retry_cpuset; return NULL; } /* Movability of hugepages depends on migration support. */ static inline gfp_t htlb_alloc_mask(struct hstate *h) { if (hugepages_treat_as_movable || hugepage_migration_supported(h)) return GFP_HIGHUSER_MOVABLE; else return GFP_HIGHUSER; } static struct page *dequeue_huge_page_vma(struct hstate *h, struct vm_area_struct *vma, unsigned long address, int avoid_reserve, long chg) { struct page *page; struct mempolicy *mpol; gfp_t gfp_mask; nodemask_t *nodemask; int nid; /* * A child process with MAP_PRIVATE mappings created by their parent * have no page reserves. This check ensures that reservations are * not "stolen". The child may still get SIGKILLed */ if (!vma_has_reserves(vma, chg) && h->free_huge_pages - h->resv_huge_pages == 0) goto err; /* If reserves cannot be used, ensure enough pages are in the pool */ if (avoid_reserve && h->free_huge_pages - h->resv_huge_pages == 0) goto err; gfp_mask = htlb_alloc_mask(h); nid = huge_node(vma, address, gfp_mask, &mpol, &nodemask); page = dequeue_huge_page_nodemask(h, gfp_mask, nid, nodemask); if (page && !avoid_reserve && vma_has_reserves(vma, chg)) { SetPagePrivate(page); h->resv_huge_pages--; } mpol_cond_put(mpol); return page; err: return NULL; } /* * common helper functions for hstate_next_node_to_{alloc|free}. * We may have allocated or freed a huge page based on a different * nodes_allowed previously, so h->next_node_to_{alloc|free} might * be outside of *nodes_allowed. Ensure that we use an allowed * node for alloc or free. */ static int next_node_allowed(int nid, nodemask_t *nodes_allowed) { nid = next_node_in(nid, *nodes_allowed); VM_BUG_ON(nid >= MAX_NUMNODES); return nid; } static int get_valid_node_allowed(int nid, nodemask_t *nodes_allowed) { if (!node_isset(nid, *nodes_allowed)) nid = next_node_allowed(nid, nodes_allowed); return nid; } /* * returns the previously saved node ["this node"] from which to * allocate a persistent huge page for the pool and advance the * next node from which to allocate, handling wrap at end of node * mask. */ static int hstate_next_node_to_alloc(struct hstate *h, nodemask_t *nodes_allowed) { int nid; VM_BUG_ON(!nodes_allowed); nid = get_valid_node_allowed(h->next_nid_to_alloc, nodes_allowed); h->next_nid_to_alloc = next_node_allowed(nid, nodes_allowed); return nid; } /* * helper for free_pool_huge_page() - return the previously saved * node ["this node"] from which to free a huge page. Advance the * next node id whether or not we find a free huge page to free so * that the next attempt to free addresses the next node. */ static int hstate_next_node_to_free(struct hstate *h, nodemask_t *nodes_allowed) { int nid; VM_BUG_ON(!nodes_allowed); nid = get_valid_node_allowed(h->next_nid_to_free, nodes_allowed); h->next_nid_to_free = next_node_allowed(nid, nodes_allowed); return nid; } #define for_each_node_mask_to_alloc(hs, nr_nodes, node, mask) \ for (nr_nodes = nodes_weight(*mask); \ nr_nodes > 0 && \ ((node = hstate_next_node_to_alloc(hs, mask)) || 1); \ nr_nodes--) #define for_each_node_mask_to_free(hs, nr_nodes, node, mask) \ for (nr_nodes = nodes_weight(*mask); \ nr_nodes > 0 && \ ((node = hstate_next_node_to_free(hs, mask)) || 1); \ nr_nodes--) #ifdef CONFIG_ARCH_HAS_GIGANTIC_PAGE static void destroy_compound_gigantic_page(struct page *page, unsigned int order) { int i; int nr_pages = 1 << order; struct page *p = page + 1; atomic_set(compound_mapcount_ptr(page), 0); for (i = 1; i < nr_pages; i++, p = mem_map_next(p, page, i)) { clear_compound_head(p); set_page_refcounted(p); } set_compound_order(page, 0); __ClearPageHead(page); } static void free_gigantic_page(struct page *page, unsigned int order) { free_contig_range(page_to_pfn(page), 1 << order); } static int __alloc_gigantic_page(unsigned long start_pfn, unsigned long nr_pages, gfp_t gfp_mask) { unsigned long end_pfn = start_pfn + nr_pages; return alloc_contig_range(start_pfn, end_pfn, MIGRATE_MOVABLE, gfp_mask); } static bool pfn_range_valid_gigantic(struct zone *z, unsigned long start_pfn, unsigned long nr_pages) { unsigned long i, end_pfn = start_pfn + nr_pages; struct page *page; for (i = start_pfn; i < end_pfn; i++) { if (!pfn_valid(i)) return false; page = pfn_to_page(i); if (page_zone(page) != z) return false; if (PageReserved(page)) return false; if (page_count(page) > 0) return false; if (PageHuge(page)) return false; } return true; } static bool zone_spans_last_pfn(const struct zone *zone, unsigned long start_pfn, unsigned long nr_pages) { unsigned long last_pfn = start_pfn + nr_pages - 1; return zone_spans_pfn(zone, last_pfn); } static struct page *alloc_gigantic_page(int nid, struct hstate *h) { unsigned int order = huge_page_order(h); unsigned long nr_pages = 1 << order; unsigned long ret, pfn, flags; struct zonelist *zonelist; struct zone *zone; struct zoneref *z; gfp_t gfp_mask; gfp_mask = htlb_alloc_mask(h) | __GFP_THISNODE; zonelist = node_zonelist(nid, gfp_mask); for_each_zone_zonelist_nodemask(zone, z, zonelist, gfp_zone(gfp_mask), NULL) { spin_lock_irqsave(&zone->lock, flags); pfn = ALIGN(zone->zone_start_pfn, nr_pages); while (zone_spans_last_pfn(zone, pfn, nr_pages)) { if (pfn_range_valid_gigantic(zone, pfn, nr_pages)) { /* * We release the zone lock here because * alloc_contig_range() will also lock the zone * at some point. If there's an allocation * spinning on this lock, it may win the race * and cause alloc_contig_range() to fail... */ spin_unlock_irqrestore(&zone->lock, flags); ret = __alloc_gigantic_page(pfn, nr_pages, gfp_mask); if (!ret) return pfn_to_page(pfn); spin_lock_irqsave(&zone->lock, flags); } pfn += nr_pages; } spin_unlock_irqrestore(&zone->lock, flags); } return NULL; } static void prep_new_huge_page(struct hstate *h, struct page *page, int nid); static void prep_compound_gigantic_page(struct page *page, unsigned int order); static struct page *alloc_fresh_gigantic_page_node(struct hstate *h, int nid) { struct page *page; page = alloc_gigantic_page(nid, h); if (page) { prep_compound_gigantic_page(page, huge_page_order(h)); prep_new_huge_page(h, page, nid); } return page; } static int alloc_fresh_gigantic_page(struct hstate *h, nodemask_t *nodes_allowed) { struct page *page = NULL; int nr_nodes, node; for_each_node_mask_to_alloc(h, nr_nodes, node, nodes_allowed) { page = alloc_fresh_gigantic_page_node(h, node); if (page) return 1; } return 0; } #else /* !CONFIG_ARCH_HAS_GIGANTIC_PAGE */ static inline bool gigantic_page_supported(void) { return false; } static inline void free_gigantic_page(struct page *page, unsigned int order) { } static inline void destroy_compound_gigantic_page(struct page *page, unsigned int order) { } static inline int alloc_fresh_gigantic_page(struct hstate *h, nodemask_t *nodes_allowed) { return 0; } #endif static void update_and_free_page(struct hstate *h, struct page *page) { int i; if (hstate_is_gigantic(h) && !gigantic_page_supported()) return; h->nr_huge_pages--; h->nr_huge_pages_node[page_to_nid(page)]--; for (i = 0; i < pages_per_huge_page(h); i++) { page[i].flags &= ~(1 << PG_locked | 1 << PG_error | 1 << PG_referenced | 1 << PG_dirty | 1 << PG_active | 1 << PG_private | 1 << PG_writeback); } VM_BUG_ON_PAGE(hugetlb_cgroup_from_page(page), page); set_compound_page_dtor(page, NULL_COMPOUND_DTOR); set_page_refcounted(page); if (hstate_is_gigantic(h)) { destroy_compound_gigantic_page(page, huge_page_order(h)); free_gigantic_page(page, huge_page_order(h)); } else { __free_pages(page, huge_page_order(h)); } } struct hstate *size_to_hstate(unsigned long size) { struct hstate *h; for_each_hstate(h) { if (huge_page_size(h) == size) return h; } return NULL; } /* * Test to determine whether the hugepage is "active/in-use" (i.e. being linked * to hstate->hugepage_activelist.) * * This function can be called for tail pages, but never returns true for them. */ bool page_huge_active(struct page *page) { VM_BUG_ON_PAGE(!PageHuge(page), page); return PageHead(page) && PagePrivate(&page[1]); } /* never called for tail page */ static void set_page_huge_active(struct page *page) { VM_BUG_ON_PAGE(!PageHeadHuge(page), page); SetPagePrivate(&page[1]); } static void clear_page_huge_active(struct page *page) { VM_BUG_ON_PAGE(!PageHeadHuge(page), page); ClearPagePrivate(&page[1]); } void free_huge_page(struct page *page) { /* * Can't pass hstate in here because it is called from the * compound page destructor. */ struct hstate *h = page_hstate(page); int nid = page_to_nid(page); struct hugepage_subpool *spool = (struct hugepage_subpool *)page_private(page); bool restore_reserve; set_page_private(page, 0); page->mapping = NULL; VM_BUG_ON_PAGE(page_count(page), page); VM_BUG_ON_PAGE(page_mapcount(page), page); restore_reserve = PagePrivate(page); ClearPagePrivate(page); /* * A return code of zero implies that the subpool will be under its * minimum size if the reservation is not restored after page is free. * Therefore, force restore_reserve operation. */ if (hugepage_subpool_put_pages(spool, 1) == 0) restore_reserve = true; spin_lock(&hugetlb_lock); clear_page_huge_active(page); hugetlb_cgroup_uncharge_page(hstate_index(h), pages_per_huge_page(h), page); if (restore_reserve) h->resv_huge_pages++; if (h->surplus_huge_pages_node[nid]) { /* remove the page from active list */ list_del(&page->lru); update_and_free_page(h, page); h->surplus_huge_pages--; h->surplus_huge_pages_node[nid]--; } else { arch_clear_hugepage_flags(page); enqueue_huge_page(h, page); } spin_unlock(&hugetlb_lock); } static void prep_new_huge_page(struct hstate *h, struct page *page, int nid) { INIT_LIST_HEAD(&page->lru); set_compound_page_dtor(page, HUGETLB_PAGE_DTOR); spin_lock(&hugetlb_lock); set_hugetlb_cgroup(page, NULL); h->nr_huge_pages++; h->nr_huge_pages_node[nid]++; spin_unlock(&hugetlb_lock); put_page(page); /* free it into the hugepage allocator */ } static void prep_compound_gigantic_page(struct page *page, unsigned int order) { int i; int nr_pages = 1 << order; struct page *p = page + 1; /* we rely on prep_new_huge_page to set the destructor */ set_compound_order(page, order); __ClearPageReserved(page); __SetPageHead(page); for (i = 1; i < nr_pages; i++, p = mem_map_next(p, page, i)) { /* * For gigantic hugepages allocated through bootmem at * boot, it's safer to be consistent with the not-gigantic * hugepages and clear the PG_reserved bit from all tail pages * too. Otherwse drivers using get_user_pages() to access tail * pages may get the reference counting wrong if they see * PG_reserved set on a tail page (despite the head page not * having PG_reserved set). Enforcing this consistency between * head and tail pages allows drivers to optimize away a check * on the head page when they need know if put_page() is needed * after get_user_pages(). */ __ClearPageReserved(p); set_page_count(p, 0); set_compound_head(p, page); } atomic_set(compound_mapcount_ptr(page), -1); } /* * PageHuge() only returns true for hugetlbfs pages, but not for normal or * transparent huge pages. See the PageTransHuge() documentation for more * details. */ int PageHuge(struct page *page) { if (!PageCompound(page)) return 0; page = compound_head(page); return page[1].compound_dtor == HUGETLB_PAGE_DTOR; } EXPORT_SYMBOL_GPL(PageHuge); /* * PageHeadHuge() only returns true for hugetlbfs head page, but not for * normal or transparent huge pages. */ int PageHeadHuge(struct page *page_head) { if (!PageHead(page_head)) return 0; return get_compound_page_dtor(page_head) == free_huge_page; } pgoff_t __basepage_index(struct page *page) { struct page *page_head = compound_head(page); pgoff_t index = page_index(page_head); unsigned long compound_idx; if (!PageHuge(page_head)) return page_index(page); if (compound_order(page_head) >= MAX_ORDER) compound_idx = page_to_pfn(page) - page_to_pfn(page_head); else compound_idx = page - page_head; return (index << compound_order(page_head)) + compound_idx; } static struct page *alloc_fresh_huge_page_node(struct hstate *h, int nid) { struct page *page; page = __alloc_pages_node(nid, htlb_alloc_mask(h)|__GFP_COMP|__GFP_THISNODE| __GFP_RETRY_MAYFAIL|__GFP_NOWARN, huge_page_order(h)); if (page) { prep_new_huge_page(h, page, nid); } return page; } static int alloc_fresh_huge_page(struct hstate *h, nodemask_t *nodes_allowed) { struct page *page; int nr_nodes, node; int ret = 0; for_each_node_mask_to_alloc(h, nr_nodes, node, nodes_allowed) { page = alloc_fresh_huge_page_node(h, node); if (page) { ret = 1; break; } } if (ret) count_vm_event(HTLB_BUDDY_PGALLOC); else count_vm_event(HTLB_BUDDY_PGALLOC_FAIL); return ret; } /* * Free huge page from pool from next node to free. * Attempt to keep persistent huge pages more or less * balanced over allowed nodes. * Called with hugetlb_lock locked. */ static int free_pool_huge_page(struct hstate *h, nodemask_t *nodes_allowed, bool acct_surplus) { int nr_nodes, node; int ret = 0; for_each_node_mask_to_free(h, nr_nodes, node, nodes_allowed) { /* * If we're returning unused surplus pages, only examine * nodes with surplus pages. */ if ((!acct_surplus || h->surplus_huge_pages_node[node]) && !list_empty(&h->hugepage_freelists[node])) { struct page *page = list_entry(h->hugepage_freelists[node].next, struct page, lru); list_del(&page->lru); h->free_huge_pages--; h->free_huge_pages_node[node]--; if (acct_surplus) { h->surplus_huge_pages--; h->surplus_huge_pages_node[node]--; } update_and_free_page(h, page); ret = 1; break; } } return ret; } /* * Dissolve a given free hugepage into free buddy pages. This function does * nothing for in-use (including surplus) hugepages. Returns -EBUSY if the * number of free hugepages would be reduced below the number of reserved * hugepages. */ int dissolve_free_huge_page(struct page *page) { int rc = 0; spin_lock(&hugetlb_lock); if (PageHuge(page) && !page_count(page)) { struct page *head = compound_head(page); struct hstate *h = page_hstate(head); int nid = page_to_nid(head); if (h->free_huge_pages - h->resv_huge_pages == 0) { rc = -EBUSY; goto out; } /* * Move PageHWPoison flag from head page to the raw error page, * which makes any subpages rather than the error page reusable. */ if (PageHWPoison(head) && page != head) { SetPageHWPoison(page); ClearPageHWPoison(head); } list_del(&head->lru); h->free_huge_pages--; h->free_huge_pages_node[nid]--; h->max_huge_pages--; update_and_free_page(h, head); } out: spin_unlock(&hugetlb_lock); return rc; } /* * Dissolve free hugepages in a given pfn range. Used by memory hotplug to * make specified memory blocks removable from the system. * Note that this will dissolve a free gigantic hugepage completely, if any * part of it lies within the given range. * Also note that if dissolve_free_huge_page() returns with an error, all * free hugepages that were dissolved before that error are lost. */ int dissolve_free_huge_pages(unsigned long start_pfn, unsigned long end_pfn) { unsigned long pfn; struct page *page; int rc = 0; if (!hugepages_supported()) return rc; for (pfn = start_pfn; pfn < end_pfn; pfn += 1 << minimum_order) { page = pfn_to_page(pfn); if (PageHuge(page) && !page_count(page)) { rc = dissolve_free_huge_page(page); if (rc) break; } } return rc; } static struct page *__hugetlb_alloc_buddy_huge_page(struct hstate *h, gfp_t gfp_mask, int nid, nodemask_t *nmask) { int order = huge_page_order(h); gfp_mask |= __GFP_COMP|__GFP_RETRY_MAYFAIL|__GFP_NOWARN; if (nid == NUMA_NO_NODE) nid = numa_mem_id(); return __alloc_pages_nodemask(gfp_mask, order, nid, nmask); } static struct page *__alloc_buddy_huge_page(struct hstate *h, gfp_t gfp_mask, int nid, nodemask_t *nmask) { struct page *page; unsigned int r_nid; if (hstate_is_gigantic(h)) return NULL; /* * Assume we will successfully allocate the surplus page to * prevent racing processes from causing the surplus to exceed * overcommit * * This however introduces a different race, where a process B * tries to grow the static hugepage pool while alloc_pages() is * called by process A. B will only examine the per-node * counters in determining if surplus huge pages can be * converted to normal huge pages in adjust_pool_surplus(). A * won't be able to increment the per-node counter, until the * lock is dropped by B, but B doesn't drop hugetlb_lock until * no more huge pages can be converted from surplus to normal * state (and doesn't try to convert again). Thus, we have a * case where a surplus huge page exists, the pool is grown, and * the surplus huge page still exists after, even though it * should just have been converted to a normal huge page. This * does not leak memory, though, as the hugepage will be freed * once it is out of use. It also does not allow the counters to * go out of whack in adjust_pool_surplus() as we don't modify * the node values until we've gotten the hugepage and only the * per-node value is checked there. */ spin_lock(&hugetlb_lock); if (h->surplus_huge_pages >= h->nr_overcommit_huge_pages) { spin_unlock(&hugetlb_lock); return NULL; } else { h->nr_huge_pages++; h->surplus_huge_pages++; } spin_unlock(&hugetlb_lock); page = __hugetlb_alloc_buddy_huge_page(h, gfp_mask, nid, nmask); spin_lock(&hugetlb_lock); if (page) { INIT_LIST_HEAD(&page->lru); r_nid = page_to_nid(page); set_compound_page_dtor(page, HUGETLB_PAGE_DTOR); set_hugetlb_cgroup(page, NULL); /* * We incremented the global counters already */ h->nr_huge_pages_node[r_nid]++; h->surplus_huge_pages_node[r_nid]++; __count_vm_event(HTLB_BUDDY_PGALLOC); } else { h->nr_huge_pages--; h->surplus_huge_pages--; __count_vm_event(HTLB_BUDDY_PGALLOC_FAIL); } spin_unlock(&hugetlb_lock); return page; } /* * Use the VMA's mpolicy to allocate a huge page from the buddy. */ static struct page *__alloc_buddy_huge_page_with_mpol(struct hstate *h, struct vm_area_struct *vma, unsigned long addr) { struct page *page; struct mempolicy *mpol; gfp_t gfp_mask = htlb_alloc_mask(h); int nid; nodemask_t *nodemask; nid = huge_node(vma, addr, gfp_mask, &mpol, &nodemask); page = __alloc_buddy_huge_page(h, gfp_mask, nid, nodemask); mpol_cond_put(mpol); return page; } /* * This allocation function is useful in the context where vma is irrelevant. * E.g. soft-offlining uses this function because it only cares physical * address of error page. */ struct page *alloc_huge_page_node(struct hstate *h, int nid) { gfp_t gfp_mask = htlb_alloc_mask(h); struct page *page = NULL; if (nid != NUMA_NO_NODE) gfp_mask |= __GFP_THISNODE; spin_lock(&hugetlb_lock); if (h->free_huge_pages - h->resv_huge_pages > 0) page = dequeue_huge_page_nodemask(h, gfp_mask, nid, NULL); spin_unlock(&hugetlb_lock); if (!page) page = __alloc_buddy_huge_page(h, gfp_mask, nid, NULL); return page; } struct page *alloc_huge_page_nodemask(struct hstate *h, int preferred_nid, nodemask_t *nmask) { gfp_t gfp_mask = htlb_alloc_mask(h); spin_lock(&hugetlb_lock); if (h->free_huge_pages - h->resv_huge_pages > 0) { struct page *page; page = dequeue_huge_page_nodemask(h, gfp_mask, preferred_nid, nmask); if (page) { spin_unlock(&hugetlb_lock); return page; } } spin_unlock(&hugetlb_lock); /* No reservations, try to overcommit */ return __alloc_buddy_huge_page(h, gfp_mask, preferred_nid, nmask); } /* * Increase the hugetlb pool such that it can accommodate a reservation * of size 'delta'. */ static int gather_surplus_pages(struct hstate *h, int delta) { struct list_head surplus_list; struct page *page, *tmp; int ret, i; int needed, allocated; bool alloc_ok = true; needed = (h->resv_huge_pages + delta) - h->free_huge_pages; if (needed <= 0) { h->resv_huge_pages += delta; return 0; } allocated = 0; INIT_LIST_HEAD(&surplus_list); ret = -ENOMEM; retry: spin_unlock(&hugetlb_lock); for (i = 0; i < needed; i++) { page = __alloc_buddy_huge_page(h, htlb_alloc_mask(h), NUMA_NO_NODE, NULL); if (!page) { alloc_ok = false; break; } list_add(&page->lru, &surplus_list); cond_resched(); } allocated += i; /* * After retaking hugetlb_lock, we need to recalculate 'needed' * because either resv_huge_pages or free_huge_pages may have changed. */ spin_lock(&hugetlb_lock); needed = (h->resv_huge_pages + delta) - (h->free_huge_pages + allocated); if (needed > 0) { if (alloc_ok) goto retry; /* * We were not able to allocate enough pages to * satisfy the entire reservation so we free what * we've allocated so far. */ goto free; } /* * The surplus_list now contains _at_least_ the number of extra pages * needed to accommodate the reservation. Add the appropriate number * of pages to the hugetlb pool and free the extras back to the buddy * allocator. Commit the entire reservation here to prevent another * process from stealing the pages as they are added to the pool but * before they are reserved. */ needed += allocated; h->resv_huge_pages += delta; ret = 0; /* Free the needed pages to the hugetlb pool */ list_for_each_entry_safe(page, tmp, &surplus_list, lru) { if ((--needed) < 0) break; /* * This page is now managed by the hugetlb allocator and has * no users -- drop the buddy allocator's reference. */ put_page_testzero(page); VM_BUG_ON_PAGE(page_count(page), page); enqueue_huge_page(h, page); } free: spin_unlock(&hugetlb_lock); /* Free unnecessary surplus pages to the buddy allocator */ list_for_each_entry_safe(page, tmp, &surplus_list, lru) put_page(page); spin_lock(&hugetlb_lock); return ret; } /* * This routine has two main purposes: * 1) Decrement the reservation count (resv_huge_pages) by the value passed * in unused_resv_pages. This corresponds to the prior adjustments made * to the associated reservation map. * 2) Free any unused surplus pages that may have been allocated to satisfy * the reservation. As many as unused_resv_pages may be freed. * * Called with hugetlb_lock held. However, the lock could be dropped (and * reacquired) during calls to cond_resched_lock. Whenever dropping the lock, * we must make sure nobody else can claim pages we are in the process of * freeing. Do this by ensuring resv_huge_page always is greater than the * number of huge pages we plan to free when dropping the lock. */ static void return_unused_surplus_pages(struct hstate *h, unsigned long unused_resv_pages) { unsigned long nr_pages; /* Cannot return gigantic pages currently */ if (hstate_is_gigantic(h)) goto out; /* * Part (or even all) of the reservation could have been backed * by pre-allocated pages. Only free surplus pages. */ nr_pages = min(unused_resv_pages, h->surplus_huge_pages); /* * We want to release as many surplus pages as possible, spread * evenly across all nodes with memory. Iterate across these nodes * until we can no longer free unreserved surplus pages. This occurs * when the nodes with surplus pages have no free pages. * free_pool_huge_page() will balance the the freed pages across the * on-line nodes with memory and will handle the hstate accounting. * * Note that we decrement resv_huge_pages as we free the pages. If * we drop the lock, resv_huge_pages will still be sufficiently large * to cover subsequent pages we may free. */ while (nr_pages--) { h->resv_huge_pages--; unused_resv_pages--; if (!free_pool_huge_page(h, &node_states[N_MEMORY], 1)) goto out; cond_resched_lock(&hugetlb_lock); } out: /* Fully uncommit the reservation */ h->resv_huge_pages -= unused_resv_pages; } /* * vma_needs_reservation, vma_commit_reservation and vma_end_reservation * are used by the huge page allocation routines to manage reservations. * * vma_needs_reservation is called to determine if the huge page at addr * within the vma has an associated reservation. If a reservation is * needed, the value 1 is returned. The caller is then responsible for * managing the global reservation and subpool usage counts. After * the huge page has been allocated, vma_commit_reservation is called * to add the page to the reservation map. If the page allocation fails, * the reservation must be ended instead of committed. vma_end_reservation * is called in such cases. * * In the normal case, vma_commit_reservation returns the same value * as the preceding vma_needs_reservation call. The only time this * is not the case is if a reserve map was changed between calls. It * is the responsibility of the caller to notice the difference and * take appropriate action. * * vma_add_reservation is used in error paths where a reservation must * be restored when a newly allocated huge page must be freed. It is * to be called after calling vma_needs_reservation to determine if a * reservation exists. */ enum vma_resv_mode { VMA_NEEDS_RESV, VMA_COMMIT_RESV, VMA_END_RESV, VMA_ADD_RESV, }; static long __vma_reservation_common(struct hstate *h, struct vm_area_struct *vma, unsigned long addr, enum vma_resv_mode mode) { struct resv_map *resv; pgoff_t idx; long ret; resv = vma_resv_map(vma); if (!resv) return 1; idx = vma_hugecache_offset(h, vma, addr); switch (mode) { case VMA_NEEDS_RESV: ret = region_chg(resv, idx, idx + 1); break; case VMA_COMMIT_RESV: ret = region_add(resv, idx, idx + 1); break; case VMA_END_RESV: region_abort(resv, idx, idx + 1); ret = 0; break; case VMA_ADD_RESV: if (vma->vm_flags & VM_MAYSHARE) ret = region_add(resv, idx, idx + 1); else { region_abort(resv, idx, idx + 1); ret = region_del(resv, idx, idx + 1); } break; default: BUG(); } if (vma->vm_flags & VM_MAYSHARE) return ret; else if (is_vma_resv_set(vma, HPAGE_RESV_OWNER) && ret >= 0) { /* * In most cases, reserves always exist for private mappings. * However, a file associated with mapping could have been * hole punched or truncated after reserves were consumed. * As subsequent fault on such a range will not use reserves. * Subtle - The reserve map for private mappings has the * opposite meaning than that of shared mappings. If NO * entry is in the reserve map, it means a reservation exists. * If an entry exists in the reserve map, it means the * reservation has already been consumed. As a result, the * return value of this routine is the opposite of the * value returned from reserve map manipulation routines above. */ if (ret) return 0; else return 1; } else return ret < 0 ? ret : 0; } static long vma_needs_reservation(struct hstate *h, struct vm_area_struct *vma, unsigned long addr) { return __vma_reservation_common(h, vma, addr, VMA_NEEDS_RESV); } static long vma_commit_reservation(struct hstate *h, struct vm_area_struct *vma, unsigned long addr) { return __vma_reservation_common(h, vma, addr, VMA_COMMIT_RESV); } static void vma_end_reservation(struct hstate *h, struct vm_area_struct *vma, unsigned long addr) { (void)__vma_reservation_common(h, vma, addr, VMA_END_RESV); } static long vma_add_reservation(struct hstate *h, struct vm_area_struct *vma, unsigned long addr) { return __vma_reservation_common(h, vma, addr, VMA_ADD_RESV); } /* * This routine is called to restore a reservation on error paths. In the * specific error paths, a huge page was allocated (via alloc_huge_page) * and is about to be freed. If a reservation for the page existed, * alloc_huge_page would have consumed the reservation and set PagePrivate * in the newly allocated page. When the page is freed via free_huge_page, * the global reservation count will be incremented if PagePrivate is set. * However, free_huge_page can not adjust the reserve map. Adjust the * reserve map here to be consistent with global reserve count adjustments * to be made by free_huge_page. */ static void restore_reserve_on_error(struct hstate *h, struct vm_area_struct *vma, unsigned long address, struct page *page) { if (unlikely(PagePrivate(page))) { long rc = vma_needs_reservation(h, vma, address); if (unlikely(rc < 0)) { /* * Rare out of memory condition in reserve map * manipulation. Clear PagePrivate so that * global reserve count will not be incremented * by free_huge_page. This will make it appear * as though the reservation for this page was * consumed. This may prevent the task from * faulting in the page at a later time. This * is better than inconsistent global huge page * accounting of reserve counts. */ ClearPagePrivate(page); } else if (rc) { rc = vma_add_reservation(h, vma, address); if (unlikely(rc < 0)) /* * See above comment about rare out of * memory condition. */ ClearPagePrivate(page); } else vma_end_reservation(h, vma, address); } } struct page *alloc_huge_page(struct vm_area_struct *vma, unsigned long addr, int avoid_reserve) { struct hugepage_subpool *spool = subpool_vma(vma); struct hstate *h = hstate_vma(vma); struct page *page; long map_chg, map_commit; long gbl_chg; int ret, idx; struct hugetlb_cgroup *h_cg; idx = hstate_index(h); /* * Examine the region/reserve map to determine if the process * has a reservation for the page to be allocated. A return * code of zero indicates a reservation exists (no change). */ map_chg = gbl_chg = vma_needs_reservation(h, vma, addr); if (map_chg < 0) return ERR_PTR(-ENOMEM); /* * Processes that did not create the mapping will have no * reserves as indicated by the region/reserve map. Check * that the allocation will not exceed the subpool limit. * Allocations for MAP_NORESERVE mappings also need to be * checked against any subpool limit. */ if (map_chg || avoid_reserve) { gbl_chg = hugepage_subpool_get_pages(spool, 1); if (gbl_chg < 0) { vma_end_reservation(h, vma, addr); return ERR_PTR(-ENOSPC); } /* * Even though there was no reservation in the region/reserve * map, there could be reservations associated with the * subpool that can be used. This would be indicated if the * return value of hugepage_subpool_get_pages() is zero. * However, if avoid_reserve is specified we still avoid even * the subpool reservations. */ if (avoid_reserve) gbl_chg = 1; } ret = hugetlb_cgroup_charge_cgroup(idx, pages_per_huge_page(h), &h_cg); if (ret) goto out_subpool_put; spin_lock(&hugetlb_lock); /* * glb_chg is passed to indicate whether or not a page must be taken * from the global free pool (global change). gbl_chg == 0 indicates * a reservation exists for the allocation. */ page = dequeue_huge_page_vma(h, vma, addr, avoid_reserve, gbl_chg); if (!page) { spin_unlock(&hugetlb_lock); page = __alloc_buddy_huge_page_with_mpol(h, vma, addr); if (!page) goto out_uncharge_cgroup; if (!avoid_reserve && vma_has_reserves(vma, gbl_chg)) { SetPagePrivate(page); h->resv_huge_pages--; } spin_lock(&hugetlb_lock); list_move(&page->lru, &h->hugepage_activelist); /* Fall through */ } hugetlb_cgroup_commit_charge(idx, pages_per_huge_page(h), h_cg, page); spin_unlock(&hugetlb_lock); set_page_private(page, (unsigned long)spool); map_commit = vma_commit_reservation(h, vma, addr); if (unlikely(map_chg > map_commit)) { /* * The page was added to the reservation map between * vma_needs_reservation and vma_commit_reservation. * This indicates a race with hugetlb_reserve_pages. * Adjust for the subpool count incremented above AND * in hugetlb_reserve_pages for the same page. Also, * the reservation count added in hugetlb_reserve_pages * no longer applies. */ long rsv_adjust; rsv_adjust = hugepage_subpool_put_pages(spool, 1); hugetlb_acct_memory(h, -rsv_adjust); } return page; out_uncharge_cgroup: hugetlb_cgroup_uncharge_cgroup(idx, pages_per_huge_page(h), h_cg); out_subpool_put: if (map_chg || avoid_reserve) hugepage_subpool_put_pages(spool, 1); vma_end_reservation(h, vma, addr); return ERR_PTR(-ENOSPC); } /* * alloc_huge_page()'s wrapper which simply returns the page if allocation * succeeds, otherwise NULL. This function is called from new_vma_page(), * where no ERR_VALUE is expected to be returned. */ struct page *alloc_huge_page_noerr(struct vm_area_struct *vma, unsigned long addr, int avoid_reserve) { struct page *page = alloc_huge_page(vma, addr, avoid_reserve); if (IS_ERR(page)) page = NULL; return page; } int alloc_bootmem_huge_page(struct hstate *h) __attribute__ ((weak, alias("__alloc_bootmem_huge_page"))); int __alloc_bootmem_huge_page(struct hstate *h) { struct huge_bootmem_page *m; int nr_nodes, node; for_each_node_mask_to_alloc(h, nr_nodes, node, &node_states[N_MEMORY]) { void *addr; addr = memblock_virt_alloc_try_nid_nopanic( huge_page_size(h), huge_page_size(h), 0, BOOTMEM_ALLOC_ACCESSIBLE, node); if (addr) { /* * Use the beginning of the huge page to store the * huge_bootmem_page struct (until gather_bootmem * puts them into the mem_map). */ m = addr; goto found; } } return 0; found: BUG_ON(!IS_ALIGNED(virt_to_phys(m), huge_page_size(h))); /* Put them into a private list first because mem_map is not up yet */ list_add(&m->list, &huge_boot_pages); m->hstate = h; return 1; } static void __init prep_compound_huge_page(struct page *page, unsigned int order) { if (unlikely(order > (MAX_ORDER - 1))) prep_compound_gigantic_page(page, order); else prep_compound_page(page, order); } /* Put bootmem huge pages into the standard lists after mem_map is up */ static void __init gather_bootmem_prealloc(void) { struct huge_bootmem_page *m; list_for_each_entry(m, &huge_boot_pages, list) { struct hstate *h = m->hstate; struct page *page; #ifdef CONFIG_HIGHMEM page = pfn_to_page(m->phys >> PAGE_SHIFT); memblock_free_late(__pa(m), sizeof(struct huge_bootmem_page)); #else page = virt_to_page(m); #endif WARN_ON(page_count(page) != 1); prep_compound_huge_page(page, h->order); WARN_ON(PageReserved(page)); prep_new_huge_page(h, page, page_to_nid(page)); /* * If we had gigantic hugepages allocated at boot time, we need * to restore the 'stolen' pages to totalram_pages in order to * fix confusing memory reports from free(1) and another * side-effects, like CommitLimit going negative. */ if (hstate_is_gigantic(h)) adjust_managed_page_count(page, 1 << h->order); } } static void __init hugetlb_hstate_alloc_pages(struct hstate *h) { unsigned long i; for (i = 0; i < h->max_huge_pages; ++i) { if (hstate_is_gigantic(h)) { if (!alloc_bootmem_huge_page(h)) break; } else if (!alloc_fresh_huge_page(h, &node_states[N_MEMORY])) break; cond_resched(); } if (i < h->max_huge_pages) { char buf[32]; string_get_size(huge_page_size(h), 1, STRING_UNITS_2, buf, 32); pr_warn("HugeTLB: allocating %lu of page size %s failed. Only allocated %lu hugepages.\n", h->max_huge_pages, buf, i); h->max_huge_pages = i; } } static void __init hugetlb_init_hstates(void) { struct hstate *h; for_each_hstate(h) { if (minimum_order > huge_page_order(h)) minimum_order = huge_page_order(h); /* oversize hugepages were init'ed in early boot */ if (!hstate_is_gigantic(h)) hugetlb_hstate_alloc_pages(h); } VM_BUG_ON(minimum_order == UINT_MAX); } static void __init report_hugepages(void) { struct hstate *h; for_each_hstate(h) { char buf[32]; string_get_size(huge_page_size(h), 1, STRING_UNITS_2, buf, 32); pr_info("HugeTLB registered %s page size, pre-allocated %ld pages\n", buf, h->free_huge_pages); } } #ifdef CONFIG_HIGHMEM static void try_to_free_low(struct hstate *h, unsigned long count, nodemask_t *nodes_allowed) { int i; if (hstate_is_gigantic(h)) return; for_each_node_mask(i, *nodes_allowed) { struct page *page, *next; struct list_head *freel = &h->hugepage_freelists[i]; list_for_each_entry_safe(page, next, freel, lru) { if (count >= h->nr_huge_pages) return; if (PageHighMem(page)) continue; list_del(&page->lru); update_and_free_page(h, page); h->free_huge_pages--; h->free_huge_pages_node[page_to_nid(page)]--; } } } #else static inline void try_to_free_low(struct hstate *h, unsigned long count, nodemask_t *nodes_allowed) { } #endif /* * Increment or decrement surplus_huge_pages. Keep node-specific counters * balanced by operating on them in a round-robin fashion. * Returns 1 if an adjustment was made. */ static int adjust_pool_surplus(struct hstate *h, nodemask_t *nodes_allowed, int delta) { int nr_nodes, node; VM_BUG_ON(delta != -1 && delta != 1); if (delta < 0) { for_each_node_mask_to_alloc(h, nr_nodes, node, nodes_allowed) { if (h->surplus_huge_pages_node[node]) goto found; } } else { for_each_node_mask_to_free(h, nr_nodes, node, nodes_allowed) { if (h->surplus_huge_pages_node[node] < h->nr_huge_pages_node[node]) goto found; } } return 0; found: h->surplus_huge_pages += delta; h->surplus_huge_pages_node[node] += delta; return 1; } #define persistent_huge_pages(h) (h->nr_huge_pages - h->surplus_huge_pages) static unsigned long set_max_huge_pages(struct hstate *h, unsigned long count, nodemask_t *nodes_allowed) { unsigned long min_count, ret; if (hstate_is_gigantic(h) && !gigantic_page_supported()) return h->max_huge_pages; /* * Increase the pool size * First take pages out of surplus state. Then make up the * remaining difference by allocating fresh huge pages. * * We might race with __alloc_buddy_huge_page() here and be unable * to convert a surplus huge page to a normal huge page. That is * not critical, though, it just means the overall size of the * pool might be one hugepage larger than it needs to be, but * within all the constraints specified by the sysctls. */ spin_lock(&hugetlb_lock); while (h->surplus_huge_pages && count > persistent_huge_pages(h)) { if (!adjust_pool_surplus(h, nodes_allowed, -1)) break; } while (count > persistent_huge_pages(h)) { /* * If this allocation races such that we no longer need the * page, free_huge_page will handle it by freeing the page * and reducing the surplus. */ spin_unlock(&hugetlb_lock); /* yield cpu to avoid soft lockup */ cond_resched(); if (hstate_is_gigantic(h)) ret = alloc_fresh_gigantic_page(h, nodes_allowed); else ret = alloc_fresh_huge_page(h, nodes_allowed); spin_lock(&hugetlb_lock); if (!ret) goto out; /* Bail for signals. Probably ctrl-c from user */ if (signal_pending(current)) goto out; } /* * Decrease the pool size * First return free pages to the buddy allocator (being careful * to keep enough around to satisfy reservations). Then place * pages into surplus state as needed so the pool will shrink * to the desired size as pages become free. * * By placing pages into the surplus state independent of the * overcommit value, we are allowing the surplus pool size to * exceed overcommit. There are few sane options here. Since * __alloc_buddy_huge_page() is checking the global counter, * though, we'll note that we're not allowed to exceed surplus * and won't grow the pool anywhere else. Not until one of the * sysctls are changed, or the surplus pages go out of use. */ min_count = h->resv_huge_pages + h->nr_huge_pages - h->free_huge_pages; min_count = max(count, min_count); try_to_free_low(h, min_count, nodes_allowed); while (min_count < persistent_huge_pages(h)) { if (!free_pool_huge_page(h, nodes_allowed, 0)) break; cond_resched_lock(&hugetlb_lock); } while (count < persistent_huge_pages(h)) { if (!adjust_pool_surplus(h, nodes_allowed, 1)) break; } out: ret = persistent_huge_pages(h); spin_unlock(&hugetlb_lock); return ret; } #define HSTATE_ATTR_RO(_name) \ static struct kobj_attribute _name##_attr = __ATTR_RO(_name) #define HSTATE_ATTR(_name) \ static struct kobj_attribute _name##_attr = \ __ATTR(_name, 0644, _name##_show, _name##_store) static struct kobject *hugepages_kobj; static struct kobject *hstate_kobjs[HUGE_MAX_HSTATE]; static struct hstate *kobj_to_node_hstate(struct kobject *kobj, int *nidp); static struct hstate *kobj_to_hstate(struct kobject *kobj, int *nidp) { int i; for (i = 0; i < HUGE_MAX_HSTATE; i++) if (hstate_kobjs[i] == kobj) { if (nidp) *nidp = NUMA_NO_NODE; return &hstates[i]; } return kobj_to_node_hstate(kobj, nidp); } static ssize_t nr_hugepages_show_common(struct kobject *kobj, struct kobj_attribute *attr, char *buf) { struct hstate *h; unsigned long nr_huge_pages; int nid; h = kobj_to_hstate(kobj, &nid); if (nid == NUMA_NO_NODE) nr_huge_pages = h->nr_huge_pages; else nr_huge_pages = h->nr_huge_pages_node[nid]; return sprintf(buf, "%lu\n", nr_huge_pages); } static ssize_t __nr_hugepages_store_common(bool obey_mempolicy, struct hstate *h, int nid, unsigned long count, size_t len) { int err; NODEMASK_ALLOC(nodemask_t, nodes_allowed, GFP_KERNEL | __GFP_NORETRY); if (hstate_is_gigantic(h) && !gigantic_page_supported()) { err = -EINVAL; goto out; } if (nid == NUMA_NO_NODE) { /* * global hstate attribute */ if (!(obey_mempolicy && init_nodemask_of_mempolicy(nodes_allowed))) { NODEMASK_FREE(nodes_allowed); nodes_allowed = &node_states[N_MEMORY]; } } else if (nodes_allowed) { /* * per node hstate attribute: adjust count to global, * but restrict alloc/free to the specified node. */ count += h->nr_huge_pages - h->nr_huge_pages_node[nid]; init_nodemask_of_node(nodes_allowed, nid); } else nodes_allowed = &node_states[N_MEMORY]; h->max_huge_pages = set_max_huge_pages(h, count, nodes_allowed); if (nodes_allowed != &node_states[N_MEMORY]) NODEMASK_FREE(nodes_allowed); return len; out: NODEMASK_FREE(nodes_allowed); return err; } static ssize_t nr_hugepages_store_common(bool obey_mempolicy, struct kobject *kobj, const char *buf, size_t len) { struct hstate *h; unsigned long count; int nid; int err; err = kstrtoul(buf, 10, &count); if (err) return err; h = kobj_to_hstate(kobj, &nid); return __nr_hugepages_store_common(obey_mempolicy, h, nid, count, len); } static ssize_t nr_hugepages_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) { return nr_hugepages_show_common(kobj, attr, buf); } static ssize_t nr_hugepages_store(struct kobject *kobj, struct kobj_attribute *attr, const char *buf, size_t len) { return nr_hugepages_store_common(false, kobj, buf, len); } HSTATE_ATTR(nr_hugepages); #ifdef CONFIG_NUMA /* * hstate attribute for optionally mempolicy-based constraint on persistent * huge page alloc/free. */ static ssize_t nr_hugepages_mempolicy_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) { return nr_hugepages_show_common(kobj, attr, buf); } static ssize_t nr_hugepages_mempolicy_store(struct kobject *kobj, struct kobj_attribute *attr, const char *buf, size_t len) { return nr_hugepages_store_common(true, kobj, buf, len); } HSTATE_ATTR(nr_hugepages_mempolicy); #endif static ssize_t nr_overcommit_hugepages_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) { struct hstate *h = kobj_to_hstate(kobj, NULL); return sprintf(buf, "%lu\n", h->nr_overcommit_huge_pages); } static ssize_t nr_overcommit_hugepages_store(struct kobject *kobj, struct kobj_attribute *attr, const char *buf, size_t count) { int err; unsigned long input; struct hstate *h = kobj_to_hstate(kobj, NULL); if (hstate_is_gigantic(h)) return -EINVAL; err = kstrtoul(buf, 10, &input); if (err) return err; spin_lock(&hugetlb_lock); h->nr_overcommit_huge_pages = input; spin_unlock(&hugetlb_lock); return count; } HSTATE_ATTR(nr_overcommit_hugepages); static ssize_t free_hugepages_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) { struct hstate *h; unsigned long free_huge_pages; int nid; h = kobj_to_hstate(kobj, &nid); if (nid == NUMA_NO_NODE) free_huge_pages = h->free_huge_pages; else free_huge_pages = h->free_huge_pages_node[nid]; return sprintf(buf, "%lu\n", free_huge_pages); } HSTATE_ATTR_RO(free_hugepages); static ssize_t resv_hugepages_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) { struct hstate *h = kobj_to_hstate(kobj, NULL); return sprintf(buf, "%lu\n", h->resv_huge_pages); } HSTATE_ATTR_RO(resv_hugepages); static ssize_t surplus_hugepages_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) { struct hstate *h; unsigned long surplus_huge_pages; int nid; h = kobj_to_hstate(kobj, &nid); if (nid == NUMA_NO_NODE) surplus_huge_pages = h->surplus_huge_pages; else surplus_huge_pages = h->surplus_huge_pages_node[nid]; return sprintf(buf, "%lu\n", surplus_huge_pages); } HSTATE_ATTR_RO(surplus_hugepages); static struct attribute *hstate_attrs[] = { &nr_hugepages_attr.attr, &nr_overcommit_hugepages_attr.attr, &free_hugepages_attr.attr, &resv_hugepages_attr.attr, &surplus_hugepages_attr.attr, #ifdef CONFIG_NUMA &nr_hugepages_mempolicy_attr.attr, #endif NULL, }; static const struct attribute_group hstate_attr_group = { .attrs = hstate_attrs, }; static int hugetlb_sysfs_add_hstate(struct hstate *h, struct kobject *parent, struct kobject **hstate_kobjs, const struct attribute_group *hstate_attr_group) { int retval; int hi = hstate_index(h); hstate_kobjs[hi] = kobject_create_and_add(h->name, parent); if (!hstate_kobjs[hi]) return -ENOMEM; retval = sysfs_create_group(hstate_kobjs[hi], hstate_attr_group); if (retval) kobject_put(hstate_kobjs[hi]); return retval; } static void __init hugetlb_sysfs_init(void) { struct hstate *h; int err; hugepages_kobj = kobject_create_and_add("hugepages", mm_kobj); if (!hugepages_kobj) return; for_each_hstate(h) { err = hugetlb_sysfs_add_hstate(h, hugepages_kobj, hstate_kobjs, &hstate_attr_group); if (err) pr_err("Hugetlb: Unable to add hstate %s", h->name); } } #ifdef CONFIG_NUMA /* * node_hstate/s - associate per node hstate attributes, via their kobjects, * with node devices in node_devices[] using a parallel array. The array * index of a node device or _hstate == node id. * This is here to avoid any static dependency of the node device driver, in * the base kernel, on the hugetlb module. */ struct node_hstate { struct kobject *hugepages_kobj; struct kobject *hstate_kobjs[HUGE_MAX_HSTATE]; }; static struct node_hstate node_hstates[MAX_NUMNODES]; /* * A subset of global hstate attributes for node devices */ static struct attribute *per_node_hstate_attrs[] = { &nr_hugepages_attr.attr, &free_hugepages_attr.attr, &surplus_hugepages_attr.attr, NULL, }; static const struct attribute_group per_node_hstate_attr_group = { .attrs = per_node_hstate_attrs, }; /* * kobj_to_node_hstate - lookup global hstate for node device hstate attr kobj. * Returns node id via non-NULL nidp. */ static struct hstate *kobj_to_node_hstate(struct kobject *kobj, int *nidp) { int nid; for (nid = 0; nid < nr_node_ids; nid++) { struct node_hstate *nhs = &node_hstates[nid]; int i; for (i = 0; i < HUGE_MAX_HSTATE; i++) if (nhs->hstate_kobjs[i] == kobj) { if (nidp) *nidp = nid; return &hstates[i]; } } BUG(); return NULL; } /* * Unregister hstate attributes from a single node device. * No-op if no hstate attributes attached. */ static void hugetlb_unregister_node(struct node *node) { struct hstate *h; struct node_hstate *nhs = &node_hstates[node->dev.id]; if (!nhs->hugepages_kobj) return; /* no hstate attributes */ for_each_hstate(h) { int idx = hstate_index(h); if (nhs->hstate_kobjs[idx]) { kobject_put(nhs->hstate_kobjs[idx]); nhs->hstate_kobjs[idx] = NULL; } } kobject_put(nhs->hugepages_kobj); nhs->hugepages_kobj = NULL; } /* * Register hstate attributes for a single node device. * No-op if attributes already registered. */ static void hugetlb_register_node(struct node *node) { struct hstate *h; struct node_hstate *nhs = &node_hstates[node->dev.id]; int err; if (nhs->hugepages_kobj) return; /* already allocated */ nhs->hugepages_kobj = kobject_create_and_add("hugepages", &node->dev.kobj); if (!nhs->hugepages_kobj) return; for_each_hstate(h) { err = hugetlb_sysfs_add_hstate(h, nhs->hugepages_kobj, nhs->hstate_kobjs, &per_node_hstate_attr_group); if (err) { pr_err("Hugetlb: Unable to add hstate %s for node %d\n", h->name, node->dev.id); hugetlb_unregister_node(node); break; } } } /* * hugetlb init time: register hstate attributes for all registered node * devices of nodes that have memory. All on-line nodes should have * registered their associated device by this time. */ static void __init hugetlb_register_all_nodes(void) { int nid; for_each_node_state(nid, N_MEMORY) { struct node *node = node_devices[nid]; if (node->dev.id == nid) hugetlb_register_node(node); } /* * Let the node device driver know we're here so it can * [un]register hstate attributes on node hotplug. */ register_hugetlbfs_with_node(hugetlb_register_node, hugetlb_unregister_node); } #else /* !CONFIG_NUMA */ static struct hstate *kobj_to_node_hstate(struct kobject *kobj, int *nidp) { BUG(); if (nidp) *nidp = -1; return NULL; } static void hugetlb_register_all_nodes(void) { } #endif static int __init hugetlb_init(void) { int i; if (!hugepages_supported()) return 0; if (!size_to_hstate(default_hstate_size)) { if (default_hstate_size != 0) { pr_err("HugeTLB: unsupported default_hugepagesz %lu. Reverting to %lu\n", default_hstate_size, HPAGE_SIZE); } default_hstate_size = HPAGE_SIZE; if (!size_to_hstate(default_hstate_size)) hugetlb_add_hstate(HUGETLB_PAGE_ORDER); } default_hstate_idx = hstate_index(size_to_hstate(default_hstate_size)); if (default_hstate_max_huge_pages) { if (!default_hstate.max_huge_pages) default_hstate.max_huge_pages = default_hstate_max_huge_pages; } hugetlb_init_hstates(); gather_bootmem_prealloc(); report_hugepages(); hugetlb_sysfs_init(); hugetlb_register_all_nodes(); hugetlb_cgroup_file_init(); #ifdef CONFIG_SMP num_fault_mutexes = roundup_pow_of_two(8 * num_possible_cpus()); #else num_fault_mutexes = 1; #endif hugetlb_fault_mutex_table = kmalloc(sizeof(struct mutex) * num_fault_mutexes, GFP_KERNEL); BUG_ON(!hugetlb_fault_mutex_table); for (i = 0; i < num_fault_mutexes; i++) mutex_init(&hugetlb_fault_mutex_table[i]); return 0; } subsys_initcall(hugetlb_init); /* Should be called on processing a hugepagesz=... option */ void __init hugetlb_bad_size(void) { parsed_valid_hugepagesz = false; } void __init hugetlb_add_hstate(unsigned int order) { struct hstate *h; unsigned long i; if (size_to_hstate(PAGE_SIZE << order)) { pr_warn("hugepagesz= specified twice, ignoring\n"); return; } BUG_ON(hugetlb_max_hstate >= HUGE_MAX_HSTATE); BUG_ON(order == 0); h = &hstates[hugetlb_max_hstate++]; h->order = order; h->mask = ~((1ULL << (order + PAGE_SHIFT)) - 1); h->nr_huge_pages = 0; h->free_huge_pages = 0; for (i = 0; i < MAX_NUMNODES; ++i) INIT_LIST_HEAD(&h->hugepage_freelists[i]); INIT_LIST_HEAD(&h->hugepage_activelist); h->next_nid_to_alloc = first_memory_node; h->next_nid_to_free = first_memory_node; snprintf(h->name, HSTATE_NAME_LEN, "hugepages-%lukB", huge_page_size(h)/1024); parsed_hstate = h; } static int __init hugetlb_nrpages_setup(char *s) { unsigned long *mhp; static unsigned long *last_mhp; if (!parsed_valid_hugepagesz) { pr_warn("hugepages = %s preceded by " "an unsupported hugepagesz, ignoring\n", s); parsed_valid_hugepagesz = true; return 1; } /* * !hugetlb_max_hstate means we haven't parsed a hugepagesz= parameter yet, * so this hugepages= parameter goes to the "default hstate". */ else if (!hugetlb_max_hstate) mhp = &default_hstate_max_huge_pages; else mhp = &parsed_hstate->max_huge_pages; if (mhp == last_mhp) { pr_warn("hugepages= specified twice without interleaving hugepagesz=, ignoring\n"); return 1; } if (sscanf(s, "%lu", mhp) <= 0) *mhp = 0; /* * Global state is always initialized later in hugetlb_init. * But we need to allocate >= MAX_ORDER hstates here early to still * use the bootmem allocator. */ if (hugetlb_max_hstate && parsed_hstate->order >= MAX_ORDER) hugetlb_hstate_alloc_pages(parsed_hstate); last_mhp = mhp; return 1; } __setup("hugepages=", hugetlb_nrpages_setup); static int __init hugetlb_default_setup(char *s) { default_hstate_size = memparse(s, &s); return 1; } __setup("default_hugepagesz=", hugetlb_default_setup); static unsigned int cpuset_mems_nr(unsigned int *array) { int node; unsigned int nr = 0; for_each_node_mask(node, cpuset_current_mems_allowed) nr += array[node]; return nr; } #ifdef CONFIG_SYSCTL static int hugetlb_sysctl_handler_common(bool obey_mempolicy, struct ctl_table *table, int write, void __user *buffer, size_t *length, loff_t *ppos) { struct hstate *h = &default_hstate; unsigned long tmp = h->max_huge_pages; int ret; if (!hugepages_supported()) return -EOPNOTSUPP; table->data = &tmp; table->maxlen = sizeof(unsigned long); ret = proc_doulongvec_minmax(table, write, buffer, length, ppos); if (ret) goto out; if (write) ret = __nr_hugepages_store_common(obey_mempolicy, h, NUMA_NO_NODE, tmp, *length); out: return ret; } int hugetlb_sysctl_handler(struct ctl_table *table, int write, void __user *buffer, size_t *length, loff_t *ppos) { return hugetlb_sysctl_handler_common(false, table, write, buffer, length, ppos); } #ifdef CONFIG_NUMA int hugetlb_mempolicy_sysctl_handler(struct ctl_table *table, int write, void __user *buffer, size_t *length, loff_t *ppos) { return hugetlb_sysctl_handler_common(true, table, write, buffer, length, ppos); } #endif /* CONFIG_NUMA */ int hugetlb_overcommit_handler(struct ctl_table *table, int write, void __user *buffer, size_t *length, loff_t *ppos) { struct hstate *h = &default_hstate; unsigned long tmp; int ret; if (!hugepages_supported()) return -EOPNOTSUPP; tmp = h->nr_overcommit_huge_pages; if (write && hstate_is_gigantic(h)) return -EINVAL; table->data = &tmp; table->maxlen = sizeof(unsigned long); ret = proc_doulongvec_minmax(table, write, buffer, length, ppos); if (ret) goto out; if (write) { spin_lock(&hugetlb_lock); h->nr_overcommit_huge_pages = tmp; spin_unlock(&hugetlb_lock); } out: return ret; } #endif /* CONFIG_SYSCTL */ void hugetlb_report_meminfo(struct seq_file *m) { struct hstate *h = &default_hstate; if (!hugepages_supported()) return; seq_printf(m, "HugePages_Total: %5lu\n" "HugePages_Free: %5lu\n" "HugePages_Rsvd: %5lu\n" "HugePages_Surp: %5lu\n" "Hugepagesize: %8lu kB\n", h->nr_huge_pages, h->free_huge_pages, h->resv_huge_pages, h->surplus_huge_pages, 1UL << (huge_page_order(h) + PAGE_SHIFT - 10)); } int hugetlb_report_node_meminfo(int nid, char *buf) { struct hstate *h = &default_hstate; if (!hugepages_supported()) return 0; return sprintf(buf, "Node %d HugePages_Total: %5u\n" "Node %d HugePages_Free: %5u\n" "Node %d HugePages_Surp: %5u\n", nid, h->nr_huge_pages_node[nid], nid, h->free_huge_pages_node[nid], nid, h->surplus_huge_pages_node[nid]); } void hugetlb_show_meminfo(void) { struct hstate *h; int nid; if (!hugepages_supported()) return; for_each_node_state(nid, N_MEMORY) for_each_hstate(h) pr_info("Node %d hugepages_total=%u hugepages_free=%u hugepages_surp=%u hugepages_size=%lukB\n", nid, h->nr_huge_pages_node[nid], h->free_huge_pages_node[nid], h->surplus_huge_pages_node[nid], 1UL << (huge_page_order(h) + PAGE_SHIFT - 10)); } void hugetlb_report_usage(struct seq_file *m, struct mm_struct *mm) { seq_printf(m, "HugetlbPages:\t%8lu kB\n", atomic_long_read(&mm->hugetlb_usage) << (PAGE_SHIFT - 10)); } /* Return the number pages of memory we physically have, in PAGE_SIZE units. */ unsigned long hugetlb_total_pages(void) { struct hstate *h; unsigned long nr_total_pages = 0; for_each_hstate(h) nr_total_pages += h->nr_huge_pages * pages_per_huge_page(h); return nr_total_pages; } static int hugetlb_acct_memory(struct hstate *h, long delta) { int ret = -ENOMEM; spin_lock(&hugetlb_lock); /* * When cpuset is configured, it breaks the strict hugetlb page * reservation as the accounting is done on a global variable. Such * reservation is completely rubbish in the presence of cpuset because * the reservation is not checked against page availability for the * current cpuset. Application can still potentially OOM'ed by kernel * with lack of free htlb page in cpuset that the task is in. * Attempt to enforce strict accounting with cpuset is almost * impossible (or too ugly) because cpuset is too fluid that * task or memory node can be dynamically moved between cpusets. * * The change of semantics for shared hugetlb mapping with cpuset is * undesirable. However, in order to preserve some of the semantics, * we fall back to check against current free page availability as * a best attempt and hopefully to minimize the impact of changing * semantics that cpuset has. */ if (delta > 0) { if (gather_surplus_pages(h, delta) < 0) goto out; if (delta > cpuset_mems_nr(h->free_huge_pages_node)) { return_unused_surplus_pages(h, delta); goto out; } } ret = 0; if (delta < 0) return_unused_surplus_pages(h, (unsigned long) -delta); out: spin_unlock(&hugetlb_lock); return ret; } static void hugetlb_vm_op_open(struct vm_area_struct *vma) { struct resv_map *resv = vma_resv_map(vma); /* * This new VMA should share its siblings reservation map if present. * The VMA will only ever have a valid reservation map pointer where * it is being copied for another still existing VMA. As that VMA * has a reference to the reservation map it cannot disappear until * after this open call completes. It is therefore safe to take a * new reference here without additional locking. */ if (resv && is_vma_resv_set(vma, HPAGE_RESV_OWNER)) kref_get(&resv->refs); } static void hugetlb_vm_op_close(struct vm_area_struct *vma) { struct hstate *h = hstate_vma(vma); struct resv_map *resv = vma_resv_map(vma); struct hugepage_subpool *spool = subpool_vma(vma); unsigned long reserve, start, end; long gbl_reserve; if (!resv || !is_vma_resv_set(vma, HPAGE_RESV_OWNER)) return; start = vma_hugecache_offset(h, vma, vma->vm_start); end = vma_hugecache_offset(h, vma, vma->vm_end); reserve = (end - start) - region_count(resv, start, end); kref_put(&resv->refs, resv_map_release); if (reserve) { /* * Decrement reserve counts. The global reserve count may be * adjusted if the subpool has a minimum size. */ gbl_reserve = hugepage_subpool_put_pages(spool, reserve); hugetlb_acct_memory(h, -gbl_reserve); } } /* * We cannot handle pagefaults against hugetlb pages at all. They cause * handle_mm_fault() to try to instantiate regular-sized pages in the * hugegpage VMA. do_page_fault() is supposed to trap this, so BUG is we get * this far. */ static int hugetlb_vm_op_fault(struct vm_fault *vmf) { BUG(); return 0; } const struct vm_operations_struct hugetlb_vm_ops = { .fault = hugetlb_vm_op_fault, .open = hugetlb_vm_op_open, .close = hugetlb_vm_op_close, }; static pte_t make_huge_pte(struct vm_area_struct *vma, struct page *page, int writable) { pte_t entry; if (writable) { entry = huge_pte_mkwrite(huge_pte_mkdirty(mk_huge_pte(page, vma->vm_page_prot))); } else { entry = huge_pte_wrprotect(mk_huge_pte(page, vma->vm_page_prot)); } entry = pte_mkyoung(entry); entry = pte_mkhuge(entry); entry = arch_make_huge_pte(entry, vma, page, writable); return entry; } static void set_huge_ptep_writable(struct vm_area_struct *vma, unsigned long address, pte_t *ptep) { pte_t entry; entry = huge_pte_mkwrite(huge_pte_mkdirty(huge_ptep_get(ptep))); if (huge_ptep_set_access_flags(vma, address, ptep, entry, 1)) update_mmu_cache(vma, address, ptep); } bool is_hugetlb_entry_migration(pte_t pte) { swp_entry_t swp; if (huge_pte_none(pte) || pte_present(pte)) return false; swp = pte_to_swp_entry(pte); if (non_swap_entry(swp) && is_migration_entry(swp)) return true; else return false; } static int is_hugetlb_entry_hwpoisoned(pte_t pte) { swp_entry_t swp; if (huge_pte_none(pte) || pte_present(pte)) return 0; swp = pte_to_swp_entry(pte); if (non_swap_entry(swp) && is_hwpoison_entry(swp)) return 1; else return 0; } int copy_hugetlb_page_range(struct mm_struct *dst, struct mm_struct *src, struct vm_area_struct *vma) { pte_t *src_pte, *dst_pte, entry; struct page *ptepage; unsigned long addr; int cow; struct hstate *h = hstate_vma(vma); unsigned long sz = huge_page_size(h); unsigned long mmun_start; /* For mmu_notifiers */ unsigned long mmun_end; /* For mmu_notifiers */ int ret = 0; cow = (vma->vm_flags & (VM_SHARED | VM_MAYWRITE)) == VM_MAYWRITE; mmun_start = vma->vm_start; mmun_end = vma->vm_end; if (cow) mmu_notifier_invalidate_range_start(src, mmun_start, mmun_end); for (addr = vma->vm_start; addr < vma->vm_end; addr += sz) { spinlock_t *src_ptl, *dst_ptl; src_pte = huge_pte_offset(src, addr, sz); if (!src_pte) continue; dst_pte = huge_pte_alloc(dst, addr, sz); if (!dst_pte) { ret = -ENOMEM; break; } /* If the pagetables are shared don't copy or take references */ if (dst_pte == src_pte) continue; dst_ptl = huge_pte_lock(h, dst, dst_pte); src_ptl = huge_pte_lockptr(h, src, src_pte); spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING); entry = huge_ptep_get(src_pte); if (huge_pte_none(entry)) { /* skip none entry */ ; } else if (unlikely(is_hugetlb_entry_migration(entry) || is_hugetlb_entry_hwpoisoned(entry))) { swp_entry_t swp_entry = pte_to_swp_entry(entry); if (is_write_migration_entry(swp_entry) && cow) { /* * COW mappings require pages in both * parent and child to be set to read. */ make_migration_entry_read(&swp_entry); entry = swp_entry_to_pte(swp_entry); set_huge_swap_pte_at(src, addr, src_pte, entry, sz); } set_huge_swap_pte_at(dst, addr, dst_pte, entry, sz); } else { if (cow) { huge_ptep_set_wrprotect(src, addr, src_pte); mmu_notifier_invalidate_range(src, mmun_start, mmun_end); } entry = huge_ptep_get(src_pte); ptepage = pte_page(entry); get_page(ptepage); page_dup_rmap(ptepage, true); set_huge_pte_at(dst, addr, dst_pte, entry); hugetlb_count_add(pages_per_huge_page(h), dst); } spin_unlock(src_ptl); spin_unlock(dst_ptl); } if (cow) mmu_notifier_invalidate_range_end(src, mmun_start, mmun_end); return ret; } void __unmap_hugepage_range(struct mmu_gather *tlb, struct vm_area_struct *vma, unsigned long start, unsigned long end, struct page *ref_page) { struct mm_struct *mm = vma->vm_mm; unsigned long address; pte_t *ptep; pte_t pte; spinlock_t *ptl; struct page *page; struct hstate *h = hstate_vma(vma); unsigned long sz = huge_page_size(h); const unsigned long mmun_start = start; /* For mmu_notifiers */ const unsigned long mmun_end = end; /* For mmu_notifiers */ WARN_ON(!is_vm_hugetlb_page(vma)); BUG_ON(start & ~huge_page_mask(h)); BUG_ON(end & ~huge_page_mask(h)); /* * This is a hugetlb vma, all the pte entries should point * to huge page. */ tlb_remove_check_page_size_change(tlb, sz); tlb_start_vma(tlb, vma); mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end); address = start; for (; address < end; address += sz) { ptep = huge_pte_offset(mm, address, sz); if (!ptep) continue; ptl = huge_pte_lock(h, mm, ptep); if (huge_pmd_unshare(mm, &address, ptep)) { spin_unlock(ptl); continue; } pte = huge_ptep_get(ptep); if (huge_pte_none(pte)) { spin_unlock(ptl); continue; } /* * Migrating hugepage or HWPoisoned hugepage is already * unmapped and its refcount is dropped, so just clear pte here. */ if (unlikely(!pte_present(pte))) { huge_pte_clear(mm, address, ptep, sz); spin_unlock(ptl); continue; } page = pte_page(pte); /* * If a reference page is supplied, it is because a specific * page is being unmapped, not a range. Ensure the page we * are about to unmap is the actual page of interest. */ if (ref_page) { if (page != ref_page) { spin_unlock(ptl); continue; } /* * Mark the VMA as having unmapped its page so that * future faults in this VMA will fail rather than * looking like data was lost */ set_vma_resv_flags(vma, HPAGE_RESV_UNMAPPED); } pte = huge_ptep_get_and_clear(mm, address, ptep); tlb_remove_huge_tlb_entry(h, tlb, ptep, address); if (huge_pte_dirty(pte)) set_page_dirty(page); hugetlb_count_sub(pages_per_huge_page(h), mm); page_remove_rmap(page, true); spin_unlock(ptl); tlb_remove_page_size(tlb, page, huge_page_size(h)); /* * Bail out after unmapping reference page if supplied */ if (ref_page) break; } mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end); tlb_end_vma(tlb, vma); } void __unmap_hugepage_range_final(struct mmu_gather *tlb, struct vm_area_struct *vma, unsigned long start, unsigned long end, struct page *ref_page) { __unmap_hugepage_range(tlb, vma, start, end, ref_page); /* * Clear this flag so that x86's huge_pmd_share page_table_shareable * test will fail on a vma being torn down, and not grab a page table * on its way out. We're lucky that the flag has such an appropriate * name, and can in fact be safely cleared here. We could clear it * before the __unmap_hugepage_range above, but all that's necessary * is to clear it before releasing the i_mmap_rwsem. This works * because in the context this is called, the VMA is about to be * destroyed and the i_mmap_rwsem is held. */ vma->vm_flags &= ~VM_MAYSHARE; } void unmap_hugepage_range(struct vm_area_struct *vma, unsigned long start, unsigned long end, struct page *ref_page) { struct mm_struct *mm; struct mmu_gather tlb; mm = vma->vm_mm; tlb_gather_mmu(&tlb, mm, start, end); __unmap_hugepage_range(&tlb, vma, start, end, ref_page); tlb_finish_mmu(&tlb, start, end); } /* * This is called when the original mapper is failing to COW a MAP_PRIVATE * mappping it owns the reserve page for. The intention is to unmap the page * from other VMAs and let the children be SIGKILLed if they are faulting the * same region. */ static void unmap_ref_private(struct mm_struct *mm, struct vm_area_struct *vma, struct page *page, unsigned long address) { struct hstate *h = hstate_vma(vma); struct vm_area_struct *iter_vma; struct address_space *mapping; pgoff_t pgoff; /* * vm_pgoff is in PAGE_SIZE units, hence the different calculation * from page cache lookup which is in HPAGE_SIZE units. */ address = address & huge_page_mask(h); pgoff = ((address - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff; mapping = vma->vm_file->f_mapping; /* * Take the mapping lock for the duration of the table walk. As * this mapping should be shared between all the VMAs, * __unmap_hugepage_range() is called as the lock is already held */ i_mmap_lock_write(mapping); vma_interval_tree_foreach(iter_vma, &mapping->i_mmap, pgoff, pgoff) { /* Do not unmap the current VMA */ if (iter_vma == vma) continue; /* * Shared VMAs have their own reserves and do not affect * MAP_PRIVATE accounting but it is possible that a shared * VMA is using the same page so check and skip such VMAs. */ if (iter_vma->vm_flags & VM_MAYSHARE) continue; /* * Unmap the page from other VMAs without their own reserves. * They get marked to be SIGKILLed if they fault in these * areas. This is because a future no-page fault on this VMA * could insert a zeroed page instead of the data existing * from the time of fork. This would look like data corruption */ if (!is_vma_resv_set(iter_vma, HPAGE_RESV_OWNER)) unmap_hugepage_range(iter_vma, address, address + huge_page_size(h), page); } i_mmap_unlock_write(mapping); } /* * Hugetlb_cow() should be called with page lock of the original hugepage held. * Called with hugetlb_instantiation_mutex held and pte_page locked so we * cannot race with other handlers or page migration. * Keep the pte_same checks anyway to make transition from the mutex easier. */ static int hugetlb_cow(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long address, pte_t *ptep, struct page *pagecache_page, spinlock_t *ptl) { pte_t pte; struct hstate *h = hstate_vma(vma); struct page *old_page, *new_page; int ret = 0, outside_reserve = 0; unsigned long mmun_start; /* For mmu_notifiers */ unsigned long mmun_end; /* For mmu_notifiers */ pte = huge_ptep_get(ptep); old_page = pte_page(pte); retry_avoidcopy: /* If no-one else is actually using this page, avoid the copy * and just make the page writable */ if (page_mapcount(old_page) == 1 && PageAnon(old_page)) { page_move_anon_rmap(old_page, vma); set_huge_ptep_writable(vma, address, ptep); return 0; } /* * If the process that created a MAP_PRIVATE mapping is about to * perform a COW due to a shared page count, attempt to satisfy * the allocation without using the existing reserves. The pagecache * page is used to determine if the reserve at this address was * consumed or not. If reserves were used, a partial faulted mapping * at the time of fork() could consume its reserves on COW instead * of the full address range. */ if (is_vma_resv_set(vma, HPAGE_RESV_OWNER) && old_page != pagecache_page) outside_reserve = 1; get_page(old_page); /* * Drop page table lock as buddy allocator may be called. It will * be acquired again before returning to the caller, as expected. */ spin_unlock(ptl); new_page = alloc_huge_page(vma, address, outside_reserve); if (IS_ERR(new_page)) { /* * If a process owning a MAP_PRIVATE mapping fails to COW, * it is due to references held by a child and an insufficient * huge page pool. To guarantee the original mappers * reliability, unmap the page from child processes. The child * may get SIGKILLed if it later faults. */ if (outside_reserve) { put_page(old_page); BUG_ON(huge_pte_none(pte)); unmap_ref_private(mm, vma, old_page, address); BUG_ON(huge_pte_none(pte)); spin_lock(ptl); ptep = huge_pte_offset(mm, address & huge_page_mask(h), huge_page_size(h)); if (likely(ptep && pte_same(huge_ptep_get(ptep), pte))) goto retry_avoidcopy; /* * race occurs while re-acquiring page table * lock, and our job is done. */ return 0; } ret = (PTR_ERR(new_page) == -ENOMEM) ? VM_FAULT_OOM : VM_FAULT_SIGBUS; goto out_release_old; } /* * When the original hugepage is shared one, it does not have * anon_vma prepared. */ if (unlikely(anon_vma_prepare(vma))) { ret = VM_FAULT_OOM; goto out_release_all; } copy_user_huge_page(new_page, old_page, address, vma, pages_per_huge_page(h)); __SetPageUptodate(new_page); set_page_huge_active(new_page); mmun_start = address & huge_page_mask(h); mmun_end = mmun_start + huge_page_size(h); mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end); /* * Retake the page table lock to check for racing updates * before the page tables are altered */ spin_lock(ptl); ptep = huge_pte_offset(mm, address & huge_page_mask(h), huge_page_size(h)); if (likely(ptep && pte_same(huge_ptep_get(ptep), pte))) { ClearPagePrivate(new_page); /* Break COW */ huge_ptep_clear_flush(vma, address, ptep); mmu_notifier_invalidate_range(mm, mmun_start, mmun_end); set_huge_pte_at(mm, address, ptep, make_huge_pte(vma, new_page, 1)); page_remove_rmap(old_page, true); hugepage_add_new_anon_rmap(new_page, vma, address); /* Make the old page be freed below */ new_page = old_page; } spin_unlock(ptl); mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end); out_release_all: restore_reserve_on_error(h, vma, address, new_page); put_page(new_page); out_release_old: put_page(old_page); spin_lock(ptl); /* Caller expects lock to be held */ return ret; } /* Return the pagecache page at a given address within a VMA */ static struct page *hugetlbfs_pagecache_page(struct hstate *h, struct vm_area_struct *vma, unsigned long address) { struct address_space *mapping; pgoff_t idx; mapping = vma->vm_file->f_mapping; idx = vma_hugecache_offset(h, vma, address); return find_lock_page(mapping, idx); } /* * Return whether there is a pagecache page to back given address within VMA. * Caller follow_hugetlb_page() holds page_table_lock so we cannot lock_page. */ static bool hugetlbfs_pagecache_present(struct hstate *h, struct vm_area_struct *vma, unsigned long address) { struct address_space *mapping; pgoff_t idx; struct page *page; mapping = vma->vm_file->f_mapping; idx = vma_hugecache_offset(h, vma, address); page = find_get_page(mapping, idx); if (page) put_page(page); return page != NULL; } int huge_add_to_page_cache(struct page *page, struct address_space *mapping, pgoff_t idx) { struct inode *inode = mapping->host; struct hstate *h = hstate_inode(inode); int err = add_to_page_cache(page, mapping, idx, GFP_KERNEL); if (err) return err; ClearPagePrivate(page); spin_lock(&inode->i_lock); inode->i_blocks += blocks_per_huge_page(h); spin_unlock(&inode->i_lock); return 0; } static int hugetlb_no_page(struct mm_struct *mm, struct vm_area_struct *vma, struct address_space *mapping, pgoff_t idx, unsigned long address, pte_t *ptep, unsigned int flags) { struct hstate *h = hstate_vma(vma); int ret = VM_FAULT_SIGBUS; int anon_rmap = 0; unsigned long size; struct page *page; pte_t new_pte; spinlock_t *ptl; /* * Currently, we are forced to kill the process in the event the * original mapper has unmapped pages from the child due to a failed * COW. Warn that such a situation has occurred as it may not be obvious */ if (is_vma_resv_set(vma, HPAGE_RESV_UNMAPPED)) { pr_warn_ratelimited("PID %d killed due to inadequate hugepage pool\n", current->pid); return ret; } /* * Use page lock to guard against racing truncation * before we get page_table_lock. */ retry: page = find_lock_page(mapping, idx); if (!page) { size = i_size_read(mapping->host) >> huge_page_shift(h); if (idx >= size) goto out; /* * Check for page in userfault range */ if (userfaultfd_missing(vma)) { u32 hash; struct vm_fault vmf = { .vma = vma, .address = address, .flags = flags, /* * Hard to debug if it ends up being * used by a callee that assumes * something about the other * uninitialized fields... same as in * memory.c */ }; /* * hugetlb_fault_mutex must be dropped before * handling userfault. Reacquire after handling * fault to make calling code simpler. */ hash = hugetlb_fault_mutex_hash(h, mm, vma, mapping, idx, address); mutex_unlock(&hugetlb_fault_mutex_table[hash]); ret = handle_userfault(&vmf, VM_UFFD_MISSING); mutex_lock(&hugetlb_fault_mutex_table[hash]); goto out; } page = alloc_huge_page(vma, address, 0); if (IS_ERR(page)) { ret = PTR_ERR(page); if (ret == -ENOMEM) ret = VM_FAULT_OOM; else ret = VM_FAULT_SIGBUS; goto out; } clear_huge_page(page, address, pages_per_huge_page(h)); __SetPageUptodate(page); set_page_huge_active(page); if (vma->vm_flags & VM_MAYSHARE) { int err = huge_add_to_page_cache(page, mapping, idx); if (err) { put_page(page); if (err == -EEXIST) goto retry; goto out; } } else { lock_page(page); if (unlikely(anon_vma_prepare(vma))) { ret = VM_FAULT_OOM; goto backout_unlocked; } anon_rmap = 1; } } else { /* * If memory error occurs between mmap() and fault, some process * don't have hwpoisoned swap entry for errored virtual address. * So we need to block hugepage fault by PG_hwpoison bit check. */ if (unlikely(PageHWPoison(page))) { ret = VM_FAULT_HWPOISON | VM_FAULT_SET_HINDEX(hstate_index(h)); goto backout_unlocked; } } /* * If we are going to COW a private mapping later, we examine the * pending reservations for this page now. This will ensure that * any allocations necessary to record that reservation occur outside * the spinlock. */ if ((flags & FAULT_FLAG_WRITE) && !(vma->vm_flags & VM_SHARED)) { if (vma_needs_reservation(h, vma, address) < 0) { ret = VM_FAULT_OOM; goto backout_unlocked; } /* Just decrements count, does not deallocate */ vma_end_reservation(h, vma, address); } ptl = huge_pte_lock(h, mm, ptep); size = i_size_read(mapping->host) >> huge_page_shift(h); if (idx >= size) goto backout; ret = 0; if (!huge_pte_none(huge_ptep_get(ptep))) goto backout; if (anon_rmap) { ClearPagePrivate(page); hugepage_add_new_anon_rmap(page, vma, address); } else page_dup_rmap(page, true); new_pte = make_huge_pte(vma, page, ((vma->vm_flags & VM_WRITE) && (vma->vm_flags & VM_SHARED))); set_huge_pte_at(mm, address, ptep, new_pte); hugetlb_count_add(pages_per_huge_page(h), mm); if ((flags & FAULT_FLAG_WRITE) && !(vma->vm_flags & VM_SHARED)) { /* Optimization, do the COW without a second fault */ ret = hugetlb_cow(mm, vma, address, ptep, page, ptl); } spin_unlock(ptl); unlock_page(page); out: return ret; backout: spin_unlock(ptl); backout_unlocked: unlock_page(page); restore_reserve_on_error(h, vma, address, page); put_page(page); goto out; } #ifdef CONFIG_SMP u32 hugetlb_fault_mutex_hash(struct hstate *h, struct mm_struct *mm, struct vm_area_struct *vma, struct address_space *mapping, pgoff_t idx, unsigned long address) { unsigned long key[2]; u32 hash; if (vma->vm_flags & VM_SHARED) { key[0] = (unsigned long) mapping; key[1] = idx; } else { key[0] = (unsigned long) mm; key[1] = address >> huge_page_shift(h); } hash = jhash2((u32 *)&key, sizeof(key)/sizeof(u32), 0); return hash & (num_fault_mutexes - 1); } #else /* * For uniprocesor systems we always use a single mutex, so just * return 0 and avoid the hashing overhead. */ u32 hugetlb_fault_mutex_hash(struct hstate *h, struct mm_struct *mm, struct vm_area_struct *vma, struct address_space *mapping, pgoff_t idx, unsigned long address) { return 0; } #endif int hugetlb_fault(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long address, unsigned int flags) { pte_t *ptep, entry; spinlock_t *ptl; int ret; u32 hash; pgoff_t idx; struct page *page = NULL; struct page *pagecache_page = NULL; struct hstate *h = hstate_vma(vma); struct address_space *mapping; int need_wait_lock = 0; address &= huge_page_mask(h); ptep = huge_pte_offset(mm, address, huge_page_size(h)); if (ptep) { entry = huge_ptep_get(ptep); if (unlikely(is_hugetlb_entry_migration(entry))) { migration_entry_wait_huge(vma, mm, ptep); return 0; } else if (unlikely(is_hugetlb_entry_hwpoisoned(entry))) return VM_FAULT_HWPOISON_LARGE | VM_FAULT_SET_HINDEX(hstate_index(h)); } else { ptep = huge_pte_alloc(mm, address, huge_page_size(h)); if (!ptep) return VM_FAULT_OOM; } mapping = vma->vm_file->f_mapping; idx = vma_hugecache_offset(h, vma, address); /* * Serialize hugepage allocation and instantiation, so that we don't * get spurious allocation failures if two CPUs race to instantiate * the same page in the page cache. */ hash = hugetlb_fault_mutex_hash(h, mm, vma, mapping, idx, address); mutex_lock(&hugetlb_fault_mutex_table[hash]); entry = huge_ptep_get(ptep); if (huge_pte_none(entry)) { ret = hugetlb_no_page(mm, vma, mapping, idx, address, ptep, flags); goto out_mutex; } ret = 0; /* * entry could be a migration/hwpoison entry at this point, so this * check prevents the kernel from going below assuming that we have * a active hugepage in pagecache. This goto expects the 2nd page fault, * and is_hugetlb_entry_(migration|hwpoisoned) check will properly * handle it. */ if (!pte_present(entry)) goto out_mutex; /* * If we are going to COW the mapping later, we examine the pending * reservations for this page now. This will ensure that any * allocations necessary to record that reservation occur outside the * spinlock. For private mappings, we also lookup the pagecache * page now as it is used to determine if a reservation has been * consumed. */ if ((flags & FAULT_FLAG_WRITE) && !huge_pte_write(entry)) { if (vma_needs_reservation(h, vma, address) < 0) { ret = VM_FAULT_OOM; goto out_mutex; } /* Just decrements count, does not deallocate */ vma_end_reservation(h, vma, address); if (!(vma->vm_flags & VM_MAYSHARE)) pagecache_page = hugetlbfs_pagecache_page(h, vma, address); } ptl = huge_pte_lock(h, mm, ptep); /* Check for a racing update before calling hugetlb_cow */ if (unlikely(!pte_same(entry, huge_ptep_get(ptep)))) goto out_ptl; /* * hugetlb_cow() requires page locks of pte_page(entry) and * pagecache_page, so here we need take the former one * when page != pagecache_page or !pagecache_page. */ page = pte_page(entry); if (page != pagecache_page) if (!trylock_page(page)) { need_wait_lock = 1; goto out_ptl; } get_page(page); if (flags & FAULT_FLAG_WRITE) { if (!huge_pte_write(entry)) { ret = hugetlb_cow(mm, vma, address, ptep, pagecache_page, ptl); goto out_put_page; } entry = huge_pte_mkdirty(entry); } entry = pte_mkyoung(entry); if (huge_ptep_set_access_flags(vma, address, ptep, entry, flags & FAULT_FLAG_WRITE)) update_mmu_cache(vma, address, ptep); out_put_page: if (page != pagecache_page) unlock_page(page); put_page(page); out_ptl: spin_unlock(ptl); if (pagecache_page) { unlock_page(pagecache_page); put_page(pagecache_page); } out_mutex: mutex_unlock(&hugetlb_fault_mutex_table[hash]); /* * Generally it's safe to hold refcount during waiting page lock. But * here we just wait to defer the next page fault to avoid busy loop and * the page is not used after unlocked before returning from the current * page fault. So we are safe from accessing freed page, even if we wait * here without taking refcount. */ if (need_wait_lock) wait_on_page_locked(page); return ret; } /* * Used by userfaultfd UFFDIO_COPY. Based on mcopy_atomic_pte with * modifications for huge pages. */ int hugetlb_mcopy_atomic_pte(struct mm_struct *dst_mm, pte_t *dst_pte, struct vm_area_struct *dst_vma, unsigned long dst_addr, unsigned long src_addr, struct page **pagep) { int vm_shared = dst_vma->vm_flags & VM_SHARED; struct hstate *h = hstate_vma(dst_vma); pte_t _dst_pte; spinlock_t *ptl; int ret; struct page *page; if (!*pagep) { ret = -ENOMEM; page = alloc_huge_page(dst_vma, dst_addr, 0); if (IS_ERR(page)) goto out; ret = copy_huge_page_from_user(page, (const void __user *) src_addr, pages_per_huge_page(h), false); /* fallback to copy_from_user outside mmap_sem */ if (unlikely(ret)) { ret = -EFAULT; *pagep = page; /* don't free the page */ goto out; } } else { page = *pagep; *pagep = NULL; } /* * The memory barrier inside __SetPageUptodate makes sure that * preceding stores to the page contents become visible before * the set_pte_at() write. */ __SetPageUptodate(page); set_page_huge_active(page); /* * If shared, add to page cache */ if (vm_shared) { struct address_space *mapping = dst_vma->vm_file->f_mapping; pgoff_t idx = vma_hugecache_offset(h, dst_vma, dst_addr); ret = huge_add_to_page_cache(page, mapping, idx); if (ret) goto out_release_nounlock; } ptl = huge_pte_lockptr(h, dst_mm, dst_pte); spin_lock(ptl); ret = -EEXIST; if (!huge_pte_none(huge_ptep_get(dst_pte))) goto out_release_unlock; if (vm_shared) { page_dup_rmap(page, true); } else { ClearPagePrivate(page); hugepage_add_new_anon_rmap(page, dst_vma, dst_addr); } _dst_pte = make_huge_pte(dst_vma, page, dst_vma->vm_flags & VM_WRITE); if (dst_vma->vm_flags & VM_WRITE) _dst_pte = huge_pte_mkdirty(_dst_pte); _dst_pte = pte_mkyoung(_dst_pte); set_huge_pte_at(dst_mm, dst_addr, dst_pte, _dst_pte); (void)huge_ptep_set_access_flags(dst_vma, dst_addr, dst_pte, _dst_pte, dst_vma->vm_flags & VM_WRITE); hugetlb_count_add(pages_per_huge_page(h), dst_mm); /* No need to invalidate - it was non-present before */ update_mmu_cache(dst_vma, dst_addr, dst_pte); spin_unlock(ptl); if (vm_shared) unlock_page(page); ret = 0; out: return ret; out_release_unlock: spin_unlock(ptl); if (vm_shared) unlock_page(page); out_release_nounlock: put_page(page); goto out; } long follow_hugetlb_page(struct mm_struct *mm, struct vm_area_struct *vma, struct page **pages, struct vm_area_struct **vmas, unsigned long *position, unsigned long *nr_pages, long i, unsigned int flags, int *nonblocking) { unsigned long pfn_offset; unsigned long vaddr = *position; unsigned long remainder = *nr_pages; struct hstate *h = hstate_vma(vma); int err = -EFAULT; while (vaddr < vma->vm_end && remainder) { pte_t *pte; spinlock_t *ptl = NULL; int absent; struct page *page; /* * If we have a pending SIGKILL, don't keep faulting pages and * potentially allocating memory. */ if (unlikely(fatal_signal_pending(current))) { remainder = 0; break; } /* * Some archs (sparc64, sh*) have multiple pte_ts to * each hugepage. We have to make sure we get the * first, for the page indexing below to work. * * Note that page table lock is not held when pte is null. */ pte = huge_pte_offset(mm, vaddr & huge_page_mask(h), huge_page_size(h)); if (pte) ptl = huge_pte_lock(h, mm, pte); absent = !pte || huge_pte_none(huge_ptep_get(pte)); /* * When coredumping, it suits get_dump_page if we just return * an error where there's an empty slot with no huge pagecache * to back it. This way, we avoid allocating a hugepage, and * the sparse dumpfile avoids allocating disk blocks, but its * huge holes still show up with zeroes where they need to be. */ if (absent && (flags & FOLL_DUMP) && !hugetlbfs_pagecache_present(h, vma, vaddr)) { if (pte) spin_unlock(ptl); remainder = 0; break; } /* * We need call hugetlb_fault for both hugepages under migration * (in which case hugetlb_fault waits for the migration,) and * hwpoisoned hugepages (in which case we need to prevent the * caller from accessing to them.) In order to do this, we use * here is_swap_pte instead of is_hugetlb_entry_migration and * is_hugetlb_entry_hwpoisoned. This is because it simply covers * both cases, and because we can't follow correct pages * directly from any kind of swap entries. */ if (absent || is_swap_pte(huge_ptep_get(pte)) || ((flags & FOLL_WRITE) && !huge_pte_write(huge_ptep_get(pte)))) { int ret; unsigned int fault_flags = 0; if (pte) spin_unlock(ptl); if (flags & FOLL_WRITE) fault_flags |= FAULT_FLAG_WRITE; if (nonblocking) fault_flags |= FAULT_FLAG_ALLOW_RETRY; if (flags & FOLL_NOWAIT) fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_RETRY_NOWAIT; if (flags & FOLL_TRIED) { VM_WARN_ON_ONCE(fault_flags & FAULT_FLAG_ALLOW_RETRY); fault_flags |= FAULT_FLAG_TRIED; } ret = hugetlb_fault(mm, vma, vaddr, fault_flags); if (ret & VM_FAULT_ERROR) { err = vm_fault_to_errno(ret, flags); remainder = 0; break; } if (ret & VM_FAULT_RETRY) { if (nonblocking) *nonblocking = 0; *nr_pages = 0; /* * VM_FAULT_RETRY must not return an * error, it will return zero * instead. * * No need to update "position" as the * caller will not check it after * *nr_pages is set to 0. */ return i; } continue; } pfn_offset = (vaddr & ~huge_page_mask(h)) >> PAGE_SHIFT; page = pte_page(huge_ptep_get(pte)); same_page: if (pages) { pages[i] = mem_map_offset(page, pfn_offset); get_page(pages[i]); } if (vmas) vmas[i] = vma; vaddr += PAGE_SIZE; ++pfn_offset; --remainder; ++i; if (vaddr < vma->vm_end && remainder && pfn_offset < pages_per_huge_page(h)) { /* * We use pfn_offset to avoid touching the pageframes * of this compound page. */ goto same_page; } spin_unlock(ptl); } *nr_pages = remainder; /* * setting position is actually required only if remainder is * not zero but it's faster not to add a "if (remainder)" * branch. */ *position = vaddr; return i ? i : err; } #ifndef __HAVE_ARCH_FLUSH_HUGETLB_TLB_RANGE /* * ARCHes with special requirements for evicting HUGETLB backing TLB entries can * implement this. */ #define flush_hugetlb_tlb_range(vma, addr, end) flush_tlb_range(vma, addr, end) #endif unsigned long hugetlb_change_protection(struct vm_area_struct *vma, unsigned long address, unsigned long end, pgprot_t newprot) { struct mm_struct *mm = vma->vm_mm; unsigned long start = address; pte_t *ptep; pte_t pte; struct hstate *h = hstate_vma(vma); unsigned long pages = 0; BUG_ON(address >= end); flush_cache_range(vma, address, end); mmu_notifier_invalidate_range_start(mm, start, end); i_mmap_lock_write(vma->vm_file->f_mapping); for (; address < end; address += huge_page_size(h)) { spinlock_t *ptl; ptep = huge_pte_offset(mm, address, huge_page_size(h)); if (!ptep) continue; ptl = huge_pte_lock(h, mm, ptep); if (huge_pmd_unshare(mm, &address, ptep)) { pages++; spin_unlock(ptl); continue; } pte = huge_ptep_get(ptep); if (unlikely(is_hugetlb_entry_hwpoisoned(pte))) { spin_unlock(ptl); continue; } if (unlikely(is_hugetlb_entry_migration(pte))) { swp_entry_t entry = pte_to_swp_entry(pte); if (is_write_migration_entry(entry)) { pte_t newpte; make_migration_entry_read(&entry); newpte = swp_entry_to_pte(entry); set_huge_swap_pte_at(mm, address, ptep, newpte, huge_page_size(h)); pages++; } spin_unlock(ptl); continue; } if (!huge_pte_none(pte)) { pte = huge_ptep_get_and_clear(mm, address, ptep); pte = pte_mkhuge(huge_pte_modify(pte, newprot)); pte = arch_make_huge_pte(pte, vma, NULL, 0); set_huge_pte_at(mm, address, ptep, pte); pages++; } spin_unlock(ptl); } /* * Must flush TLB before releasing i_mmap_rwsem: x86's huge_pmd_unshare * may have cleared our pud entry and done put_page on the page table: * once we release i_mmap_rwsem, another task can do the final put_page * and that page table be reused and filled with junk. */ flush_hugetlb_tlb_range(vma, start, end); mmu_notifier_invalidate_range(mm, start, end); i_mmap_unlock_write(vma->vm_file->f_mapping); mmu_notifier_invalidate_range_end(mm, start, end); return pages << h->order; } int hugetlb_reserve_pages(struct inode *inode, long from, long to, struct vm_area_struct *vma, vm_flags_t vm_flags) { long ret, chg; struct hstate *h = hstate_inode(inode); struct hugepage_subpool *spool = subpool_inode(inode); struct resv_map *resv_map; long gbl_reserve; /* * Only apply hugepage reservation if asked. At fault time, an * attempt will be made for VM_NORESERVE to allocate a page * without using reserves */ if (vm_flags & VM_NORESERVE) return 0; /* * Shared mappings base their reservation on the number of pages that * are already allocated on behalf of the file. Private mappings need * to reserve the full area even if read-only as mprotect() may be * called to make the mapping read-write. Assume !vma is a shm mapping */ if (!vma || vma->vm_flags & VM_MAYSHARE) { resv_map = inode_resv_map(inode); chg = region_chg(resv_map, from, to); } else { resv_map = resv_map_alloc(); if (!resv_map) return -ENOMEM; chg = to - from; set_vma_resv_map(vma, resv_map); set_vma_resv_flags(vma, HPAGE_RESV_OWNER); } if (chg < 0) { ret = chg; goto out_err; } /* * There must be enough pages in the subpool for the mapping. If * the subpool has a minimum size, there may be some global * reservations already in place (gbl_reserve). */ gbl_reserve = hugepage_subpool_get_pages(spool, chg); if (gbl_reserve < 0) { ret = -ENOSPC; goto out_err; } /* * Check enough hugepages are available for the reservation. * Hand the pages back to the subpool if there are not */ ret = hugetlb_acct_memory(h, gbl_reserve); if (ret < 0) { /* put back original number of pages, chg */ (void)hugepage_subpool_put_pages(spool, chg); goto out_err; } /* * Account for the reservations made. Shared mappings record regions * that have reservations as they are shared by multiple VMAs. * When the last VMA disappears, the region map says how much * the reservation was and the page cache tells how much of * the reservation was consumed. Private mappings are per-VMA and * only the consumed reservations are tracked. When the VMA * disappears, the original reservation is the VMA size and the * consumed reservations are stored in the map. Hence, nothing * else has to be done for private mappings here */ if (!vma || vma->vm_flags & VM_MAYSHARE) { long add = region_add(resv_map, from, to); if (unlikely(chg > add)) { /* * pages in this range were added to the reserve * map between region_chg and region_add. This * indicates a race with alloc_huge_page. Adjust * the subpool and reserve counts modified above * based on the difference. */ long rsv_adjust; rsv_adjust = hugepage_subpool_put_pages(spool, chg - add); hugetlb_acct_memory(h, -rsv_adjust); } } return 0; out_err: if (!vma || vma->vm_flags & VM_MAYSHARE) /* Don't call region_abort if region_chg failed */ if (chg >= 0) region_abort(resv_map, from, to); if (vma && is_vma_resv_set(vma, HPAGE_RESV_OWNER)) kref_put(&resv_map->refs, resv_map_release); return ret; } long hugetlb_unreserve_pages(struct inode *inode, long start, long end, long freed) { struct hstate *h = hstate_inode(inode); struct resv_map *resv_map = inode_resv_map(inode); long chg = 0; struct hugepage_subpool *spool = subpool_inode(inode); long gbl_reserve; if (resv_map) { chg = region_del(resv_map, start, end); /* * region_del() can fail in the rare case where a region * must be split and another region descriptor can not be * allocated. If end == LONG_MAX, it will not fail. */ if (chg < 0) return chg; } spin_lock(&inode->i_lock); inode->i_blocks -= (blocks_per_huge_page(h) * freed); spin_unlock(&inode->i_lock); /* * If the subpool has a minimum size, the number of global * reservations to be released may be adjusted. */ gbl_reserve = hugepage_subpool_put_pages(spool, (chg - freed)); hugetlb_acct_memory(h, -gbl_reserve); return 0; } #ifdef CONFIG_ARCH_WANT_HUGE_PMD_SHARE static unsigned long page_table_shareable(struct vm_area_struct *svma, struct vm_area_struct *vma, unsigned long addr, pgoff_t idx) { unsigned long saddr = ((idx - svma->vm_pgoff) << PAGE_SHIFT) + svma->vm_start; unsigned long sbase = saddr & PUD_MASK; unsigned long s_end = sbase + PUD_SIZE; /* Allow segments to share if only one is marked locked */ unsigned long vm_flags = vma->vm_flags & VM_LOCKED_CLEAR_MASK; unsigned long svm_flags = svma->vm_flags & VM_LOCKED_CLEAR_MASK; /* * match the virtual addresses, permission and the alignment of the * page table page. */ if (pmd_index(addr) != pmd_index(saddr) || vm_flags != svm_flags || sbase < svma->vm_start || svma->vm_end < s_end) return 0; return saddr; } static bool vma_shareable(struct vm_area_struct *vma, unsigned long addr) { unsigned long base = addr & PUD_MASK; unsigned long end = base + PUD_SIZE; /* * check on proper vm_flags and page table alignment */ if (vma->vm_flags & VM_MAYSHARE && vma->vm_start <= base && end <= vma->vm_end) return true; return false; } /* * Search for a shareable pmd page for hugetlb. In any case calls pmd_alloc() * and returns the corresponding pte. While this is not necessary for the * !shared pmd case because we can allocate the pmd later as well, it makes the * code much cleaner. pmd allocation is essential for the shared case because * pud has to be populated inside the same i_mmap_rwsem section - otherwise * racing tasks could either miss the sharing (see huge_pte_offset) or select a * bad pmd for sharing. */ pte_t *huge_pmd_share(struct mm_struct *mm, unsigned long addr, pud_t *pud) { struct vm_area_struct *vma = find_vma(mm, addr); struct address_space *mapping = vma->vm_file->f_mapping; pgoff_t idx = ((addr - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff; struct vm_area_struct *svma; unsigned long saddr; pte_t *spte = NULL; pte_t *pte; spinlock_t *ptl; if (!vma_shareable(vma, addr)) return (pte_t *)pmd_alloc(mm, pud, addr); i_mmap_lock_write(mapping); vma_interval_tree_foreach(svma, &mapping->i_mmap, idx, idx) { if (svma == vma) continue; saddr = page_table_shareable(svma, vma, addr, idx); if (saddr) { spte = huge_pte_offset(svma->vm_mm, saddr, vma_mmu_pagesize(svma)); if (spte) { get_page(virt_to_page(spte)); break; } } } if (!spte) goto out; ptl = huge_pte_lock(hstate_vma(vma), mm, spte); if (pud_none(*pud)) { pud_populate(mm, pud, (pmd_t *)((unsigned long)spte & PAGE_MASK)); mm_inc_nr_pmds(mm); } else { put_page(virt_to_page(spte)); } spin_unlock(ptl); out: pte = (pte_t *)pmd_alloc(mm, pud, addr); i_mmap_unlock_write(mapping); return pte; } /* * unmap huge page backed by shared pte. * * Hugetlb pte page is ref counted at the time of mapping. If pte is shared * indicated by page_count > 1, unmap is achieved by clearing pud and * decrementing the ref count. If count == 1, the pte page is not shared. * * called with page table lock held. * * returns: 1 successfully unmapped a shared pte page * 0 the underlying pte page is not shared, or it is the last user */ int huge_pmd_unshare(struct mm_struct *mm, unsigned long *addr, pte_t *ptep) { pgd_t *pgd = pgd_offset(mm, *addr); p4d_t *p4d = p4d_offset(pgd, *addr); pud_t *pud = pud_offset(p4d, *addr); BUG_ON(page_count(virt_to_page(ptep)) == 0); if (page_count(virt_to_page(ptep)) == 1) return 0; pud_clear(pud); put_page(virt_to_page(ptep)); mm_dec_nr_pmds(mm); *addr = ALIGN(*addr, HPAGE_SIZE * PTRS_PER_PTE) - HPAGE_SIZE; return 1; } #define want_pmd_share() (1) #else /* !CONFIG_ARCH_WANT_HUGE_PMD_SHARE */ pte_t *huge_pmd_share(struct mm_struct *mm, unsigned long addr, pud_t *pud) { return NULL; } int huge_pmd_unshare(struct mm_struct *mm, unsigned long *addr, pte_t *ptep) { return 0; } #define want_pmd_share() (0) #endif /* CONFIG_ARCH_WANT_HUGE_PMD_SHARE */ #ifdef CONFIG_ARCH_WANT_GENERAL_HUGETLB pte_t *huge_pte_alloc(struct mm_struct *mm, unsigned long addr, unsigned long sz) { pgd_t *pgd; p4d_t *p4d; pud_t *pud; pte_t *pte = NULL; pgd = pgd_offset(mm, addr); p4d = p4d_offset(pgd, addr); pud = pud_alloc(mm, p4d, addr); if (pud) { if (sz == PUD_SIZE) { pte = (pte_t *)pud; } else { BUG_ON(sz != PMD_SIZE); if (want_pmd_share() && pud_none(*pud)) pte = huge_pmd_share(mm, addr, pud); else pte = (pte_t *)pmd_alloc(mm, pud, addr); } } BUG_ON(pte && pte_present(*pte) && !pte_huge(*pte)); return pte; } /* * huge_pte_offset() - Walk the page table to resolve the hugepage * entry at address @addr * * Return: Pointer to page table or swap entry (PUD or PMD) for * address @addr, or NULL if a p*d_none() entry is encountered and the * size @sz doesn't match the hugepage size at this level of the page * table. */ pte_t *huge_pte_offset(struct mm_struct *mm, unsigned long addr, unsigned long sz) { pgd_t *pgd; p4d_t *p4d; pud_t *pud; pmd_t *pmd; pgd = pgd_offset(mm, addr); if (!pgd_present(*pgd)) return NULL; p4d = p4d_offset(pgd, addr); if (!p4d_present(*p4d)) return NULL; pud = pud_offset(p4d, addr); if (sz != PUD_SIZE && pud_none(*pud)) return NULL; /* hugepage or swap? */ if (pud_huge(*pud) || !pud_present(*pud)) return (pte_t *)pud; pmd = pmd_offset(pud, addr); if (sz != PMD_SIZE && pmd_none(*pmd)) return NULL; /* hugepage or swap? */ if (pmd_huge(*pmd) || !pmd_present(*pmd)) return (pte_t *)pmd; return NULL; } #endif /* CONFIG_ARCH_WANT_GENERAL_HUGETLB */ /* * These functions are overwritable if your architecture needs its own * behavior. */ struct page * __weak follow_huge_addr(struct mm_struct *mm, unsigned long address, int write) { return ERR_PTR(-EINVAL); } struct page * __weak follow_huge_pd(struct vm_area_struct *vma, unsigned long address, hugepd_t hpd, int flags, int pdshift) { WARN(1, "hugepd follow called with no support for hugepage directory format\n"); return NULL; } struct page * __weak follow_huge_pmd(struct mm_struct *mm, unsigned long address, pmd_t *pmd, int flags) { struct page *page = NULL; spinlock_t *ptl; pte_t pte; retry: ptl = pmd_lockptr(mm, pmd); spin_lock(ptl); /* * make sure that the address range covered by this pmd is not * unmapped from other threads. */ if (!pmd_huge(*pmd)) goto out; pte = huge_ptep_get((pte_t *)pmd); if (pte_present(pte)) { page = pmd_page(*pmd) + ((address & ~PMD_MASK) >> PAGE_SHIFT); if (flags & FOLL_GET) get_page(page); } else { if (is_hugetlb_entry_migration(pte)) { spin_unlock(ptl); __migration_entry_wait(mm, (pte_t *)pmd, ptl); goto retry; } /* * hwpoisoned entry is treated as no_page_table in * follow_page_mask(). */ } out: spin_unlock(ptl); return page; } struct page * __weak follow_huge_pud(struct mm_struct *mm, unsigned long address, pud_t *pud, int flags) { if (flags & FOLL_GET) return NULL; return pte_page(*(pte_t *)pud) + ((address & ~PUD_MASK) >> PAGE_SHIFT); } struct page * __weak follow_huge_pgd(struct mm_struct *mm, unsigned long address, pgd_t *pgd, int flags) { if (flags & FOLL_GET) return NULL; return pte_page(*(pte_t *)pgd) + ((address & ~PGDIR_MASK) >> PAGE_SHIFT); } bool isolate_huge_page(struct page *page, struct list_head *list) { bool ret = true; VM_BUG_ON_PAGE(!PageHead(page), page); spin_lock(&hugetlb_lock); if (!page_huge_active(page) || !get_page_unless_zero(page)) { ret = false; goto unlock; } clear_page_huge_active(page); list_move_tail(&page->lru, list); unlock: spin_unlock(&hugetlb_lock); return ret; } void putback_active_hugepage(struct page *page) { VM_BUG_ON_PAGE(!PageHead(page), page); spin_lock(&hugetlb_lock); set_page_huge_active(page); list_move_tail(&page->lru, &(page_hstate(page))->hugepage_activelist); spin_unlock(&hugetlb_lock); put_page(page); }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_2842_0
crossvul-cpp_data_bad_5815_0
/* * FFV1 decoder * * Copyright (c) 2003-2013 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 * FF Video Codec 1 (a lossless codec) decoder */ #include "libavutil/avassert.h" #include "libavutil/crc.h" #include "libavutil/opt.h" #include "libavutil/imgutils.h" #include "libavutil/pixdesc.h" #include "libavutil/timer.h" #include "avcodec.h" #include "internal.h" #include "get_bits.h" #include "rangecoder.h" #include "golomb.h" #include "mathops.h" #include "ffv1.h" static inline av_flatten int get_symbol_inline(RangeCoder *c, uint8_t *state, int is_signed) { if (get_rac(c, state + 0)) return 0; else { int i, e, a; e = 0; while (get_rac(c, state + 1 + FFMIN(e, 9))) // 1..10 e++; a = 1; for (i = e - 1; i >= 0; i--) a += a + get_rac(c, state + 22 + FFMIN(i, 9)); // 22..31 e = -(is_signed && get_rac(c, state + 11 + FFMIN(e, 10))); // 11..21 return (a ^ e) - e; } } static av_noinline int get_symbol(RangeCoder *c, uint8_t *state, int is_signed) { return get_symbol_inline(c, state, is_signed); } static inline int get_vlc_symbol(GetBitContext *gb, VlcState *const state, int bits) { int k, i, v, ret; i = state->count; k = 0; while (i < state->error_sum) { // FIXME: optimize k++; i += i; } v = get_sr_golomb(gb, k, 12, bits); av_dlog(NULL, "v:%d bias:%d error:%d drift:%d count:%d k:%d", v, state->bias, state->error_sum, state->drift, state->count, k); #if 0 // JPEG LS if (k == 0 && 2 * state->drift <= -state->count) v ^= (-1); #else v ^= ((2 * state->drift + state->count) >> 31); #endif ret = fold(v + state->bias, bits); update_vlc_state(state, v); return ret; } static av_always_inline void decode_line(FFV1Context *s, int w, int16_t *sample[2], int plane_index, int bits) { PlaneContext *const p = &s->plane[plane_index]; RangeCoder *const c = &s->c; int x; int run_count = 0; int run_mode = 0; int run_index = s->run_index; for (x = 0; x < w; x++) { int diff, context, sign; context = get_context(p, sample[1] + x, sample[0] + x, sample[1] + x); if (context < 0) { context = -context; sign = 1; } else sign = 0; av_assert2(context < p->context_count); if (s->ac) { diff = get_symbol_inline(c, p->state[context], 1); } else { if (context == 0 && run_mode == 0) run_mode = 1; if (run_mode) { if (run_count == 0 && run_mode == 1) { if (get_bits1(&s->gb)) { run_count = 1 << ff_log2_run[run_index]; if (x + run_count <= w) run_index++; } else { if (ff_log2_run[run_index]) run_count = get_bits(&s->gb, ff_log2_run[run_index]); else run_count = 0; if (run_index) run_index--; run_mode = 2; } } run_count--; if (run_count < 0) { run_mode = 0; run_count = 0; diff = get_vlc_symbol(&s->gb, &p->vlc_state[context], bits); if (diff >= 0) diff++; } else diff = 0; } else diff = get_vlc_symbol(&s->gb, &p->vlc_state[context], bits); av_dlog(s->avctx, "count:%d index:%d, mode:%d, x:%d pos:%d\n", run_count, run_index, run_mode, x, get_bits_count(&s->gb)); } if (sign) diff = -diff; sample[1][x] = (predict(sample[1] + x, sample[0] + x) + diff) & ((1 << bits) - 1); } s->run_index = run_index; } static void decode_plane(FFV1Context *s, uint8_t *src, int w, int h, int stride, int plane_index) { int x, y; int16_t *sample[2]; sample[0] = s->sample_buffer + 3; sample[1] = s->sample_buffer + w + 6 + 3; s->run_index = 0; memset(s->sample_buffer, 0, 2 * (w + 6) * sizeof(*s->sample_buffer)); for (y = 0; y < h; y++) { int16_t *temp = sample[0]; // FIXME: try a normal buffer sample[0] = sample[1]; sample[1] = temp; sample[1][-1] = sample[0][0]; sample[0][w] = sample[0][w - 1]; // { START_TIMER if (s->avctx->bits_per_raw_sample <= 8) { decode_line(s, w, sample, plane_index, 8); for (x = 0; x < w; x++) src[x + stride * y] = sample[1][x]; } else { decode_line(s, w, sample, plane_index, s->avctx->bits_per_raw_sample); if (s->packed_at_lsb) { for (x = 0; x < w; x++) { ((uint16_t*)(src + stride*y))[x] = sample[1][x]; } } else { for (x = 0; x < w; x++) { ((uint16_t*)(src + stride*y))[x] = sample[1][x] << (16 - s->avctx->bits_per_raw_sample); } } } // STOP_TIMER("decode-line") } } } static void decode_rgb_frame(FFV1Context *s, uint8_t *src[3], int w, int h, int stride[3]) { int x, y, p; int16_t *sample[4][2]; int lbd = s->avctx->bits_per_raw_sample <= 8; int bits = s->avctx->bits_per_raw_sample > 0 ? s->avctx->bits_per_raw_sample : 8; int offset = 1 << bits; for (x = 0; x < 4; x++) { sample[x][0] = s->sample_buffer + x * 2 * (w + 6) + 3; sample[x][1] = s->sample_buffer + (x * 2 + 1) * (w + 6) + 3; } s->run_index = 0; memset(s->sample_buffer, 0, 8 * (w + 6) * sizeof(*s->sample_buffer)); for (y = 0; y < h; y++) { for (p = 0; p < 3 + s->transparency; p++) { int16_t *temp = sample[p][0]; // FIXME: try a normal buffer sample[p][0] = sample[p][1]; sample[p][1] = temp; sample[p][1][-1]= sample[p][0][0 ]; sample[p][0][ w]= sample[p][0][w-1]; if (lbd) decode_line(s, w, sample[p], (p + 1)/2, 9); else decode_line(s, w, sample[p], (p + 1)/2, bits + 1); } for (x = 0; x < w; x++) { int g = sample[0][1][x]; int b = sample[1][1][x]; int r = sample[2][1][x]; int a = sample[3][1][x]; b -= offset; r -= offset; g -= (b + r) >> 2; b += g; r += g; if (lbd) *((uint32_t*)(src[0] + x*4 + stride[0]*y)) = b + (g<<8) + (r<<16) + (a<<24); else { *((uint16_t*)(src[0] + x*2 + stride[0]*y)) = b; *((uint16_t*)(src[1] + x*2 + stride[1]*y)) = g; *((uint16_t*)(src[2] + x*2 + stride[2]*y)) = r; } } } } static int decode_slice_header(FFV1Context *f, FFV1Context *fs) { RangeCoder *c = &fs->c; uint8_t state[CONTEXT_SIZE]; unsigned ps, i, context_count; memset(state, 128, sizeof(state)); av_assert0(f->version > 2); fs->slice_x = get_symbol(c, state, 0) * f->width ; fs->slice_y = get_symbol(c, state, 0) * f->height; fs->slice_width = (get_symbol(c, state, 0) + 1) * f->width + fs->slice_x; fs->slice_height = (get_symbol(c, state, 0) + 1) * f->height + fs->slice_y; fs->slice_x /= f->num_h_slices; fs->slice_y /= f->num_v_slices; fs->slice_width = fs->slice_width /f->num_h_slices - fs->slice_x; fs->slice_height = fs->slice_height/f->num_v_slices - fs->slice_y; if ((unsigned)fs->slice_width > f->width || (unsigned)fs->slice_height > f->height) return -1; if ( (unsigned)fs->slice_x + (uint64_t)fs->slice_width > f->width || (unsigned)fs->slice_y + (uint64_t)fs->slice_height > f->height) return -1; for (i = 0; i < f->plane_count; i++) { PlaneContext * const p = &fs->plane[i]; int idx = get_symbol(c, state, 0); if (idx > (unsigned)f->quant_table_count) { av_log(f->avctx, AV_LOG_ERROR, "quant_table_index out of range\n"); return -1; } p->quant_table_index = idx; memcpy(p->quant_table, f->quant_tables[idx], sizeof(p->quant_table)); context_count = f->context_count[idx]; if (p->context_count < context_count) { av_freep(&p->state); av_freep(&p->vlc_state); } p->context_count = context_count; } ps = get_symbol(c, state, 0); if (ps == 1) { f->cur->interlaced_frame = 1; f->cur->top_field_first = 1; } else if (ps == 2) { f->cur->interlaced_frame = 1; f->cur->top_field_first = 0; } else if (ps == 3) { f->cur->interlaced_frame = 0; } f->cur->sample_aspect_ratio.num = get_symbol(c, state, 0); f->cur->sample_aspect_ratio.den = get_symbol(c, state, 0); return 0; } static int decode_slice(AVCodecContext *c, void *arg) { FFV1Context *fs = *(void **)arg; FFV1Context *f = fs->avctx->priv_data; int width, height, x, y, ret; const int ps = av_pix_fmt_desc_get(c->pix_fmt)->comp[0].step_minus1 + 1; AVFrame * const p = f->cur; int i, si; for( si=0; fs != f->slice_context[si]; si ++) ; if(f->fsrc && !p->key_frame) ff_thread_await_progress(&f->last_picture, si, 0); if(f->fsrc && !p->key_frame) { FFV1Context *fssrc = f->fsrc->slice_context[si]; FFV1Context *fsdst = f->slice_context[si]; av_assert1(fsdst->plane_count == fssrc->plane_count); av_assert1(fsdst == fs); if (!p->key_frame) fsdst->slice_damaged |= fssrc->slice_damaged; for (i = 0; i < f->plane_count; i++) { PlaneContext *psrc = &fssrc->plane[i]; PlaneContext *pdst = &fsdst->plane[i]; av_free(pdst->state); av_free(pdst->vlc_state); memcpy(pdst, psrc, sizeof(*pdst)); pdst->state = NULL; pdst->vlc_state = NULL; if (fssrc->ac) { pdst->state = av_malloc(CONTEXT_SIZE * psrc->context_count); memcpy(pdst->state, psrc->state, CONTEXT_SIZE * psrc->context_count); } else { pdst->vlc_state = av_malloc(sizeof(*pdst->vlc_state) * psrc->context_count); memcpy(pdst->vlc_state, psrc->vlc_state, sizeof(*pdst->vlc_state) * psrc->context_count); } } } if (f->version > 2) { if (ffv1_init_slice_state(f, fs) < 0) return AVERROR(ENOMEM); if (decode_slice_header(f, fs) < 0) { fs->slice_damaged = 1; return AVERROR_INVALIDDATA; } } if ((ret = ffv1_init_slice_state(f, fs)) < 0) return ret; if (f->cur->key_frame) ffv1_clear_slice_state(f, fs); width = fs->slice_width; height = fs->slice_height; x = fs->slice_x; y = fs->slice_y; if (!fs->ac) { if (f->version == 3 && f->micro_version > 1 || f->version > 3) get_rac(&fs->c, (uint8_t[]) { 129 }); fs->ac_byte_count = f->version > 2 || (!x && !y) ? fs->c.bytestream - fs->c.bytestream_start - 1 : 0; init_get_bits(&fs->gb, fs->c.bytestream_start + fs->ac_byte_count, (fs->c.bytestream_end - fs->c.bytestream_start - fs->ac_byte_count) * 8); } av_assert1(width && height); if (f->colorspace == 0) { const int chroma_width = FF_CEIL_RSHIFT(width, f->chroma_h_shift); const int chroma_height = FF_CEIL_RSHIFT(height, f->chroma_v_shift); const int cx = x >> f->chroma_h_shift; const int cy = y >> f->chroma_v_shift; decode_plane(fs, p->data[0] + ps*x + y*p->linesize[0], width, height, p->linesize[0], 0); if (f->chroma_planes) { decode_plane(fs, p->data[1] + ps*cx+cy*p->linesize[1], chroma_width, chroma_height, p->linesize[1], 1); decode_plane(fs, p->data[2] + ps*cx+cy*p->linesize[2], chroma_width, chroma_height, p->linesize[2], 1); } if (fs->transparency) decode_plane(fs, p->data[3] + ps*x + y*p->linesize[3], width, height, p->linesize[3], 2); } else { uint8_t *planes[3] = { p->data[0] + ps * x + y * p->linesize[0], p->data[1] + ps * x + y * p->linesize[1], p->data[2] + ps * x + y * p->linesize[2] }; decode_rgb_frame(fs, planes, width, height, p->linesize); } if (fs->ac && f->version > 2) { int v; get_rac(&fs->c, (uint8_t[]) { 129 }); v = fs->c.bytestream_end - fs->c.bytestream - 2 - 5*f->ec; if (v) { av_log(f->avctx, AV_LOG_ERROR, "bytestream end mismatching by %d\n", v); fs->slice_damaged = 1; } } emms_c(); ff_thread_report_progress(&f->picture, si, 0); return 0; } static int read_quant_table(RangeCoder *c, int16_t *quant_table, int scale) { int v; int i = 0; uint8_t state[CONTEXT_SIZE]; memset(state, 128, sizeof(state)); for (v = 0; i < 128; v++) { unsigned len = get_symbol(c, state, 0) + 1; if (len > 128 - i) return AVERROR_INVALIDDATA; while (len--) { quant_table[i] = scale * v; i++; } } for (i = 1; i < 128; i++) quant_table[256 - i] = -quant_table[i]; quant_table[128] = -quant_table[127]; return 2 * v - 1; } static int read_quant_tables(RangeCoder *c, int16_t quant_table[MAX_CONTEXT_INPUTS][256]) { int i; int context_count = 1; for (i = 0; i < 5; i++) { context_count *= read_quant_table(c, quant_table[i], context_count); if (context_count > 32768U) { return AVERROR_INVALIDDATA; } } return (context_count + 1) / 2; } static int read_extra_header(FFV1Context *f) { RangeCoder *const c = &f->c; uint8_t state[CONTEXT_SIZE]; int i, j, k, ret; uint8_t state2[32][CONTEXT_SIZE]; memset(state2, 128, sizeof(state2)); memset(state, 128, sizeof(state)); ff_init_range_decoder(c, f->avctx->extradata, f->avctx->extradata_size); ff_build_rac_states(c, 0.05 * (1LL << 32), 256 - 8); f->version = get_symbol(c, state, 0); if (f->version < 2) { av_log(f->avctx, AV_LOG_ERROR, "Invalid version in global header\n"); return AVERROR_INVALIDDATA; } if (f->version > 2) { c->bytestream_end -= 4; f->micro_version = get_symbol(c, state, 0); } f->ac = f->avctx->coder_type = get_symbol(c, state, 0); if (f->ac > 1) { for (i = 1; i < 256; i++) f->state_transition[i] = get_symbol(c, state, 1) + c->one_state[i]; } f->colorspace = get_symbol(c, state, 0); //YUV cs type f->avctx->bits_per_raw_sample = get_symbol(c, state, 0); f->chroma_planes = get_rac(c, state); f->chroma_h_shift = get_symbol(c, state, 0); f->chroma_v_shift = get_symbol(c, state, 0); f->transparency = get_rac(c, state); f->plane_count = 1 + (f->chroma_planes || f->version<4) + f->transparency; f->num_h_slices = 1 + get_symbol(c, state, 0); f->num_v_slices = 1 + get_symbol(c, state, 0); if (f->num_h_slices > (unsigned)f->width || !f->num_h_slices || f->num_v_slices > (unsigned)f->height || !f->num_v_slices ) { av_log(f->avctx, AV_LOG_ERROR, "slice count invalid\n"); return AVERROR_INVALIDDATA; } f->quant_table_count = get_symbol(c, state, 0); if (f->quant_table_count > (unsigned)MAX_QUANT_TABLES) return AVERROR_INVALIDDATA; for (i = 0; i < f->quant_table_count; i++) { f->context_count[i] = read_quant_tables(c, f->quant_tables[i]); if (f->context_count[i] < 0) { av_log(f->avctx, AV_LOG_ERROR, "read_quant_table error\n"); return AVERROR_INVALIDDATA; } } if ((ret = ffv1_allocate_initial_states(f)) < 0) return ret; for (i = 0; i < f->quant_table_count; i++) if (get_rac(c, state)) { for (j = 0; j < f->context_count[i]; j++) for (k = 0; k < CONTEXT_SIZE; k++) { int pred = j ? f->initial_states[i][j - 1][k] : 128; f->initial_states[i][j][k] = (pred + get_symbol(c, state2[k], 1)) & 0xFF; } } if (f->version > 2) { f->ec = get_symbol(c, state, 0); if (f->micro_version > 2) f->intra = get_symbol(c, state, 0); } if (f->version > 2) { unsigned v; v = av_crc(av_crc_get_table(AV_CRC_32_IEEE), 0, f->avctx->extradata, f->avctx->extradata_size); if (v) { av_log(f->avctx, AV_LOG_ERROR, "CRC mismatch %X!\n", v); return AVERROR_INVALIDDATA; } } if (f->avctx->debug & FF_DEBUG_PICT_INFO) av_log(f->avctx, AV_LOG_DEBUG, "global: ver:%d.%d, coder:%d, colorspace: %d bpr:%d chroma:%d(%d:%d), alpha:%d slices:%dx%d qtabs:%d ec:%d intra:%d\n", f->version, f->micro_version, f->ac, f->colorspace, f->avctx->bits_per_raw_sample, f->chroma_planes, f->chroma_h_shift, f->chroma_v_shift, f->transparency, f->num_h_slices, f->num_v_slices, f->quant_table_count, f->ec, f->intra ); return 0; } static int read_header(FFV1Context *f) { uint8_t state[CONTEXT_SIZE]; int i, j, context_count = -1; //-1 to avoid warning RangeCoder *const c = &f->slice_context[0]->c; memset(state, 128, sizeof(state)); if (f->version < 2) { unsigned v= get_symbol(c, state, 0); if (v >= 2) { av_log(f->avctx, AV_LOG_ERROR, "invalid version %d in ver01 header\n", v); return AVERROR_INVALIDDATA; } f->version = v; f->ac = f->avctx->coder_type = get_symbol(c, state, 0); if (f->ac > 1) { for (i = 1; i < 256; i++) f->state_transition[i] = get_symbol(c, state, 1) + c->one_state[i]; } f->colorspace = get_symbol(c, state, 0); //YUV cs type if (f->version > 0) f->avctx->bits_per_raw_sample = get_symbol(c, state, 0); f->chroma_planes = get_rac(c, state); f->chroma_h_shift = get_symbol(c, state, 0); f->chroma_v_shift = get_symbol(c, state, 0); f->transparency = get_rac(c, state); f->plane_count = 2 + f->transparency; } if (f->colorspace == 0) { if (!f->transparency && !f->chroma_planes) { if (f->avctx->bits_per_raw_sample <= 8) f->avctx->pix_fmt = AV_PIX_FMT_GRAY8; else f->avctx->pix_fmt = AV_PIX_FMT_GRAY16; } else if (f->avctx->bits_per_raw_sample<=8 && !f->transparency) { switch(16 * f->chroma_h_shift + f->chroma_v_shift) { case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUV444P; break; case 0x01: f->avctx->pix_fmt = AV_PIX_FMT_YUV440P; break; case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUV422P; break; case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUV420P; break; case 0x20: f->avctx->pix_fmt = AV_PIX_FMT_YUV411P; break; case 0x22: f->avctx->pix_fmt = AV_PIX_FMT_YUV410P; break; default: av_log(f->avctx, AV_LOG_ERROR, "format not supported\n"); return AVERROR(ENOSYS); } } else if (f->avctx->bits_per_raw_sample <= 8 && f->transparency) { switch(16*f->chroma_h_shift + f->chroma_v_shift) { case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUVA444P; break; case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUVA422P; break; case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUVA420P; break; default: av_log(f->avctx, AV_LOG_ERROR, "format not supported\n"); return AVERROR(ENOSYS); } } else if (f->avctx->bits_per_raw_sample == 9) { f->packed_at_lsb = 1; switch(16 * f->chroma_h_shift + f->chroma_v_shift) { case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUV444P9; break; case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUV422P9; break; case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUV420P9; break; default: av_log(f->avctx, AV_LOG_ERROR, "format not supported\n"); return AVERROR(ENOSYS); } } else if (f->avctx->bits_per_raw_sample == 10) { f->packed_at_lsb = 1; switch(16 * f->chroma_h_shift + f->chroma_v_shift) { case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUV444P10; break; case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUV422P10; break; case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUV420P10; break; default: av_log(f->avctx, AV_LOG_ERROR, "format not supported\n"); return AVERROR(ENOSYS); } } else { switch(16 * f->chroma_h_shift + f->chroma_v_shift) { case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUV444P16; break; case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUV422P16; break; case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUV420P16; break; default: av_log(f->avctx, AV_LOG_ERROR, "format not supported\n"); return AVERROR(ENOSYS); } } } else if (f->colorspace == 1) { if (f->chroma_h_shift || f->chroma_v_shift) { av_log(f->avctx, AV_LOG_ERROR, "chroma subsampling not supported in this colorspace\n"); return AVERROR(ENOSYS); } if ( f->avctx->bits_per_raw_sample == 9) f->avctx->pix_fmt = AV_PIX_FMT_GBRP9; else if (f->avctx->bits_per_raw_sample == 10) f->avctx->pix_fmt = AV_PIX_FMT_GBRP10; else if (f->avctx->bits_per_raw_sample == 12) f->avctx->pix_fmt = AV_PIX_FMT_GBRP12; else if (f->avctx->bits_per_raw_sample == 14) f->avctx->pix_fmt = AV_PIX_FMT_GBRP14; else if (f->transparency) f->avctx->pix_fmt = AV_PIX_FMT_RGB32; else f->avctx->pix_fmt = AV_PIX_FMT_0RGB32; } else { av_log(f->avctx, AV_LOG_ERROR, "colorspace not supported\n"); return AVERROR(ENOSYS); } av_dlog(f->avctx, "%d %d %d\n", f->chroma_h_shift, f->chroma_v_shift, f->avctx->pix_fmt); if (f->version < 2) { context_count = read_quant_tables(c, f->quant_table); if (context_count < 0) { av_log(f->avctx, AV_LOG_ERROR, "read_quant_table error\n"); return AVERROR_INVALIDDATA; } } else if (f->version < 3) { f->slice_count = get_symbol(c, state, 0); } else { const uint8_t *p = c->bytestream_end; for (f->slice_count = 0; f->slice_count < MAX_SLICES && 3 < p - c->bytestream_start; f->slice_count++) { int trailer = 3 + 5*!!f->ec; int size = AV_RB24(p-trailer); if (size + trailer > p - c->bytestream_start) break; p -= size + trailer; } } if (f->slice_count > (unsigned)MAX_SLICES || f->slice_count <= 0) { av_log(f->avctx, AV_LOG_ERROR, "slice count %d is invalid\n", f->slice_count); return AVERROR_INVALIDDATA; } for (j = 0; j < f->slice_count; j++) { FFV1Context *fs = f->slice_context[j]; fs->ac = f->ac; fs->packed_at_lsb = f->packed_at_lsb; fs->slice_damaged = 0; if (f->version == 2) { fs->slice_x = get_symbol(c, state, 0) * f->width ; fs->slice_y = get_symbol(c, state, 0) * f->height; fs->slice_width = (get_symbol(c, state, 0) + 1) * f->width + fs->slice_x; fs->slice_height = (get_symbol(c, state, 0) + 1) * f->height + fs->slice_y; fs->slice_x /= f->num_h_slices; fs->slice_y /= f->num_v_slices; fs->slice_width = fs->slice_width / f->num_h_slices - fs->slice_x; fs->slice_height = fs->slice_height / f->num_v_slices - fs->slice_y; if ((unsigned)fs->slice_width > f->width || (unsigned)fs->slice_height > f->height) return AVERROR_INVALIDDATA; if ( (unsigned)fs->slice_x + (uint64_t)fs->slice_width > f->width || (unsigned)fs->slice_y + (uint64_t)fs->slice_height > f->height) return AVERROR_INVALIDDATA; } for (i = 0; i < f->plane_count; i++) { PlaneContext *const p = &fs->plane[i]; if (f->version == 2) { int idx = get_symbol(c, state, 0); if (idx > (unsigned)f->quant_table_count) { av_log(f->avctx, AV_LOG_ERROR, "quant_table_index out of range\n"); return AVERROR_INVALIDDATA; } p->quant_table_index = idx; memcpy(p->quant_table, f->quant_tables[idx], sizeof(p->quant_table)); context_count = f->context_count[idx]; } else { memcpy(p->quant_table, f->quant_table, sizeof(p->quant_table)); } if (f->version <= 2) { av_assert0(context_count >= 0); if (p->context_count < context_count) { av_freep(&p->state); av_freep(&p->vlc_state); } p->context_count = context_count; } } } return 0; } static av_cold int decode_init(AVCodecContext *avctx) { FFV1Context *f = avctx->priv_data; int ret; if ((ret = ffv1_common_init(avctx)) < 0) return ret; if (avctx->extradata && (ret = read_extra_header(f)) < 0) return ret; if ((ret = ffv1_init_slice_contexts(f)) < 0) return ret; avctx->internal->allocate_progress = 1; return 0; } static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { const uint8_t *buf = avpkt->data; int buf_size = avpkt->size; FFV1Context *f = avctx->priv_data; RangeCoder *const c = &f->slice_context[0]->c; int i, ret; uint8_t keystate = 128; const uint8_t *buf_p; AVFrame *p; if (f->last_picture.f) ff_thread_release_buffer(avctx, &f->last_picture); FFSWAP(ThreadFrame, f->picture, f->last_picture); f->cur = p = f->picture.f; if (f->version < 3 && avctx->field_order > AV_FIELD_PROGRESSIVE) { /* we have interlaced material flagged in container */ p->interlaced_frame = 1; if (avctx->field_order == AV_FIELD_TT || avctx->field_order == AV_FIELD_TB) p->top_field_first = 1; } f->avctx = avctx; ff_init_range_decoder(c, buf, buf_size); ff_build_rac_states(c, 0.05 * (1LL << 32), 256 - 8); p->pict_type = AV_PICTURE_TYPE_I; //FIXME I vs. P if (get_rac(c, &keystate)) { p->key_frame = 1; f->key_frame_ok = 0; if ((ret = read_header(f)) < 0) return ret; f->key_frame_ok = 1; } else { if (!f->key_frame_ok) { av_log(avctx, AV_LOG_ERROR, "Cannot decode non-keyframe without valid keyframe\n"); return AVERROR_INVALIDDATA; } p->key_frame = 0; } if ((ret = ff_thread_get_buffer(avctx, &f->picture, AV_GET_BUFFER_FLAG_REF)) < 0) return ret; if (avctx->debug & FF_DEBUG_PICT_INFO) av_log(avctx, AV_LOG_DEBUG, "ver:%d keyframe:%d coder:%d ec:%d slices:%d bps:%d\n", f->version, p->key_frame, f->ac, f->ec, f->slice_count, f->avctx->bits_per_raw_sample); ff_thread_finish_setup(avctx); buf_p = buf + buf_size; for (i = f->slice_count - 1; i >= 0; i--) { FFV1Context *fs = f->slice_context[i]; int trailer = 3 + 5*!!f->ec; int v; if (i || f->version > 2) v = AV_RB24(buf_p-trailer) + trailer; else v = buf_p - c->bytestream_start; if (buf_p - c->bytestream_start < v) { av_log(avctx, AV_LOG_ERROR, "Slice pointer chain broken\n"); return AVERROR_INVALIDDATA; } buf_p -= v; if (f->ec) { unsigned crc = av_crc(av_crc_get_table(AV_CRC_32_IEEE), 0, buf_p, v); if (crc) { int64_t ts = avpkt->pts != AV_NOPTS_VALUE ? avpkt->pts : avpkt->dts; av_log(f->avctx, AV_LOG_ERROR, "CRC mismatch %X!", crc); if (ts != AV_NOPTS_VALUE && avctx->pkt_timebase.num) { av_log(f->avctx, AV_LOG_ERROR, "at %f seconds\n", ts*av_q2d(avctx->pkt_timebase)); } else if (ts != AV_NOPTS_VALUE) { av_log(f->avctx, AV_LOG_ERROR, "at %"PRId64"\n", ts); } else { av_log(f->avctx, AV_LOG_ERROR, "\n"); } fs->slice_damaged = 1; } } if (i) { ff_init_range_decoder(&fs->c, buf_p, v); } else fs->c.bytestream_end = (uint8_t *)(buf_p + v); fs->avctx = avctx; fs->cur = p; } avctx->execute(avctx, decode_slice, &f->slice_context[0], NULL, f->slice_count, sizeof(void*)); for (i = f->slice_count - 1; i >= 0; i--) { FFV1Context *fs = f->slice_context[i]; int j; if (fs->slice_damaged && f->last_picture.f->data[0]) { const uint8_t *src[4]; uint8_t *dst[4]; ff_thread_await_progress(&f->last_picture, INT_MAX, 0); for (j = 0; j < 4; j++) { int sh = (j==1 || j==2) ? f->chroma_h_shift : 0; int sv = (j==1 || j==2) ? f->chroma_v_shift : 0; dst[j] = p->data[j] + p->linesize[j]* (fs->slice_y>>sv) + (fs->slice_x>>sh); src[j] = f->last_picture.f->data[j] + f->last_picture.f->linesize[j]* (fs->slice_y>>sv) + (fs->slice_x>>sh); } av_image_copy(dst, p->linesize, (const uint8_t **)src, f->last_picture.f->linesize, avctx->pix_fmt, fs->slice_width, fs->slice_height); } } ff_thread_report_progress(&f->picture, INT_MAX, 0); f->picture_number++; if (f->last_picture.f) ff_thread_release_buffer(avctx, &f->last_picture); f->cur = NULL; if ((ret = av_frame_ref(data, f->picture.f)) < 0) return ret; *got_frame = 1; return buf_size; } static int init_thread_copy(AVCodecContext *avctx) { FFV1Context *f = avctx->priv_data; f->picture.f = NULL; f->last_picture.f = NULL; f->sample_buffer = NULL; f->quant_table_count = 0; f->slice_count = 0; return 0; } static int update_thread_context(AVCodecContext *dst, const AVCodecContext *src) { FFV1Context *fsrc = src->priv_data; FFV1Context *fdst = dst->priv_data; int i, ret; if (dst == src) return 0; if (!fdst->picture.f) { memcpy(fdst, fsrc, sizeof(*fdst)); for (i = 0; i < fdst->quant_table_count; i++) { fdst->initial_states[i] = av_malloc(fdst->context_count[i] * sizeof(*fdst->initial_states[i])); memcpy(fdst->initial_states[i], fsrc->initial_states[i], fdst->context_count[i] * sizeof(*fdst->initial_states[i])); } fdst->picture.f = av_frame_alloc(); fdst->last_picture.f = av_frame_alloc(); if ((ret = ffv1_init_slice_contexts(fdst)) < 0) return ret; } av_assert1(fdst->slice_count == fsrc->slice_count); fdst->key_frame_ok = fsrc->key_frame_ok; ff_thread_release_buffer(dst, &fdst->picture); if (fsrc->picture.f->data[0]) { if ((ret = ff_thread_ref_frame(&fdst->picture, &fsrc->picture)) < 0) return ret; } for (i = 0; i < fdst->slice_count; i++) { FFV1Context *fsdst = fdst->slice_context[i]; FFV1Context *fssrc = fsrc->slice_context[i]; fsdst->slice_damaged = fssrc->slice_damaged; } fdst->fsrc = fsrc; return 0; } AVCodec ff_ffv1_decoder = { .name = "ffv1", .type = AVMEDIA_TYPE_VIDEO, .id = AV_CODEC_ID_FFV1, .priv_data_size = sizeof(FFV1Context), .init = decode_init, .close = ffv1_close, .decode = decode_frame, .init_thread_copy = ONLY_IF_THREADS_ENABLED(init_thread_copy), .update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context), .capabilities = CODEC_CAP_DR1 /*| CODEC_CAP_DRAW_HORIZ_BAND*/ | CODEC_CAP_FRAME_THREADS | CODEC_CAP_SLICE_THREADS, .long_name = NULL_IF_CONFIG_SMALL("FFmpeg video codec #1"), };
./CrossVul/dataset_final_sorted/CWE-119/c/bad_5815_0
crossvul-cpp_data_good_507_1
/****************************************************************************** ** Copyright (c) 2017-2018, Intel Corporation ** ** All rights reserved. ** ** ** ** Redistribution and use in source and binary forms, with or without ** ** modification, are permitted provided that the following conditions ** ** are met: ** ** 1. Redistributions of source code must retain the above copyright ** ** notice, this list of conditions and the following disclaimer. ** ** 2. Redistributions in binary form must reproduce the above copyright ** ** notice, this list of conditions and the following disclaimer in the ** ** documentation and/or other materials provided with the distribution. ** ** 3. Neither the name of the copyright holder nor the names of its ** ** contributors may be used to endorse or promote products derived ** ** from this software without specific prior written permission. ** ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** ** HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED ** ** TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR ** ** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF ** ** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ** ** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ** ** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ******************************************************************************/ /* Alexander Heinecke (Intel Corp.) ******************************************************************************/ #include "edge_proxy_common.h" void edge_sparse_csr_reader_double( const char* i_csr_file_in, unsigned int** o_row_idx, unsigned int** o_column_idx, double** o_values, unsigned int* o_row_count, unsigned int* o_column_count, unsigned int* o_element_count ) { FILE *l_csr_file_handle; const unsigned int l_line_length = 512; char l_line[512/*l_line_length*/+1]; unsigned int l_header_read = 0; unsigned int* l_row_idx_id = NULL; unsigned int l_i = 0; l_csr_file_handle = fopen( i_csr_file_in, "r" ); if ( l_csr_file_handle == NULL ) { fprintf( stderr, "cannot open CSR file!\n" ); return; } while (fgets(l_line, l_line_length, l_csr_file_handle) != NULL) { if ( strlen(l_line) == l_line_length ) { fprintf( stderr, "could not read file length!\n" ); return; } /* check if we are still reading comments header */ if ( l_line[0] == '%' ) { continue; } else { /* if we are the first line after comment header, we allocate our data structures */ if ( l_header_read == 0 ) { if (3 == sscanf(l_line, "%u %u %u", o_row_count, o_column_count, o_element_count) && 0 != *o_row_count && 0 != *o_column_count && 0 != *o_element_count) { /* allocate CSC datastructure matching mtx file */ *o_column_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_element_count)); *o_row_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count + 1)); *o_values = (double*) malloc(sizeof(double) * (*o_element_count)); l_row_idx_id = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count)); /* check if mallocs were successful */ if ( ( *o_row_idx == NULL ) || ( *o_column_idx == NULL ) || ( *o_values == NULL ) || ( l_row_idx_id == NULL ) ) { fprintf( stderr, "could not allocate sp data!\n" ); return; } /* set everything to zero for init */ memset(*o_row_idx, 0, sizeof(unsigned int)*(*o_row_count + 1)); memset(*o_column_idx, 0, sizeof(unsigned int)*(*o_element_count)); memset(*o_values, 0, sizeof(double)*(*o_element_count)); memset(l_row_idx_id, 0, sizeof(unsigned int)*(*o_row_count)); /* init column idx */ for ( l_i = 0; l_i < (*o_row_count + 1); l_i++) (*o_row_idx)[l_i] = (*o_element_count); /* init */ (*o_row_idx)[0] = 0; l_i = 0; l_header_read = 1; } else { fprintf( stderr, "could not csr description!\n" ); return; } /* now we read the actual content */ } else { unsigned int l_row, l_column; double l_value; /* read a line of content */ if ( sscanf(l_line, "%u %u %lf", &l_row, &l_column, &l_value) != 3 ) { fprintf( stderr, "could not read element!\n" ); return; } /* adjust numbers to zero termination */ l_row--; l_column--; /* add these values to row and value structure */ (*o_column_idx)[l_i] = l_column; (*o_values)[l_i] = l_value; l_i++; /* handle columns, set id to own for this column, yeah we need to handle empty columns */ l_row_idx_id[l_row] = 1; (*o_row_idx)[l_row+1] = l_i; } } } /* close mtx file */ fclose( l_csr_file_handle ); /* check if we read a file which was consistent */ if ( l_i != (*o_element_count) ) { fprintf( stderr, "we were not able to read all elements!\n" ); return; } /* let's handle empty rows */ for ( l_i = 0; l_i < (*o_row_count); l_i++) { if ( l_row_idx_id[l_i] == 0 ) { (*o_row_idx)[l_i+1] = (*o_row_idx)[l_i]; } } /* free helper data structure */ if ( l_row_idx_id != NULL ) { free( l_row_idx_id ); } } void edge_sparse_csr_reader_float( const char* i_csr_file_in, unsigned int** o_row_idx, unsigned int** o_column_idx, float** o_values, unsigned int* o_row_count, unsigned int* o_column_count, unsigned int* o_element_count ) { double* l_values; unsigned int i; /* read using double */ edge_sparse_csr_reader_double( i_csr_file_in, o_row_idx, o_column_idx, &l_values, o_row_count, o_column_count, o_element_count ); /* converting double values into float */ *o_values = (float*) malloc((*o_element_count)*sizeof(float)); for ( i = 0; i < (*o_element_count); ++i ) { (*o_values)[i] = (float)l_values[i]; } free(l_values); }
./CrossVul/dataset_final_sorted/CWE-119/c/good_507_1
crossvul-cpp_data_good_1447_0
/* ssl/d1_pkt.c */ /* * DTLS implementation written by Nagendra Modadugu * (nagendra@cs.stanford.edu) for the OpenSSL project 2005. */ /* ==================================================================== * Copyright (c) 1998-2005 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * openssl-core@openssl.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.openssl.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * 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 copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL 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. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ #include <stdio.h> #include <errno.h> #define USE_SOCKETS #include "ssl_locl.h" #include <openssl/evp.h> #include <openssl/buffer.h> #include <openssl/pqueue.h> #include <openssl/rand.h> /* mod 128 saturating subtract of two 64-bit values in big-endian order */ static int satsub64be(const unsigned char *v1,const unsigned char *v2) { int ret,sat,brw,i; if (sizeof(long) == 8) do { const union { long one; char little; } is_endian = {1}; long l; if (is_endian.little) break; /* not reached on little-endians */ /* following test is redundant, because input is * always aligned, but I take no chances... */ if (((size_t)v1|(size_t)v2)&0x7) break; l = *((long *)v1); l -= *((long *)v2); if (l>128) return 128; else if (l<-128) return -128; else return (int)l; } while (0); ret = (int)v1[7]-(int)v2[7]; sat = 0; brw = ret>>8; /* brw is either 0 or -1 */ if (ret & 0x80) { for (i=6;i>=0;i--) { brw += (int)v1[i]-(int)v2[i]; sat |= ~brw; brw >>= 8; } } else { for (i=6;i>=0;i--) { brw += (int)v1[i]-(int)v2[i]; sat |= brw; brw >>= 8; } } brw <<= 8; /* brw is either 0 or -256 */ if (sat&0xff) return brw | 0x80; else return brw + (ret&0xFF); } static int have_handshake_fragment(SSL *s, int type, unsigned char *buf, int len, int peek); static int dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap); static void dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap); static DTLS1_BITMAP *dtls1_get_bitmap(SSL *s, SSL3_RECORD *rr, unsigned int *is_next_epoch); #if 0 static int dtls1_record_needs_buffering(SSL *s, SSL3_RECORD *rr, unsigned short *priority, unsigned long *offset); #endif static int dtls1_buffer_record(SSL *s, record_pqueue *q, unsigned char *priority); static int dtls1_process_record(SSL *s); /* copy buffered record into SSL structure */ static int dtls1_copy_record(SSL *s, pitem *item) { DTLS1_RECORD_DATA *rdata; rdata = (DTLS1_RECORD_DATA *)item->data; if (s->s3->rbuf.buf != NULL) OPENSSL_free(s->s3->rbuf.buf); s->packet = rdata->packet; s->packet_length = rdata->packet_length; memcpy(&(s->s3->rbuf), &(rdata->rbuf), sizeof(SSL3_BUFFER)); memcpy(&(s->s3->rrec), &(rdata->rrec), sizeof(SSL3_RECORD)); /* Set proper sequence number for mac calculation */ memcpy(&(s->s3->read_sequence[2]), &(rdata->packet[5]), 6); return(1); } static int dtls1_buffer_record(SSL *s, record_pqueue *queue, unsigned char *priority) { DTLS1_RECORD_DATA *rdata; pitem *item; /* Limit the size of the queue to prevent DOS attacks */ if (pqueue_size(queue->q) >= 100) return 0; rdata = OPENSSL_malloc(sizeof(DTLS1_RECORD_DATA)); item = pitem_new(priority, rdata); if (rdata == NULL || item == NULL) { if (rdata != NULL) OPENSSL_free(rdata); if (item != NULL) pitem_free(item); SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR); return(0); } rdata->packet = s->packet; rdata->packet_length = s->packet_length; memcpy(&(rdata->rbuf), &(s->s3->rbuf), sizeof(SSL3_BUFFER)); memcpy(&(rdata->rrec), &(s->s3->rrec), sizeof(SSL3_RECORD)); item->data = rdata; #ifndef OPENSSL_NO_SCTP /* Store bio_dgram_sctp_rcvinfo struct */ if (BIO_dgram_is_sctp(SSL_get_rbio(s)) && (s->state == SSL3_ST_SR_FINISHED_A || s->state == SSL3_ST_CR_FINISHED_A)) { BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SCTP_GET_RCVINFO, sizeof(rdata->recordinfo), &rdata->recordinfo); } #endif s->packet = NULL; s->packet_length = 0; memset(&(s->s3->rbuf), 0, sizeof(SSL3_BUFFER)); memset(&(s->s3->rrec), 0, sizeof(SSL3_RECORD)); if (!ssl3_setup_buffers(s)) { SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR); if (rdata->rbuf.buf != NULL) OPENSSL_free(rdata->rbuf.buf); OPENSSL_free(rdata); pitem_free(item); return(-1); } /* insert should not fail, since duplicates are dropped */ if (pqueue_insert(queue->q, item) == NULL) { SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR); if (rdata->rbuf.buf != NULL) OPENSSL_free(rdata->rbuf.buf); OPENSSL_free(rdata); pitem_free(item); return(-1); } return(1); } static int dtls1_retrieve_buffered_record(SSL *s, record_pqueue *queue) { pitem *item; item = pqueue_pop(queue->q); if (item) { dtls1_copy_record(s, item); OPENSSL_free(item->data); pitem_free(item); return(1); } return(0); } /* retrieve a buffered record that belongs to the new epoch, i.e., not processed * yet */ #define dtls1_get_unprocessed_record(s) \ dtls1_retrieve_buffered_record((s), \ &((s)->d1->unprocessed_rcds)) /* retrieve a buffered record that belongs to the current epoch, ie, processed */ #define dtls1_get_processed_record(s) \ dtls1_retrieve_buffered_record((s), \ &((s)->d1->processed_rcds)) static int dtls1_process_buffered_records(SSL *s) { pitem *item; item = pqueue_peek(s->d1->unprocessed_rcds.q); if (item) { /* Check if epoch is current. */ if (s->d1->unprocessed_rcds.epoch != s->d1->r_epoch) return(1); /* Nothing to do. */ /* Process all the records. */ while (pqueue_peek(s->d1->unprocessed_rcds.q)) { dtls1_get_unprocessed_record(s); if ( ! dtls1_process_record(s)) return(0); if(dtls1_buffer_record(s, &(s->d1->processed_rcds), s->s3->rrec.seq_num)<0) return -1; } } /* sync epoch numbers once all the unprocessed records * have been processed */ s->d1->processed_rcds.epoch = s->d1->r_epoch; s->d1->unprocessed_rcds.epoch = s->d1->r_epoch + 1; return(1); } #if 0 static int dtls1_get_buffered_record(SSL *s) { pitem *item; PQ_64BIT priority = (((PQ_64BIT)s->d1->handshake_read_seq) << 32) | ((PQ_64BIT)s->d1->r_msg_hdr.frag_off); if ( ! SSL_in_init(s)) /* if we're not (re)negotiating, nothing buffered */ return 0; item = pqueue_peek(s->d1->rcvd_records); if (item && item->priority == priority) { /* Check if we've received the record of interest. It must be * a handshake record, since data records as passed up without * buffering */ DTLS1_RECORD_DATA *rdata; item = pqueue_pop(s->d1->rcvd_records); rdata = (DTLS1_RECORD_DATA *)item->data; if (s->s3->rbuf.buf != NULL) OPENSSL_free(s->s3->rbuf.buf); s->packet = rdata->packet; s->packet_length = rdata->packet_length; memcpy(&(s->s3->rbuf), &(rdata->rbuf), sizeof(SSL3_BUFFER)); memcpy(&(s->s3->rrec), &(rdata->rrec), sizeof(SSL3_RECORD)); OPENSSL_free(item->data); pitem_free(item); /* s->d1->next_expected_seq_num++; */ return(1); } return 0; } #endif static int dtls1_process_record(SSL *s) { int i,al; int enc_err; SSL_SESSION *sess; SSL3_RECORD *rr; unsigned int mac_size; unsigned char md[EVP_MAX_MD_SIZE]; rr= &(s->s3->rrec); sess = s->session; /* At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length, * and we have that many bytes in s->packet */ rr->input= &(s->packet[DTLS1_RT_HEADER_LENGTH]); /* ok, we can now read from 's->packet' data into 'rr' * rr->input points at rr->length bytes, which * need to be copied into rr->data by either * the decryption or by the decompression * When the data is 'copied' into the rr->data buffer, * rr->input will be pointed at the new buffer */ /* We now have - encrypted [ MAC [ compressed [ plain ] ] ] * rr->length bytes of encrypted compressed stuff. */ /* check is not needed I believe */ if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) { al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_ENCRYPTED_LENGTH_TOO_LONG); goto f_err; } /* decrypt in place in 'rr->input' */ rr->data=rr->input; rr->orig_len=rr->length; enc_err = s->method->ssl3_enc->enc(s,0); /* enc_err is: * 0: (in non-constant time) if the record is publically invalid. * 1: if the padding is valid * -1: if the padding is invalid */ if (enc_err == 0) { /* For DTLS we simply ignore bad packets. */ rr->length = 0; s->packet_length = 0; goto err; } #ifdef TLS_DEBUG printf("dec %d\n",rr->length); { unsigned int z; for (z=0; z<rr->length; z++) printf("%02X%c",rr->data[z],((z+1)%16)?' ':'\n'); } printf("\n"); #endif /* r->length is now the compressed data plus mac */ if ((sess != NULL) && (s->enc_read_ctx != NULL) && (EVP_MD_CTX_md(s->read_hash) != NULL)) { /* s->read_hash != NULL => mac_size != -1 */ unsigned char *mac = NULL; unsigned char mac_tmp[EVP_MAX_MD_SIZE]; mac_size=EVP_MD_CTX_size(s->read_hash); OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE); /* orig_len is the length of the record before any padding was * removed. This is public information, as is the MAC in use, * therefore we can safely process the record in a different * amount of time if it's too short to possibly contain a MAC. */ if (rr->orig_len < mac_size || /* CBC records must have a padding length byte too. */ (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE && rr->orig_len < mac_size+1)) { al=SSL_AD_DECODE_ERROR; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_LENGTH_TOO_SHORT); goto f_err; } if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) { /* We update the length so that the TLS header bytes * can be constructed correctly but we need to extract * the MAC in constant time from within the record, * without leaking the contents of the padding bytes. * */ mac = mac_tmp; ssl3_cbc_copy_mac(mac_tmp, rr, mac_size); rr->length -= mac_size; } else { /* In this case there's no padding, so |rec->orig_len| * equals |rec->length| and we checked that there's * enough bytes for |mac_size| above. */ rr->length -= mac_size; mac = &rr->data[rr->length]; } i=s->method->ssl3_enc->mac(s,md,0 /* not send */); if (i < 0 || mac == NULL || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0) enc_err = -1; if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+mac_size) enc_err = -1; } if (enc_err < 0) { /* decryption failed, silently discard message */ rr->length = 0; s->packet_length = 0; goto err; } /* r->length is now just compressed */ if (s->expand != NULL) { if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) { al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_COMPRESSED_LENGTH_TOO_LONG); goto f_err; } if (!ssl3_do_uncompress(s)) { al=SSL_AD_DECOMPRESSION_FAILURE; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_BAD_DECOMPRESSION); goto f_err; } } if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH) { al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_DATA_LENGTH_TOO_LONG); goto f_err; } rr->off=0; /*- * So at this point the following is true * ssl->s3->rrec.type is the type of record * ssl->s3->rrec.length == number of bytes in record * ssl->s3->rrec.off == offset to first valid byte * ssl->s3->rrec.data == where to take bytes from, increment * after use :-). */ /* we have pulled in a full packet so zero things */ s->packet_length=0; return(1); f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); err: return(0); } /*- * Call this to get a new input record. * It will return <= 0 if more data is needed, normally due to an error * or non-blocking IO. * When it finishes, one packet has been decoded and can be found in * ssl->s3->rrec.type - is the type of record * ssl->s3->rrec.data, - data * ssl->s3->rrec.length, - number of bytes */ /* used only by dtls1_read_bytes */ int dtls1_get_record(SSL *s) { int ssl_major,ssl_minor; int i,n; SSL3_RECORD *rr; unsigned char *p = NULL; unsigned short version; DTLS1_BITMAP *bitmap; unsigned int is_next_epoch; rr= &(s->s3->rrec); /* The epoch may have changed. If so, process all the * pending records. This is a non-blocking operation. */ if(dtls1_process_buffered_records(s)<0) return -1; /* if we're renegotiating, then there may be buffered records */ if (dtls1_get_processed_record(s)) return 1; /* get something from the wire */ again: /* check if we have the header */ if ( (s->rstate != SSL_ST_READ_BODY) || (s->packet_length < DTLS1_RT_HEADER_LENGTH)) { n=ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH, s->s3->rbuf.len, 0); /* read timeout is handled by dtls1_read_bytes */ if (n <= 0) return(n); /* error or non-blocking */ /* this packet contained a partial record, dump it */ if (s->packet_length != DTLS1_RT_HEADER_LENGTH) { s->packet_length = 0; goto again; } s->rstate=SSL_ST_READ_BODY; p=s->packet; if (s->msg_callback) s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH, s, s->msg_callback_arg); /* Pull apart the header into the DTLS1_RECORD */ rr->type= *(p++); ssl_major= *(p++); ssl_minor= *(p++); version=(ssl_major<<8)|ssl_minor; /* sequence number is 64 bits, with top 2 bytes = epoch */ n2s(p,rr->epoch); memcpy(&(s->s3->read_sequence[2]), p, 6); p+=6; n2s(p,rr->length); /* Lets check version */ if (!s->first_packet) { if (version != s->version) { /* unexpected version, silently discard */ rr->length = 0; s->packet_length = 0; goto again; } } if ((version & 0xff00) != (s->version & 0xff00)) { /* wrong version, silently discard record */ rr->length = 0; s->packet_length = 0; goto again; } if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) { /* record too long, silently discard it */ rr->length = 0; s->packet_length = 0; goto again; } /* now s->rstate == SSL_ST_READ_BODY */ } /* s->rstate == SSL_ST_READ_BODY, get and decode the data */ if (rr->length > s->packet_length-DTLS1_RT_HEADER_LENGTH) { /* now s->packet_length == DTLS1_RT_HEADER_LENGTH */ i=rr->length; n=ssl3_read_n(s,i,i,1); /* this packet contained a partial record, dump it */ if ( n != i) { rr->length = 0; s->packet_length = 0; goto again; } /* now n == rr->length, * and s->packet_length == DTLS1_RT_HEADER_LENGTH + rr->length */ } s->rstate=SSL_ST_READ_HEADER; /* set state for later operations */ /* match epochs. NULL means the packet is dropped on the floor */ bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch); if ( bitmap == NULL) { rr->length = 0; s->packet_length = 0; /* dump this record */ goto again; /* get another record */ } #ifndef OPENSSL_NO_SCTP /* Only do replay check if no SCTP bio */ if (!BIO_dgram_is_sctp(SSL_get_rbio(s))) { #endif /* Check whether this is a repeat, or aged record. * Don't check if we're listening and this message is * a ClientHello. They can look as if they're replayed, * since they arrive from different connections and * would be dropped unnecessarily. */ if (!(s->d1->listen && rr->type == SSL3_RT_HANDSHAKE && s->packet_length > DTLS1_RT_HEADER_LENGTH && s->packet[DTLS1_RT_HEADER_LENGTH] == SSL3_MT_CLIENT_HELLO) && !dtls1_record_replay_check(s, bitmap)) { rr->length = 0; s->packet_length=0; /* dump this record */ goto again; /* get another record */ } #ifndef OPENSSL_NO_SCTP } #endif /* just read a 0 length packet */ if (rr->length == 0) goto again; /* If this record is from the next epoch (either HM or ALERT), * and a handshake is currently in progress, buffer it since it * cannot be processed at this time. However, do not buffer * anything while listening. */ if (is_next_epoch) { if ((SSL_in_init(s) || s->in_handshake) && !s->d1->listen) { if(dtls1_buffer_record(s, &(s->d1->unprocessed_rcds), rr->seq_num)<0) return -1; dtls1_record_bitmap_update(s, bitmap);/* Mark receipt of record. */ } rr->length = 0; s->packet_length = 0; goto again; } if (!dtls1_process_record(s)) { rr->length = 0; s->packet_length = 0; /* dump this record */ goto again; /* get another record */ } dtls1_record_bitmap_update(s, bitmap);/* Mark receipt of record. */ return(1); } /*- * Return up to 'len' payload bytes received in 'type' records. * 'type' is one of the following: * * - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us) * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us) * - 0 (during a shutdown, no data has to be returned) * * If we don't have stored data to work from, read a SSL/TLS record first * (possibly multiple records if we still don't have anything to return). * * This function must handle any surprises the peer may have for us, such as * Alert records (e.g. close_notify), ChangeCipherSpec records (not really * a surprise, but handled as if it were), or renegotiation requests. * Also if record payloads contain fragments too small to process, we store * them until there is enough for the respective protocol (the record protocol * may use arbitrary fragmentation and even interleaving): * Change cipher spec protocol * just 1 byte needed, no need for keeping anything stored * Alert protocol * 2 bytes needed (AlertLevel, AlertDescription) * Handshake protocol * 4 bytes needed (HandshakeType, uint24 length) -- we just have * to detect unexpected Client Hello and Hello Request messages * here, anything else is handled by higher layers * Application data protocol * none of our business */ int dtls1_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek) { int al,i,j,ret; unsigned int n; SSL3_RECORD *rr; void (*cb)(const SSL *ssl,int type2,int val)=NULL; if (s->s3->rbuf.buf == NULL) /* Not initialized yet */ if (!ssl3_setup_buffers(s)) return(-1); if ((type && (type != SSL3_RT_APPLICATION_DATA) && (type != SSL3_RT_HANDSHAKE)) || (peek && (type != SSL3_RT_APPLICATION_DATA))) { SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR); return -1; } /* check whether there's a handshake message (client hello?) waiting */ if ( (ret = have_handshake_fragment(s, type, buf, len, peek))) return ret; /* Now s->d1->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE. */ #ifndef OPENSSL_NO_SCTP /* Continue handshake if it had to be interrupted to read * app data with SCTP. */ if ((!s->in_handshake && SSL_in_init(s)) || (BIO_dgram_is_sctp(SSL_get_rbio(s)) && (s->state == DTLS1_SCTP_ST_SR_READ_SOCK || s->state == DTLS1_SCTP_ST_CR_READ_SOCK) && s->s3->in_read_app_data != 2)) #else if (!s->in_handshake && SSL_in_init(s)) #endif { /* type == SSL3_RT_APPLICATION_DATA */ i=s->handshake_func(s); if (i < 0) return(i); if (i == 0) { SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE); return(-1); } } start: s->rwstate=SSL_NOTHING; /*- * s->s3->rrec.type - is the type of record * s->s3->rrec.data, - data * s->s3->rrec.off, - offset into 'data' for next read * s->s3->rrec.length, - number of bytes. */ rr = &(s->s3->rrec); /* We are not handshaking and have no data yet, * so process data buffered during the last handshake * in advance, if any. */ if (s->state == SSL_ST_OK && rr->length == 0) { pitem *item; item = pqueue_pop(s->d1->buffered_app_data.q); if (item) { #ifndef OPENSSL_NO_SCTP /* Restore bio_dgram_sctp_rcvinfo struct */ if (BIO_dgram_is_sctp(SSL_get_rbio(s))) { DTLS1_RECORD_DATA *rdata = (DTLS1_RECORD_DATA *) item->data; BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SCTP_SET_RCVINFO, sizeof(rdata->recordinfo), &rdata->recordinfo); } #endif dtls1_copy_record(s, item); OPENSSL_free(item->data); pitem_free(item); } } /* Check for timeout */ if (dtls1_handle_timeout(s) > 0) goto start; /* get new packet if necessary */ if ((rr->length == 0) || (s->rstate == SSL_ST_READ_BODY)) { ret=dtls1_get_record(s); if (ret <= 0) { ret = dtls1_read_failed(s, ret); /* anything other than a timeout is an error */ if (ret <= 0) return(ret); else goto start; } } if (s->d1->listen && rr->type != SSL3_RT_HANDSHAKE) { rr->length = 0; goto start; } /* we now have a packet which can be read and processed */ if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec, * reset by ssl3_get_finished */ && (rr->type != SSL3_RT_HANDSHAKE)) { /* We now have application data between CCS and Finished. * Most likely the packets were reordered on their way, so * buffer the application data for later processing rather * than dropping the connection. */ if(dtls1_buffer_record(s, &(s->d1->buffered_app_data), rr->seq_num)<0) { SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR); return -1; } rr->length = 0; goto start; } /* If the other end has shut down, throw anything we read away * (even in 'peek' mode) */ if (s->shutdown & SSL_RECEIVED_SHUTDOWN) { rr->length=0; s->rwstate=SSL_NOTHING; return(0); } if (type == rr->type) /* SSL3_RT_APPLICATION_DATA or SSL3_RT_HANDSHAKE */ { /* make sure that we are not getting application data when we * are doing a handshake for the first time */ if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) && (s->enc_read_ctx == NULL)) { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_APP_DATA_IN_HANDSHAKE); goto f_err; } if (len <= 0) return(len); if ((unsigned int)len > rr->length) n = rr->length; else n = (unsigned int)len; memcpy(buf,&(rr->data[rr->off]),n); if (!peek) { rr->length-=n; rr->off+=n; if (rr->length == 0) { s->rstate=SSL_ST_READ_HEADER; rr->off=0; } } #ifndef OPENSSL_NO_SCTP /* We were about to renegotiate but had to read * belated application data first, so retry. */ if (BIO_dgram_is_sctp(SSL_get_rbio(s)) && rr->type == SSL3_RT_APPLICATION_DATA && (s->state == DTLS1_SCTP_ST_SR_READ_SOCK || s->state == DTLS1_SCTP_ST_CR_READ_SOCK)) { s->rwstate=SSL_READING; BIO_clear_retry_flags(SSL_get_rbio(s)); BIO_set_retry_read(SSL_get_rbio(s)); } /* We might had to delay a close_notify alert because * of reordered app data. If there was an alert and there * is no message to read anymore, finally set shutdown. */ if (BIO_dgram_is_sctp(SSL_get_rbio(s)) && s->d1->shutdown_received && !BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) { s->shutdown |= SSL_RECEIVED_SHUTDOWN; return(0); } #endif return(n); } /* If we get here, then type != rr->type; if we have a handshake * message, then it was unexpected (Hello Request or Client Hello). */ /* In case of record types for which we have 'fragment' storage, * fill that so that we can process the data at a fixed place. */ { unsigned int k, dest_maxlen = 0; unsigned char *dest = NULL; unsigned int *dest_len = NULL; if (rr->type == SSL3_RT_HANDSHAKE) { dest_maxlen = sizeof s->d1->handshake_fragment; dest = s->d1->handshake_fragment; dest_len = &s->d1->handshake_fragment_len; } else if (rr->type == SSL3_RT_ALERT) { dest_maxlen = sizeof(s->d1->alert_fragment); dest = s->d1->alert_fragment; dest_len = &s->d1->alert_fragment_len; } #ifndef OPENSSL_NO_HEARTBEATS else if (rr->type == TLS1_RT_HEARTBEAT) { dtls1_process_heartbeat(s); /* Exit and notify application to read again */ rr->length = 0; s->rwstate=SSL_READING; BIO_clear_retry_flags(SSL_get_rbio(s)); BIO_set_retry_read(SSL_get_rbio(s)); return(-1); } #endif /* else it's a CCS message, or application data or wrong */ else if (rr->type != SSL3_RT_CHANGE_CIPHER_SPEC) { /* Application data while renegotiating * is allowed. Try again reading. */ if (rr->type == SSL3_RT_APPLICATION_DATA) { BIO *bio; s->s3->in_read_app_data=2; bio=SSL_get_rbio(s); s->rwstate=SSL_READING; BIO_clear_retry_flags(bio); BIO_set_retry_read(bio); return(-1); } /* Not certain if this is the right error handling */ al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_UNEXPECTED_RECORD); goto f_err; } if (dest_maxlen > 0) { /* XDTLS: In a pathalogical case, the Client Hello * may be fragmented--don't always expect dest_maxlen bytes */ if ( rr->length < dest_maxlen) { #ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE /* * for normal alerts rr->length is 2, while * dest_maxlen is 7 if we were to handle this * non-existing alert... */ FIX ME #endif s->rstate=SSL_ST_READ_HEADER; rr->length = 0; goto start; } /* now move 'n' bytes: */ for ( k = 0; k < dest_maxlen; k++) { dest[k] = rr->data[rr->off++]; rr->length--; } *dest_len = dest_maxlen; } } /* s->d1->handshake_fragment_len == 12 iff rr->type == SSL3_RT_HANDSHAKE; * s->d1->alert_fragment_len == 7 iff rr->type == SSL3_RT_ALERT. * (Possibly rr is 'empty' now, i.e. rr->length may be 0.) */ /* If we are a client, check for an incoming 'Hello Request': */ if ((!s->server) && (s->d1->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) && (s->d1->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) && (s->session != NULL) && (s->session->cipher != NULL)) { s->d1->handshake_fragment_len = 0; if ((s->d1->handshake_fragment[1] != 0) || (s->d1->handshake_fragment[2] != 0) || (s->d1->handshake_fragment[3] != 0)) { al=SSL_AD_DECODE_ERROR; SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_BAD_HELLO_REQUEST); goto err; } /* no need to check sequence number on HELLO REQUEST messages */ if (s->msg_callback) s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->d1->handshake_fragment, 4, s, s->msg_callback_arg); if (SSL_is_init_finished(s) && !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) && !s->s3->renegotiate) { s->d1->handshake_read_seq++; s->new_session = 1; ssl3_renegotiate(s); if (ssl3_renegotiate_check(s)) { i=s->handshake_func(s); if (i < 0) return(i); if (i == 0) { SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE); return(-1); } if (!(s->mode & SSL_MODE_AUTO_RETRY)) { if (s->s3->rbuf.left == 0) /* no read-ahead left? */ { BIO *bio; /* In the case where we try to read application data, * but we trigger an SSL handshake, we return -1 with * the retry option set. Otherwise renegotiation may * cause nasty problems in the blocking world */ s->rwstate=SSL_READING; bio=SSL_get_rbio(s); BIO_clear_retry_flags(bio); BIO_set_retry_read(bio); return(-1); } } } } /* we either finished a handshake or ignored the request, * now try again to obtain the (application) data we were asked for */ goto start; } if (s->d1->alert_fragment_len >= DTLS1_AL_HEADER_LENGTH) { int alert_level = s->d1->alert_fragment[0]; int alert_descr = s->d1->alert_fragment[1]; s->d1->alert_fragment_len = 0; if (s->msg_callback) s->msg_callback(0, s->version, SSL3_RT_ALERT, s->d1->alert_fragment, 2, s, s->msg_callback_arg); if (s->info_callback != NULL) cb=s->info_callback; else if (s->ctx->info_callback != NULL) cb=s->ctx->info_callback; if (cb != NULL) { j = (alert_level << 8) | alert_descr; cb(s, SSL_CB_READ_ALERT, j); } if (alert_level == 1) /* warning */ { s->s3->warn_alert = alert_descr; if (alert_descr == SSL_AD_CLOSE_NOTIFY) { #ifndef OPENSSL_NO_SCTP /* With SCTP and streams the socket may deliver app data * after a close_notify alert. We have to check this * first so that nothing gets discarded. */ if (BIO_dgram_is_sctp(SSL_get_rbio(s)) && BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) { s->d1->shutdown_received = 1; s->rwstate=SSL_READING; BIO_clear_retry_flags(SSL_get_rbio(s)); BIO_set_retry_read(SSL_get_rbio(s)); return -1; } #endif s->shutdown |= SSL_RECEIVED_SHUTDOWN; return(0); } #if 0 /* XXX: this is a possible improvement in the future */ /* now check if it's a missing record */ if (alert_descr == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE) { unsigned short seq; unsigned int frag_off; unsigned char *p = &(s->d1->alert_fragment[2]); n2s(p, seq); n2l3(p, frag_off); dtls1_retransmit_message(s, dtls1_get_queue_priority(frag->msg_header.seq, 0), frag_off, &found); if ( ! found && SSL_in_init(s)) { /* fprintf( stderr,"in init = %d\n", SSL_in_init(s)); */ /* requested a message not yet sent, send an alert ourselves */ ssl3_send_alert(s,SSL3_AL_WARNING, DTLS1_AD_MISSING_HANDSHAKE_MESSAGE); } } #endif } else if (alert_level == 2) /* fatal */ { char tmp[16]; s->rwstate=SSL_NOTHING; s->s3->fatal_alert = alert_descr; SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_AD_REASON_OFFSET + alert_descr); BIO_snprintf(tmp,sizeof tmp,"%d",alert_descr); ERR_add_error_data(2,"SSL alert number ",tmp); s->shutdown|=SSL_RECEIVED_SHUTDOWN; SSL_CTX_remove_session(s->ctx,s->session); return(0); } else { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_UNKNOWN_ALERT_TYPE); goto f_err; } goto start; } if (s->shutdown & SSL_SENT_SHUTDOWN) /* but we have not received a shutdown */ { s->rwstate=SSL_NOTHING; rr->length=0; return(0); } if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) { struct ccs_header_st ccs_hdr; unsigned int ccs_hdr_len = DTLS1_CCS_HEADER_LENGTH; dtls1_get_ccs_header(rr->data, &ccs_hdr); if (s->version == DTLS1_BAD_VER) ccs_hdr_len = 3; /* 'Change Cipher Spec' is just a single byte, so we know * exactly what the record payload has to look like */ /* XDTLS: check that epoch is consistent */ if ( (rr->length != ccs_hdr_len) || (rr->off != 0) || (rr->data[0] != SSL3_MT_CCS)) { i=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_BAD_CHANGE_CIPHER_SPEC); goto err; } rr->length=0; if (s->msg_callback) s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC, rr->data, 1, s, s->msg_callback_arg); /* We can't process a CCS now, because previous handshake * messages are still missing, so just drop it. */ if (!s->d1->change_cipher_spec_ok) { goto start; } s->d1->change_cipher_spec_ok = 0; s->s3->change_cipher_spec=1; if (!ssl3_do_change_cipher_spec(s)) goto err; /* do this whenever CCS is processed */ dtls1_reset_seq_numbers(s, SSL3_CC_READ); if (s->version == DTLS1_BAD_VER) s->d1->handshake_read_seq++; #ifndef OPENSSL_NO_SCTP /* Remember that a CCS has been received, * so that an old key of SCTP-Auth can be * deleted when a CCS is sent. Will be ignored * if no SCTP is used */ BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD, 1, NULL); #endif goto start; } /* Unexpected handshake message (Client Hello, or protocol violation) */ if ((s->d1->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) && !s->in_handshake) { struct hm_header_st msg_hdr; /* this may just be a stale retransmit */ dtls1_get_message_header(rr->data, &msg_hdr); if( rr->epoch != s->d1->r_epoch) { rr->length = 0; goto start; } /* If we are server, we may have a repeated FINISHED of the * client here, then retransmit our CCS and FINISHED. */ if (msg_hdr.type == SSL3_MT_FINISHED) { if (dtls1_check_timeout_num(s) < 0) return -1; dtls1_retransmit_buffered_messages(s); rr->length = 0; goto start; } if (((s->state&SSL_ST_MASK) == SSL_ST_OK) && !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)) { #if 0 /* worked only because C operator preferences are not as expected (and * because this is not really needed for clients except for detecting * protocol violations): */ s->state=SSL_ST_BEFORE|(s->server) ?SSL_ST_ACCEPT :SSL_ST_CONNECT; #else s->state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT; #endif s->renegotiate=1; s->new_session=1; } i=s->handshake_func(s); if (i < 0) return(i); if (i == 0) { SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE); return(-1); } if (!(s->mode & SSL_MODE_AUTO_RETRY)) { if (s->s3->rbuf.left == 0) /* no read-ahead left? */ { BIO *bio; /* In the case where we try to read application data, * but we trigger an SSL handshake, we return -1 with * the retry option set. Otherwise renegotiation may * cause nasty problems in the blocking world */ s->rwstate=SSL_READING; bio=SSL_get_rbio(s); BIO_clear_retry_flags(bio); BIO_set_retry_read(bio); return(-1); } } goto start; } switch (rr->type) { default: #ifndef OPENSSL_NO_TLS /* TLS just ignores unknown message types */ if (s->version == TLS1_VERSION) { rr->length = 0; goto start; } #endif al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_UNEXPECTED_RECORD); goto f_err; case SSL3_RT_CHANGE_CIPHER_SPEC: case SSL3_RT_ALERT: case SSL3_RT_HANDSHAKE: /* we already handled all of these, with the possible exception * of SSL3_RT_HANDSHAKE when s->in_handshake is set, but that * should not happen when type != rr->type */ al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_DTLS1_READ_BYTES,ERR_R_INTERNAL_ERROR); goto f_err; case SSL3_RT_APPLICATION_DATA: /* At this point, we were expecting handshake data, * but have application data. If the library was * running inside ssl3_read() (i.e. in_read_app_data * is set) and it makes sense to read application data * at this point (session renegotiation not yet started), * we will indulge it. */ if (s->s3->in_read_app_data && (s->s3->total_renegotiations != 0) && (( (s->state & SSL_ST_CONNECT) && (s->state >= SSL3_ST_CW_CLNT_HELLO_A) && (s->state <= SSL3_ST_CR_SRVR_HELLO_A) ) || ( (s->state & SSL_ST_ACCEPT) && (s->state <= SSL3_ST_SW_HELLO_REQ_A) && (s->state >= SSL3_ST_SR_CLNT_HELLO_A) ) )) { s->s3->in_read_app_data=2; return(-1); } else { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_UNEXPECTED_RECORD); goto f_err; } } /* not reached */ f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); err: return(-1); } int dtls1_write_app_data_bytes(SSL *s, int type, const void *buf_, int len) { int i; #ifndef OPENSSL_NO_SCTP /* Check if we have to continue an interrupted handshake * for reading belated app data with SCTP. */ if ((SSL_in_init(s) && !s->in_handshake) || (BIO_dgram_is_sctp(SSL_get_wbio(s)) && (s->state == DTLS1_SCTP_ST_SR_READ_SOCK || s->state == DTLS1_SCTP_ST_CR_READ_SOCK))) #else if (SSL_in_init(s) && !s->in_handshake) #endif { i=s->handshake_func(s); if (i < 0) return(i); if (i == 0) { SSLerr(SSL_F_DTLS1_WRITE_APP_DATA_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE); return -1; } } if (len > SSL3_RT_MAX_PLAIN_LENGTH) { SSLerr(SSL_F_DTLS1_WRITE_APP_DATA_BYTES,SSL_R_DTLS_MESSAGE_TOO_BIG); return -1; } i = dtls1_write_bytes(s, type, buf_, len); return i; } /* this only happens when a client hello is received and a handshake * is started. */ static int have_handshake_fragment(SSL *s, int type, unsigned char *buf, int len, int peek) { if ((type == SSL3_RT_HANDSHAKE) && (s->d1->handshake_fragment_len > 0)) /* (partially) satisfy request from storage */ { unsigned char *src = s->d1->handshake_fragment; unsigned char *dst = buf; unsigned int k,n; /* peek == 0 */ n = 0; while ((len > 0) && (s->d1->handshake_fragment_len > 0)) { *dst++ = *src++; len--; s->d1->handshake_fragment_len--; n++; } /* move any remaining fragment bytes: */ for (k = 0; k < s->d1->handshake_fragment_len; k++) s->d1->handshake_fragment[k] = *src++; return n; } return 0; } /* Call this to write data in records of type 'type' * It will return <= 0 if not all data has been sent or non-blocking IO. */ int dtls1_write_bytes(SSL *s, int type, const void *buf, int len) { int i; OPENSSL_assert(len <= SSL3_RT_MAX_PLAIN_LENGTH); s->rwstate=SSL_NOTHING; i=do_dtls1_write(s, type, buf, len, 0); return i; } int do_dtls1_write(SSL *s, int type, const unsigned char *buf, unsigned int len, int create_empty_fragment) { unsigned char *p,*pseq; int i,mac_size,clear=0; int prefix_len = 0; int eivlen; SSL3_RECORD *wr; SSL3_BUFFER *wb; SSL_SESSION *sess; /* first check if there is a SSL3_BUFFER still being written * out. This will happen with non blocking IO */ if (s->s3->wbuf.left != 0) { OPENSSL_assert(0); /* XDTLS: want to see if we ever get here */ return(ssl3_write_pending(s,type,buf,len)); } /* If we have an alert to send, lets send it */ if (s->s3->alert_dispatch) { i=s->method->ssl_dispatch_alert(s); if (i <= 0) return(i); /* if it went, fall through and send more stuff */ } if (len == 0 && !create_empty_fragment) return 0; wr= &(s->s3->wrec); wb= &(s->s3->wbuf); sess=s->session; if ( (sess == NULL) || (s->enc_write_ctx == NULL) || (EVP_MD_CTX_md(s->write_hash) == NULL)) clear=1; if (clear) mac_size=0; else { mac_size=EVP_MD_CTX_size(s->write_hash); if (mac_size < 0) goto err; } /* DTLS implements explicit IV, so no need for empty fragments */ #if 0 /* 'create_empty_fragment' is true only when this function calls itself */ if (!clear && !create_empty_fragment && !s->s3->empty_fragment_done && SSL_version(s) != DTLS1_VERSION && SSL_version(s) != DTLS1_BAD_VER) { /* countermeasure against known-IV weakness in CBC ciphersuites * (see http://www.openssl.org/~bodo/tls-cbc.txt) */ if (s->s3->need_empty_fragments && type == SSL3_RT_APPLICATION_DATA) { /* recursive function call with 'create_empty_fragment' set; * this prepares and buffers the data for an empty fragment * (these 'prefix_len' bytes are sent out later * together with the actual payload) */ prefix_len = s->method->do_ssl_write(s, type, buf, 0, 1); if (prefix_len <= 0) goto err; if (s->s3->wbuf.len < (size_t)prefix_len + SSL3_RT_MAX_PACKET_SIZE) { /* insufficient space */ SSLerr(SSL_F_DO_DTLS1_WRITE, ERR_R_INTERNAL_ERROR); goto err; } } s->s3->empty_fragment_done = 1; } #endif p = wb->buf + prefix_len; /* write the header */ *(p++)=type&0xff; wr->type=type; /* Special case: for hello verify request, client version 1.0 and * we haven't decided which version to use yet send back using * version 1.0 header: otherwise some clients will ignore it. */ if (s->method->version == DTLS_ANY_VERSION) { *(p++)=DTLS1_VERSION>>8; *(p++)=DTLS1_VERSION&0xff; } else { *(p++)=s->version>>8; *(p++)=s->version&0xff; } /* field where we are to write out packet epoch, seq num and len */ pseq=p; p+=10; /* Explicit IV length, block ciphers appropriate version flag */ if (s->enc_write_ctx) { int mode = EVP_CIPHER_CTX_mode(s->enc_write_ctx); if (mode == EVP_CIPH_CBC_MODE) { eivlen = EVP_CIPHER_CTX_iv_length(s->enc_write_ctx); if (eivlen <= 1) eivlen = 0; } /* Need explicit part of IV for GCM mode */ else if (mode == EVP_CIPH_GCM_MODE) eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN; else eivlen = 0; } else eivlen = 0; /* lets setup the record stuff. */ wr->data=p + eivlen; /* make room for IV in case of CBC */ wr->length=(int)len; wr->input=(unsigned char *)buf; /* we now 'read' from wr->input, wr->length bytes into * wr->data */ /* first we compress */ if (s->compress != NULL) { if (!ssl3_do_compress(s)) { SSLerr(SSL_F_DO_DTLS1_WRITE,SSL_R_COMPRESSION_FAILURE); goto err; } } else { memcpy(wr->data,wr->input,wr->length); wr->input=wr->data; } /* we should still have the output to wr->data and the input * from wr->input. Length should be wr->length. * wr->data still points in the wb->buf */ if (mac_size != 0) { if(s->method->ssl3_enc->mac(s,&(p[wr->length + eivlen]),1) < 0) goto err; wr->length+=mac_size; } /* this is true regardless of mac size */ wr->input=p; wr->data=p; if (eivlen) wr->length += eivlen; if(s->method->ssl3_enc->enc(s,1) < 1) goto err; /* record length after mac and block padding */ /* if (type == SSL3_RT_APPLICATION_DATA || (type == SSL3_RT_ALERT && ! SSL_in_init(s))) */ /* there's only one epoch between handshake and app data */ s2n(s->d1->w_epoch, pseq); /* XDTLS: ?? */ /* else s2n(s->d1->handshake_epoch, pseq); */ memcpy(pseq, &(s->s3->write_sequence[2]), 6); pseq+=6; s2n(wr->length,pseq); if (s->msg_callback) s->msg_callback(1, 0, SSL3_RT_HEADER, pseq - DTLS1_RT_HEADER_LENGTH, DTLS1_RT_HEADER_LENGTH, s, s->msg_callback_arg); /* we should now have * wr->data pointing to the encrypted data, which is * wr->length long */ wr->type=type; /* not needed but helps for debugging */ wr->length+=DTLS1_RT_HEADER_LENGTH; #if 0 /* this is now done at the message layer */ /* buffer the record, making it easy to handle retransmits */ if ( type == SSL3_RT_HANDSHAKE || type == SSL3_RT_CHANGE_CIPHER_SPEC) dtls1_buffer_record(s, wr->data, wr->length, *((PQ_64BIT *)&(s->s3->write_sequence[0]))); #endif ssl3_record_sequence_update(&(s->s3->write_sequence[0])); if (create_empty_fragment) { /* we are in a recursive call; * just return the length, don't write out anything here */ return wr->length; } /* now let's set up wb */ wb->left = prefix_len + wr->length; wb->offset = 0; /* memorize arguments so that ssl3_write_pending can detect bad write retries later */ s->s3->wpend_tot=len; s->s3->wpend_buf=buf; s->s3->wpend_type=type; s->s3->wpend_ret=len; /* we now just need to write the buffer */ return ssl3_write_pending(s,type,buf,len); err: return -1; } static int dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap) { int cmp; unsigned int shift; const unsigned char *seq = s->s3->read_sequence; cmp = satsub64be(seq,bitmap->max_seq_num); if (cmp > 0) { memcpy (s->s3->rrec.seq_num,seq,8); return 1; /* this record in new */ } shift = -cmp; if (shift >= sizeof(bitmap->map)*8) return 0; /* stale, outside the window */ else if (bitmap->map & (1UL<<shift)) return 0; /* record previously received */ memcpy (s->s3->rrec.seq_num,seq,8); return 1; } static void dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap) { int cmp; unsigned int shift; const unsigned char *seq = s->s3->read_sequence; cmp = satsub64be(seq,bitmap->max_seq_num); if (cmp > 0) { shift = cmp; if (shift < sizeof(bitmap->map)*8) bitmap->map <<= shift, bitmap->map |= 1UL; else bitmap->map = 1UL; memcpy(bitmap->max_seq_num,seq,8); } else { shift = -cmp; if (shift < sizeof(bitmap->map)*8) bitmap->map |= 1UL<<shift; } } int dtls1_dispatch_alert(SSL *s) { int i,j; void (*cb)(const SSL *ssl,int type,int val)=NULL; unsigned char buf[DTLS1_AL_HEADER_LENGTH]; unsigned char *ptr = &buf[0]; s->s3->alert_dispatch=0; memset(buf, 0x00, sizeof(buf)); *ptr++ = s->s3->send_alert[0]; *ptr++ = s->s3->send_alert[1]; #ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE if (s->s3->send_alert[1] == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE) { s2n(s->d1->handshake_read_seq, ptr); #if 0 if ( s->d1->r_msg_hdr.frag_off == 0) /* waiting for a new msg */ else s2n(s->d1->r_msg_hdr.seq, ptr); /* partial msg read */ #endif #if 0 fprintf(stderr, "s->d1->handshake_read_seq = %d, s->d1->r_msg_hdr.seq = %d\n",s->d1->handshake_read_seq,s->d1->r_msg_hdr.seq); #endif l2n3(s->d1->r_msg_hdr.frag_off, ptr); } #endif i = do_dtls1_write(s, SSL3_RT_ALERT, &buf[0], sizeof(buf), 0); if (i <= 0) { s->s3->alert_dispatch=1; /* fprintf( stderr, "not done with alert\n" ); */ } else { if (s->s3->send_alert[0] == SSL3_AL_FATAL #ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE || s->s3->send_alert[1] == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE #endif ) (void)BIO_flush(s->wbio); if (s->msg_callback) s->msg_callback(1, s->version, SSL3_RT_ALERT, s->s3->send_alert, 2, s, s->msg_callback_arg); if (s->info_callback != NULL) cb=s->info_callback; else if (s->ctx->info_callback != NULL) cb=s->ctx->info_callback; if (cb != NULL) { j=(s->s3->send_alert[0]<<8)|s->s3->send_alert[1]; cb(s,SSL_CB_WRITE_ALERT,j); } } return(i); } static DTLS1_BITMAP * dtls1_get_bitmap(SSL *s, SSL3_RECORD *rr, unsigned int *is_next_epoch) { *is_next_epoch = 0; /* In current epoch, accept HM, CCS, DATA, & ALERT */ if (rr->epoch == s->d1->r_epoch) return &s->d1->bitmap; /* Only HM and ALERT messages can be from the next epoch */ else if (rr->epoch == (unsigned long)(s->d1->r_epoch + 1) && (rr->type == SSL3_RT_HANDSHAKE || rr->type == SSL3_RT_ALERT)) { *is_next_epoch = 1; return &s->d1->next_bitmap; } return NULL; } #if 0 static int dtls1_record_needs_buffering(SSL *s, SSL3_RECORD *rr, unsigned short *priority, unsigned long *offset) { /* alerts are passed up immediately */ if ( rr->type == SSL3_RT_APPLICATION_DATA || rr->type == SSL3_RT_ALERT) return 0; /* Only need to buffer if a handshake is underway. * (this implies that Hello Request and Client Hello are passed up * immediately) */ if ( SSL_in_init(s)) { unsigned char *data = rr->data; /* need to extract the HM/CCS sequence number here */ if ( rr->type == SSL3_RT_HANDSHAKE || rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) { unsigned short seq_num; struct hm_header_st msg_hdr; struct ccs_header_st ccs_hdr; if ( rr->type == SSL3_RT_HANDSHAKE) { dtls1_get_message_header(data, &msg_hdr); seq_num = msg_hdr.seq; *offset = msg_hdr.frag_off; } else { dtls1_get_ccs_header(data, &ccs_hdr); seq_num = ccs_hdr.seq; *offset = 0; } /* this is either a record we're waiting for, or a * retransmit of something we happened to previously * receive (higher layers will drop the repeat silently */ if ( seq_num < s->d1->handshake_read_seq) return 0; if (rr->type == SSL3_RT_HANDSHAKE && seq_num == s->d1->handshake_read_seq && msg_hdr.frag_off < s->d1->r_msg_hdr.frag_off) return 0; else if ( seq_num == s->d1->handshake_read_seq && (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC || msg_hdr.frag_off == s->d1->r_msg_hdr.frag_off)) return 0; else { *priority = seq_num; return 1; } } else /* unknown record type */ return 0; } return 0; } #endif void dtls1_reset_seq_numbers(SSL *s, int rw) { unsigned char *seq; unsigned int seq_bytes = sizeof(s->s3->read_sequence); if ( rw & SSL3_CC_READ) { seq = s->s3->read_sequence; s->d1->r_epoch++; memcpy(&(s->d1->bitmap), &(s->d1->next_bitmap), sizeof(DTLS1_BITMAP)); memset(&(s->d1->next_bitmap), 0x00, sizeof(DTLS1_BITMAP)); } else { seq = s->s3->write_sequence; memcpy(s->d1->last_write_sequence, seq, sizeof(s->s3->write_sequence)); s->d1->w_epoch++; } memset(seq, 0x00, seq_bytes); }
./CrossVul/dataset_final_sorted/CWE-119/c/good_1447_0
crossvul-cpp_data_good_3407_0
/* radare - LGPL - Copyright 2009-2017 // pancake */ static int cmd_mkdir(void *data, const char *input) { char *res = r_syscmd_mkdir (input); if (res) { r_cons_print (res); free (res); } return 0; } static int cmd_mv(void *data, const char *input) { return r_syscmd_mv (input)? 1: 0; } static int cmd_mount(void *data, const char *_input) { ut64 off = 0; char *input, *oinput, *ptr, *ptr2; RList *list; RListIter *iter; RFSFile *file; RFSRoot *root; RFSPlugin *plug; RFSPartition *part; RCore *core = (RCore *)data; if (!strncmp ("kdir", _input, 4)) { return cmd_mkdir (data, _input); } if (!strncmp ("v", _input, 1)) { return cmd_mv (data, _input); } input = oinput = strdup (_input); switch (*input) { case ' ': input++; if (input[0]==' ') { input++; } ptr = strchr (input, ' '); if (ptr) { *ptr = 0; ptr++; ptr2 = strchr (ptr, ' '); if (ptr2) { *ptr2 = 0; off = r_num_math (core->num, ptr2+1); } if (!r_fs_mount (core->fs, ptr, input, off)) { eprintf ("Cannot mount %s\n", input); } } else { if (!(ptr = r_fs_name (core->fs, core->offset))) { eprintf ("Unknown filesystem type\n"); } else if (!r_fs_mount (core->fs, ptr, input, core->offset)) { eprintf ("Cannot mount %s\n", input); } free (ptr); } break; case '-': r_fs_umount (core->fs, input+1); break; case '*': eprintf ("List commands in radare format\n"); r_list_foreach (core->fs->roots, iter, root) { r_cons_printf ("m %s %s 0x%"PFMT64x"\n", root-> path, root->p->name, root->delta); } break; case '\0': r_list_foreach (core->fs->roots, iter, root) { r_cons_printf ("%s\t0x%"PFMT64x"\t%s\n", root->p->name, root->delta, root->path); } break; case 'l': // list of plugins r_list_foreach (core->fs->plugins, iter, plug) { r_cons_printf ("%10s %s\n", plug->name, plug->desc); } break; case 'd': input++; if (input[0]==' ') input++; list = r_fs_dir (core->fs, input); if (list) { r_list_foreach (list, iter, file) { r_cons_printf ("%c %s\n", file->type, file->name); } r_list_free (list); } else eprintf ("Cannot open '%s' directory\n", input); break; case 'p': input++; if (*input == ' ') input++; ptr = strchr (input, ' '); if (ptr) { *ptr = 0; off = r_num_math (core->num, ptr+1); } list = r_fs_partitions (core->fs, input, off); if (list) { r_list_foreach (list, iter, part) { r_cons_printf ("%d %02x 0x%010"PFMT64x" 0x%010"PFMT64x"\n", part->number, part->type, part->start, part->start+part->length); } r_list_free (list); } else eprintf ("Cannot read partition\n"); break; case 'o': input++; if (input[0]==' ') input++; file = r_fs_open (core->fs, input); if (file) { // XXX: dump to file or just pipe? r_fs_read (core->fs, file, 0, file->size); r_cons_printf ("f file %d 0x%08"PFMT64x"\n", file->size, file->off); r_fs_close (core->fs, file); } else eprintf ("Cannot open file\n"); break; case 'g': input++; if (*input == ' ') input++; ptr = strchr (input, ' '); if (ptr) *ptr++ = 0; else ptr = "./"; file = r_fs_open (core->fs, input); if (file) { r_fs_read (core->fs, file, 0, file->size); write (1, file->data, file->size); r_fs_close (core->fs, file); write (1, "\n", 1); } else if (!r_fs_dir_dump (core->fs, input, ptr)) eprintf ("Cannot open file\n"); break; case 'f': input++; switch (*input) { case '?': r_cons_printf ( "Usage: mf[no] [...]\n" " mfn /foo *.c ; search files by name in /foo path\n" " mfo /foo 0x5e91 ; search files by offset in /foo path\n" ); break; case 'n': input++; if (*input == ' ') input++; ptr = strchr (input, ' '); if (ptr) { *ptr++ = 0; list = r_fs_find_name (core->fs, input, ptr); r_list_foreach (list, iter, ptr) { r_str_chop_path (ptr); printf ("%s\n", ptr); } //XXX: r_list_purge (list); } else eprintf ("Unknown store path\n"); break; case 'o': input++; if (*input == ' ') input++; ptr = strchr (input, ' '); if (ptr) { *ptr++ = 0; ut64 off = r_num_math (core->num, ptr); list = r_fs_find_off (core->fs, input, off); r_list_foreach (list, iter, ptr) { r_str_chop_path (ptr); printf ("%s\n", ptr); } //XXX: r_list_purge (list); } else eprintf ("Unknown store path\n"); break; } break; case 's': if (core->http_up) { free (oinput); return false; } input++; if (input[0]==' ') input++; r_fs_prompt (core->fs, input); break; case 'y': eprintf ("TODO\n"); break; case '?': { const char* help_msg[] = { "Usage:", "m[-?*dgy] [...] ", "Mountpoints management", "m", "", "List all mountpoints in human readable format", "m*", "", "Same as above, but in r2 commands", "ml", "", "List filesystem plugins", "m", " /mnt", "Mount fs at /mnt with autodetect fs and current offset", "m", " /mnt ext2 0", "Mount ext2 fs at /mnt with delta 0 on IO", "m-/", "", "Umount given path (/)", "my", "", "Yank contents of file into clipboard", "mo", " /foo", "Get offset and size of given file", "mg", " /foo", "Get contents of file/dir dumped to disk (XXX?)", "mf", "[?] [o|n]", "Search files for given filename or for offset", "md", " /", "List directory contents for path", "mp", "", "List all supported partition types", "mp", " msdos 0", "Show partitions in msdos format at offset 0", "ms", " /mnt", "Open filesystem prompt at /mnt", //"TODO: support multiple mountpoints and RFile IO's (need io+core refactorn", NULL}; r_core_cmd_help (core, help_msg); } break; } free (oinput); return 0; }
./CrossVul/dataset_final_sorted/CWE-119/c/good_3407_0
crossvul-cpp_data_bad_5827_0
/* * Audio and Video frame extraction * Copyright (c) 2003 Fabrice Bellard * Copyright (c) 2003 Michael Niedermayer * * 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 <string.h> #include "parser.h" #include "libavutil/atomic.h" #include "libavutil/mem.h" static AVCodecParser *av_first_parser = NULL; AVCodecParser* av_parser_next(AVCodecParser *p){ if(p) return p->next; else return av_first_parser; } void av_register_codec_parser(AVCodecParser *parser) { do { parser->next = av_first_parser; } while (parser->next != avpriv_atomic_ptr_cas((void * volatile *)&av_first_parser, parser->next, parser)); } AVCodecParserContext *av_parser_init(int codec_id) { AVCodecParserContext *s = NULL; AVCodecParser *parser; int ret; if(codec_id == AV_CODEC_ID_NONE) return NULL; for(parser = av_first_parser; parser != NULL; parser = parser->next) { if (parser->codec_ids[0] == codec_id || parser->codec_ids[1] == codec_id || parser->codec_ids[2] == codec_id || parser->codec_ids[3] == codec_id || parser->codec_ids[4] == codec_id) goto found; } return NULL; found: s = av_mallocz(sizeof(AVCodecParserContext)); if (!s) goto err_out; s->parser = parser; s->priv_data = av_mallocz(parser->priv_data_size); if (!s->priv_data) goto err_out; s->fetch_timestamp=1; s->pict_type = AV_PICTURE_TYPE_I; if (parser->parser_init) { ret = parser->parser_init(s); if (ret != 0) goto err_out; } s->key_frame = -1; s->convergence_duration = 0; s->dts_sync_point = INT_MIN; s->dts_ref_dts_delta = INT_MIN; s->pts_dts_delta = INT_MIN; return s; err_out: if (s) av_freep(&s->priv_data); av_free(s); return NULL; } void ff_fetch_timestamp(AVCodecParserContext *s, int off, int remove){ int i; s->dts= s->pts= AV_NOPTS_VALUE; s->pos= -1; s->offset= 0; for(i = 0; i < AV_PARSER_PTS_NB; i++) { if ( s->cur_offset + off >= s->cur_frame_offset[i] && (s->frame_offset < s->cur_frame_offset[i] || (!s->frame_offset && !s->next_frame_offset)) // first field/frame // check disabled since MPEG-TS does not send complete PES packets && /*s->next_frame_offset + off <*/ s->cur_frame_end[i]){ s->dts= s->cur_frame_dts[i]; s->pts= s->cur_frame_pts[i]; s->pos= s->cur_frame_pos[i]; s->offset = s->next_frame_offset - s->cur_frame_offset[i]; if(remove) s->cur_frame_offset[i]= INT64_MAX; if(s->cur_offset + off < s->cur_frame_end[i]) break; } } } int av_parser_parse2(AVCodecParserContext *s, AVCodecContext *avctx, uint8_t **poutbuf, int *poutbuf_size, const uint8_t *buf, int buf_size, int64_t pts, int64_t dts, int64_t pos) { int index, i; uint8_t dummy_buf[FF_INPUT_BUFFER_PADDING_SIZE]; if(!(s->flags & PARSER_FLAG_FETCHED_OFFSET)) { s->next_frame_offset = s->cur_offset = pos; s->flags |= PARSER_FLAG_FETCHED_OFFSET; } if (buf_size == 0) { /* padding is always necessary even if EOF, so we add it here */ memset(dummy_buf, 0, sizeof(dummy_buf)); buf = dummy_buf; } else if (s->cur_offset + buf_size != s->cur_frame_end[s->cur_frame_start_index]) { /* skip remainder packets */ /* add a new packet descriptor */ i = (s->cur_frame_start_index + 1) & (AV_PARSER_PTS_NB - 1); s->cur_frame_start_index = i; s->cur_frame_offset[i] = s->cur_offset; s->cur_frame_end[i] = s->cur_offset + buf_size; s->cur_frame_pts[i] = pts; s->cur_frame_dts[i] = dts; s->cur_frame_pos[i] = pos; } if (s->fetch_timestamp){ s->fetch_timestamp=0; s->last_pts = s->pts; s->last_dts = s->dts; s->last_pos = s->pos; ff_fetch_timestamp(s, 0, 0); } /* WARNING: the returned index can be negative */ index = s->parser->parser_parse(s, avctx, (const uint8_t **)poutbuf, poutbuf_size, buf, buf_size); /* update the file pointer */ if (*poutbuf_size) { /* fill the data for the current frame */ s->frame_offset = s->next_frame_offset; /* offset of the next frame */ s->next_frame_offset = s->cur_offset + index; s->fetch_timestamp=1; } if (index < 0) index = 0; s->cur_offset += index; return index; } int av_parser_change(AVCodecParserContext *s, AVCodecContext *avctx, uint8_t **poutbuf, int *poutbuf_size, const uint8_t *buf, int buf_size, int keyframe){ if(s && s->parser->split){ if((avctx->flags & CODEC_FLAG_GLOBAL_HEADER) || (avctx->flags2 & CODEC_FLAG2_LOCAL_HEADER)){ int i= s->parser->split(avctx, buf, buf_size); buf += i; buf_size -= i; } } /* cast to avoid warning about discarding qualifiers */ *poutbuf= (uint8_t *) buf; *poutbuf_size= buf_size; if(avctx->extradata){ if( (keyframe && (avctx->flags2 & CODEC_FLAG2_LOCAL_HEADER)) /*||(s->pict_type != AV_PICTURE_TYPE_I && (s->flags & PARSER_FLAG_DUMP_EXTRADATA_AT_NOKEY))*/ /*||(? && (s->flags & PARSER_FLAG_DUMP_EXTRADATA_AT_BEGIN)*/){ int size= buf_size + avctx->extradata_size; *poutbuf_size= size; *poutbuf= av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE); memcpy(*poutbuf, avctx->extradata, avctx->extradata_size); memcpy((*poutbuf) + avctx->extradata_size, buf, buf_size + FF_INPUT_BUFFER_PADDING_SIZE); return 1; } } return 0; } void av_parser_close(AVCodecParserContext *s) { if(s){ if (s->parser->parser_close) s->parser->parser_close(s); av_free(s->priv_data); av_free(s); } } /*****************************************************/ int ff_combine_frame(ParseContext *pc, int next, const uint8_t **buf, int *buf_size) { if(pc->overread){ av_dlog(NULL, "overread %d, state:%X next:%d index:%d o_index:%d\n", pc->overread, pc->state, next, pc->index, pc->overread_index); av_dlog(NULL, "%X %X %X %X\n", (*buf)[0], (*buf)[1], (*buf)[2], (*buf)[3]); } /* Copy overread bytes from last frame into buffer. */ for(; pc->overread>0; pc->overread--){ pc->buffer[pc->index++]= pc->buffer[pc->overread_index++]; } /* flush remaining if EOF */ if(!*buf_size && next == END_NOT_FOUND){ next= 0; } pc->last_index= pc->index; /* copy into buffer end return */ if(next == END_NOT_FOUND){ void* new_buffer = av_fast_realloc(pc->buffer, &pc->buffer_size, (*buf_size) + pc->index + FF_INPUT_BUFFER_PADDING_SIZE); if(!new_buffer) return AVERROR(ENOMEM); pc->buffer = new_buffer; memcpy(&pc->buffer[pc->index], *buf, *buf_size); pc->index += *buf_size; return -1; } *buf_size= pc->overread_index= pc->index + next; /* append to buffer */ if(pc->index){ void* new_buffer = av_fast_realloc(pc->buffer, &pc->buffer_size, next + pc->index + FF_INPUT_BUFFER_PADDING_SIZE); if(!new_buffer) return AVERROR(ENOMEM); pc->buffer = new_buffer; if (next > -FF_INPUT_BUFFER_PADDING_SIZE) memcpy(&pc->buffer[pc->index], *buf, next + FF_INPUT_BUFFER_PADDING_SIZE); pc->index = 0; *buf= pc->buffer; } /* store overread bytes */ for(;next < 0; next++){ pc->state = (pc->state<<8) | pc->buffer[pc->last_index + next]; pc->state64 = (pc->state64<<8) | pc->buffer[pc->last_index + next]; pc->overread++; } if(pc->overread){ av_dlog(NULL, "overread %d, state:%X next:%d index:%d o_index:%d\n", pc->overread, pc->state, next, pc->index, pc->overread_index); av_dlog(NULL, "%X %X %X %X\n", (*buf)[0], (*buf)[1],(*buf)[2],(*buf)[3]); } return 0; } void ff_parse_close(AVCodecParserContext *s) { ParseContext *pc = s->priv_data; av_freep(&pc->buffer); } /*************************/ int ff_mpeg4video_split(AVCodecContext *avctx, const uint8_t *buf, int buf_size) { int i; uint32_t state= -1; for(i=0; i<buf_size; i++){ state= (state<<8) | buf[i]; if(state == 0x1B3 || state == 0x1B6) return i-3; } return 0; }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_5827_0
crossvul-cpp_data_good_5733_0
/* * Copyright (c) 2002 Michael Niedermayer <michaelni@gmx.at> * Copyright (c) 2011 Stefano Sabatini * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with FFmpeg; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ /** * @file * Apply a boxblur filter to the input video. * Ported from MPlayer libmpcodecs/vf_boxblur.c. */ #include "libavutil/avstring.h" #include "libavutil/common.h" #include "libavutil/eval.h" #include "libavutil/opt.h" #include "libavutil/pixdesc.h" #include "avfilter.h" #include "formats.h" #include "internal.h" #include "video.h" static const char *const var_names[] = { "w", "h", "cw", "ch", "hsub", "vsub", NULL }; enum var_name { VAR_W, VAR_H, VAR_CW, VAR_CH, VAR_HSUB, VAR_VSUB, VARS_NB }; typedef struct { int radius; int power; char *radius_expr; } FilterParam; typedef struct { const AVClass *class; FilterParam luma_param; FilterParam chroma_param; FilterParam alpha_param; int hsub, vsub; int radius[4]; int power[4]; uint8_t *temp[2]; ///< temporary buffer used in blur_power() } BoxBlurContext; #define Y 0 #define U 1 #define V 2 #define A 3 static av_cold int init(AVFilterContext *ctx) { BoxBlurContext *s = ctx->priv; if (!s->luma_param.radius_expr) { av_log(ctx, AV_LOG_ERROR, "Luma radius expression is not set.\n"); return AVERROR(EINVAL); } /* fill missing params */ if (!s->chroma_param.radius_expr) { s->chroma_param.radius_expr = av_strdup(s->luma_param.radius_expr); if (!s->chroma_param.radius_expr) return AVERROR(ENOMEM); } if (s->chroma_param.power < 0) s->chroma_param.power = s->luma_param.power; if (!s->alpha_param.radius_expr) { s->alpha_param.radius_expr = av_strdup(s->luma_param.radius_expr); if (!s->alpha_param.radius_expr) return AVERROR(ENOMEM); } if (s->alpha_param.power < 0) s->alpha_param.power = s->luma_param.power; return 0; } static av_cold void uninit(AVFilterContext *ctx) { BoxBlurContext *s = ctx->priv; av_freep(&s->temp[0]); av_freep(&s->temp[1]); } static int query_formats(AVFilterContext *ctx) { static const enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_YUV444P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV411P, AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUVA420P, AV_PIX_FMT_YUV440P, AV_PIX_FMT_GRAY8, AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ440P, AV_PIX_FMT_NONE }; ff_set_common_formats(ctx, ff_make_format_list(pix_fmts)); return 0; } static int config_input(AVFilterLink *inlink) { const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format); AVFilterContext *ctx = inlink->dst; BoxBlurContext *s = ctx->priv; int w = inlink->w, h = inlink->h; int cw, ch; double var_values[VARS_NB], res; char *expr; int ret; if (!(s->temp[0] = av_malloc(FFMAX(w, h))) || !(s->temp[1] = av_malloc(FFMAX(w, h)))) return AVERROR(ENOMEM); s->hsub = desc->log2_chroma_w; s->vsub = desc->log2_chroma_h; var_values[VAR_W] = inlink->w; var_values[VAR_H] = inlink->h; var_values[VAR_CW] = cw = w>>s->hsub; var_values[VAR_CH] = ch = h>>s->vsub; var_values[VAR_HSUB] = 1<<s->hsub; var_values[VAR_VSUB] = 1<<s->vsub; #define EVAL_RADIUS_EXPR(comp) \ expr = s->comp##_param.radius_expr; \ ret = av_expr_parse_and_eval(&res, expr, var_names, var_values, \ NULL, NULL, NULL, NULL, NULL, 0, ctx); \ s->comp##_param.radius = res; \ if (ret < 0) { \ av_log(NULL, AV_LOG_ERROR, \ "Error when evaluating " #comp " radius expression '%s'\n", expr); \ return ret; \ } EVAL_RADIUS_EXPR(luma); EVAL_RADIUS_EXPR(chroma); EVAL_RADIUS_EXPR(alpha); av_log(ctx, AV_LOG_VERBOSE, "luma_radius:%d luma_power:%d " "chroma_radius:%d chroma_power:%d " "alpha_radius:%d alpha_power:%d " "w:%d chroma_w:%d h:%d chroma_h:%d\n", s->luma_param .radius, s->luma_param .power, s->chroma_param.radius, s->chroma_param.power, s->alpha_param .radius, s->alpha_param .power, w, cw, h, ch); #define CHECK_RADIUS_VAL(w_, h_, comp) \ if (s->comp##_param.radius < 0 || \ 2*s->comp##_param.radius > FFMIN(w_, h_)) { \ av_log(ctx, AV_LOG_ERROR, \ "Invalid " #comp " radius value %d, must be >= 0 and <= %d\n", \ s->comp##_param.radius, FFMIN(w_, h_)/2); \ return AVERROR(EINVAL); \ } CHECK_RADIUS_VAL(w, h, luma); CHECK_RADIUS_VAL(cw, ch, chroma); CHECK_RADIUS_VAL(w, h, alpha); s->radius[Y] = s->luma_param.radius; s->radius[U] = s->radius[V] = s->chroma_param.radius; s->radius[A] = s->alpha_param.radius; s->power[Y] = s->luma_param.power; s->power[U] = s->power[V] = s->chroma_param.power; s->power[A] = s->alpha_param.power; return 0; } static inline void blur(uint8_t *dst, int dst_step, const uint8_t *src, int src_step, int len, int radius) { /* Naive boxblur would sum source pixels from x-radius .. x+radius * for destination pixel x. That would be O(radius*width). * If you now look at what source pixels represent 2 consecutive * output pixels, then you see they are almost identical and only * differ by 2 pixels, like: * src0 111111111 * dst0 1 * src1 111111111 * dst1 1 * src0-src1 1 -1 * so when you know one output pixel you can find the next by just adding * and subtracting 1 input pixel. * The following code adopts this faster variant. */ const int length = radius*2 + 1; const int inv = ((1<<16) + length/2)/length; int x, sum = 0; for (x = 0; x < radius; x++) sum += src[x*src_step]<<1; sum += src[radius*src_step]; for (x = 0; x <= radius; x++) { sum += src[(radius+x)*src_step] - src[(radius-x)*src_step]; dst[x*dst_step] = (sum*inv + (1<<15))>>16; } for (; x < len-radius; x++) { sum += src[(radius+x)*src_step] - src[(x-radius-1)*src_step]; dst[x*dst_step] = (sum*inv + (1<<15))>>16; } for (; x < len; x++) { sum += src[(2*len-radius-x-1)*src_step] - src[(x-radius-1)*src_step]; dst[x*dst_step] = (sum*inv + (1<<15))>>16; } } static inline void blur_power(uint8_t *dst, int dst_step, const uint8_t *src, int src_step, int len, int radius, int power, uint8_t *temp[2]) { uint8_t *a = temp[0], *b = temp[1]; if (radius && power) { blur(a, 1, src, src_step, len, radius); for (; power > 2; power--) { uint8_t *c; blur(b, 1, a, 1, len, radius); c = a; a = b; b = c; } if (power > 1) { blur(dst, dst_step, a, 1, len, radius); } else { int i; for (i = 0; i < len; i++) dst[i*dst_step] = a[i]; } } else { int i; for (i = 0; i < len; i++) dst[i*dst_step] = src[i*src_step]; } } static void hblur(uint8_t *dst, int dst_linesize, const uint8_t *src, int src_linesize, int w, int h, int radius, int power, uint8_t *temp[2]) { int y; if (radius == 0 && dst == src) return; for (y = 0; y < h; y++) blur_power(dst + y*dst_linesize, 1, src + y*src_linesize, 1, w, radius, power, temp); } static void vblur(uint8_t *dst, int dst_linesize, const uint8_t *src, int src_linesize, int w, int h, int radius, int power, uint8_t *temp[2]) { int x; if (radius == 0 && dst == src) return; for (x = 0; x < w; x++) blur_power(dst + x, dst_linesize, src + x, src_linesize, h, radius, power, temp); } static int filter_frame(AVFilterLink *inlink, AVFrame *in) { AVFilterContext *ctx = inlink->dst; BoxBlurContext *s = ctx->priv; AVFilterLink *outlink = inlink->dst->outputs[0]; AVFrame *out; int plane; int cw = FF_CEIL_RSHIFT(inlink->w, s->hsub), ch = FF_CEIL_RSHIFT(in->height, s->vsub); int w[4] = { inlink->w, cw, cw, inlink->w }; int h[4] = { in->height, ch, ch, in->height }; out = ff_get_video_buffer(outlink, outlink->w, outlink->h); if (!out) { av_frame_free(&in); return AVERROR(ENOMEM); } av_frame_copy_props(out, in); for (plane = 0; plane < 4 && in->data[plane] && in->linesize[plane]; plane++) hblur(out->data[plane], out->linesize[plane], in ->data[plane], in ->linesize[plane], w[plane], h[plane], s->radius[plane], s->power[plane], s->temp); for (plane = 0; plane < 4 && in->data[plane] && in->linesize[plane]; plane++) vblur(out->data[plane], out->linesize[plane], out->data[plane], out->linesize[plane], w[plane], h[plane], s->radius[plane], s->power[plane], s->temp); av_frame_free(&in); return ff_filter_frame(outlink, out); } #define OFFSET(x) offsetof(BoxBlurContext, x) #define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM static const AVOption boxblur_options[] = { { "luma_radius", "Radius of the luma blurring box", OFFSET(luma_param.radius_expr), AV_OPT_TYPE_STRING, {.str="2"}, .flags = FLAGS }, { "lr", "Radius of the luma blurring box", OFFSET(luma_param.radius_expr), AV_OPT_TYPE_STRING, {.str="2"}, .flags = FLAGS }, { "luma_power", "How many times should the boxblur be applied to luma", OFFSET(luma_param.power), AV_OPT_TYPE_INT, {.i64=2}, 0, INT_MAX, .flags = FLAGS }, { "lp", "How many times should the boxblur be applied to luma", OFFSET(luma_param.power), AV_OPT_TYPE_INT, {.i64=2}, 0, INT_MAX, .flags = FLAGS }, { "chroma_radius", "Radius of the chroma blurring box", OFFSET(chroma_param.radius_expr), AV_OPT_TYPE_STRING, {.str=NULL}, .flags = FLAGS }, { "cr", "Radius of the chroma blurring box", OFFSET(chroma_param.radius_expr), AV_OPT_TYPE_STRING, {.str=NULL}, .flags = FLAGS }, { "chroma_power", "How many times should the boxblur be applied to chroma", OFFSET(chroma_param.power), AV_OPT_TYPE_INT, {.i64=-1}, -1, INT_MAX, .flags = FLAGS }, { "cp", "How many times should the boxblur be applied to chroma", OFFSET(chroma_param.power), AV_OPT_TYPE_INT, {.i64=-1}, -1, INT_MAX, .flags = FLAGS }, { "alpha_radius", "Radius of the alpha blurring box", OFFSET(alpha_param.radius_expr), AV_OPT_TYPE_STRING, {.str=NULL}, .flags = FLAGS }, { "ar", "Radius of the alpha blurring box", OFFSET(alpha_param.radius_expr), AV_OPT_TYPE_STRING, {.str=NULL}, .flags = FLAGS }, { "alpha_power", "How many times should the boxblur be applied to alpha", OFFSET(alpha_param.power), AV_OPT_TYPE_INT, {.i64=-1}, -1, INT_MAX, .flags = FLAGS }, { "ap", "How many times should the boxblur be applied to alpha", OFFSET(alpha_param.power), AV_OPT_TYPE_INT, {.i64=-1}, -1, INT_MAX, .flags = FLAGS }, { NULL } }; AVFILTER_DEFINE_CLASS(boxblur); static const AVFilterPad avfilter_vf_boxblur_inputs[] = { { .name = "default", .type = AVMEDIA_TYPE_VIDEO, .config_props = config_input, .filter_frame = filter_frame, }, { NULL } }; static const AVFilterPad avfilter_vf_boxblur_outputs[] = { { .name = "default", .type = AVMEDIA_TYPE_VIDEO, }, { NULL } }; AVFilter avfilter_vf_boxblur = { .name = "boxblur", .description = NULL_IF_CONFIG_SMALL("Blur the input."), .priv_size = sizeof(BoxBlurContext), .priv_class = &boxblur_class, .init = init, .uninit = uninit, .query_formats = query_formats, .inputs = avfilter_vf_boxblur_inputs, .outputs = avfilter_vf_boxblur_outputs, .flags = AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC, };
./CrossVul/dataset_final_sorted/CWE-119/c/good_5733_0
crossvul-cpp_data_good_670_0
/** * FreeRDP: A Remote Desktop Protocol Implementation * ZGFX (RDP8) Bulk Data Compression * * Copyright 2014 Marc-Andre Moreau <marcandre.moreau@gmail.com> * Copyright 2017 Armin Novak <armin.novak@thincast.com> * Copyright 2017 Thincast Technologies GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <winpr/crt.h> #include <winpr/print.h> #include <winpr/bitstream.h> #include <freerdp/log.h> #include <freerdp/codec/zgfx.h> #define TAG FREERDP_TAG("codec") /** * RDP8 Compressor Limits: * * Maximum number of uncompressed bytes in a single segment: 65535 * Maximum match distance / minimum history size: 2500000 bytes. * Maximum number of segments: 65535 * Maximum expansion of a segment (when compressed size exceeds uncompressed): 1000 bytes * Minimum match length: 3 bytes */ struct _ZGFX_TOKEN { UINT32 prefixLength; UINT32 prefixCode; UINT32 valueBits; UINT32 tokenType; UINT32 valueBase; }; typedef struct _ZGFX_TOKEN ZGFX_TOKEN; struct _ZGFX_CONTEXT { BOOL Compressor; const BYTE* pbInputCurrent; const BYTE* pbInputEnd; UINT32 bits; UINT32 cBitsRemaining; UINT32 BitsCurrent; UINT32 cBitsCurrent; BYTE OutputBuffer[65536]; UINT32 OutputCount; BYTE HistoryBuffer[2500000]; UINT32 HistoryIndex; UINT32 HistoryBufferSize; }; static const ZGFX_TOKEN ZGFX_TOKEN_TABLE[] = { // len code vbits type vbase { 1, 0, 8, 0, 0 }, // 0 { 5, 17, 5, 1, 0 }, // 10001 { 5, 18, 7, 1, 32 }, // 10010 { 5, 19, 9, 1, 160 }, // 10011 { 5, 20, 10, 1, 672 }, // 10100 { 5, 21, 12, 1, 1696 }, // 10101 { 5, 24, 0, 0, 0x00 }, // 11000 { 5, 25, 0, 0, 0x01 }, // 11001 { 6, 44, 14, 1, 5792 }, // 101100 { 6, 45, 15, 1, 22176 }, // 101101 { 6, 52, 0, 0, 0x02 }, // 110100 { 6, 53, 0, 0, 0x03 }, // 110101 { 6, 54, 0, 0, 0xFF }, // 110110 { 7, 92, 18, 1, 54944 }, // 1011100 { 7, 93, 20, 1, 317088 }, // 1011101 { 7, 110, 0, 0, 0x04 }, // 1101110 { 7, 111, 0, 0, 0x05 }, // 1101111 { 7, 112, 0, 0, 0x06 }, // 1110000 { 7, 113, 0, 0, 0x07 }, // 1110001 { 7, 114, 0, 0, 0x08 }, // 1110010 { 7, 115, 0, 0, 0x09 }, // 1110011 { 7, 116, 0, 0, 0x0A }, // 1110100 { 7, 117, 0, 0, 0x0B }, // 1110101 { 7, 118, 0, 0, 0x3A }, // 1110110 { 7, 119, 0, 0, 0x3B }, // 1110111 { 7, 120, 0, 0, 0x3C }, // 1111000 { 7, 121, 0, 0, 0x3D }, // 1111001 { 7, 122, 0, 0, 0x3E }, // 1111010 { 7, 123, 0, 0, 0x3F }, // 1111011 { 7, 124, 0, 0, 0x40 }, // 1111100 { 7, 125, 0, 0, 0x80 }, // 1111101 { 8, 188, 20, 1, 1365664 }, // 10111100 { 8, 189, 21, 1, 2414240 }, // 10111101 { 8, 252, 0, 0, 0x0C }, // 11111100 { 8, 253, 0, 0, 0x38 }, // 11111101 { 8, 254, 0, 0, 0x39 }, // 11111110 { 8, 255, 0, 0, 0x66 }, // 11111111 { 9, 380, 22, 1, 4511392 }, // 101111100 { 9, 381, 23, 1, 8705696 }, // 101111101 { 9, 382, 24, 1, 17094304 }, // 101111110 { 0 } }; static INLINE BOOL zgfx_GetBits(ZGFX_CONTEXT* _zgfx, UINT32 _nbits) { if (!_zgfx) return FALSE; while (_zgfx->cBitsCurrent < _nbits) { _zgfx->BitsCurrent <<= 8; if (_zgfx->pbInputCurrent < _zgfx->pbInputEnd) _zgfx->BitsCurrent += *(_zgfx->pbInputCurrent)++; _zgfx->cBitsCurrent += 8; } _zgfx->cBitsRemaining -= _nbits; _zgfx->cBitsCurrent -= _nbits; _zgfx->bits = _zgfx->BitsCurrent >> _zgfx->cBitsCurrent; _zgfx->BitsCurrent &= ((1 << _zgfx->cBitsCurrent) - 1); return TRUE; } static void zgfx_history_buffer_ring_write(ZGFX_CONTEXT* zgfx, const BYTE* src, size_t count) { UINT32 front; if (count <= 0) return; if (count > zgfx->HistoryBufferSize) { const size_t residue = count - zgfx->HistoryBufferSize; count = zgfx->HistoryBufferSize; src += residue; zgfx->HistoryIndex = (zgfx->HistoryIndex + residue) % zgfx->HistoryBufferSize; } if (zgfx->HistoryIndex + count <= zgfx->HistoryBufferSize) { CopyMemory(&(zgfx->HistoryBuffer[zgfx->HistoryIndex]), src, count); if ((zgfx->HistoryIndex += count) == zgfx->HistoryBufferSize) zgfx->HistoryIndex = 0; } else { front = zgfx->HistoryBufferSize - zgfx->HistoryIndex; CopyMemory(&(zgfx->HistoryBuffer[zgfx->HistoryIndex]), src, front); CopyMemory(zgfx->HistoryBuffer, &src[front], count - front); zgfx->HistoryIndex = count - front; } } static void zgfx_history_buffer_ring_read(ZGFX_CONTEXT* zgfx, int offset, BYTE* dst, UINT32 count) { UINT32 front; UINT32 index; UINT32 bytes; UINT32 valid; UINT32 bytesLeft; BYTE* dptr = dst; BYTE* origDst = dst; if (count <= 0) return; bytesLeft = count; index = (zgfx->HistoryIndex + zgfx->HistoryBufferSize - offset) % zgfx->HistoryBufferSize; bytes = MIN(bytesLeft, offset); if ((index + bytes) <= zgfx->HistoryBufferSize) { CopyMemory(dptr, &(zgfx->HistoryBuffer[index]), bytes); } else { front = zgfx->HistoryBufferSize - index; CopyMemory(dptr, &(zgfx->HistoryBuffer[index]), front); CopyMemory(&dptr[front], zgfx->HistoryBuffer, bytes - front); } if ((bytesLeft -= bytes) == 0) return; dptr += bytes; valid = bytes; do { bytes = valid; if (bytes > bytesLeft) bytes = bytesLeft; CopyMemory(dptr, origDst, bytes); dptr += bytes; valid <<= 1; } while ((bytesLeft -= bytes) > 0); } static BOOL zgfx_decompress_segment(ZGFX_CONTEXT* zgfx, wStream* stream, size_t segmentSize) { BYTE c; BYTE flags; UINT32 extra = 0; int opIndex; int haveBits; int inPrefix; UINT32 count; UINT32 distance; BYTE* pbSegment; size_t cbSegment; if (!zgfx || !stream) return FALSE; cbSegment = segmentSize - 1; if ((Stream_GetRemainingLength(stream) < segmentSize) || (segmentSize < 1) || (segmentSize > UINT32_MAX)) return FALSE; Stream_Read_UINT8(stream, flags); /* header (1 byte) */ zgfx->OutputCount = 0; pbSegment = Stream_Pointer(stream); Stream_Seek(stream, cbSegment); if (!(flags & PACKET_COMPRESSED)) { zgfx_history_buffer_ring_write(zgfx, pbSegment, cbSegment); if (cbSegment > sizeof(zgfx->OutputBuffer)) return FALSE; CopyMemory(zgfx->OutputBuffer, pbSegment, cbSegment); zgfx->OutputCount = cbSegment; return TRUE; } zgfx->pbInputCurrent = pbSegment; zgfx->pbInputEnd = &pbSegment[cbSegment - 1]; /* NumberOfBitsToDecode = ((NumberOfBytesToDecode - 1) * 8) - ValueOfLastByte */ zgfx->cBitsRemaining = 8 * (cbSegment - 1) - *zgfx->pbInputEnd; zgfx->cBitsCurrent = 0; zgfx->BitsCurrent = 0; while (zgfx->cBitsRemaining) { haveBits = 0; inPrefix = 0; for (opIndex = 0; ZGFX_TOKEN_TABLE[opIndex].prefixLength != 0; opIndex++) { while (haveBits < ZGFX_TOKEN_TABLE[opIndex].prefixLength) { zgfx_GetBits(zgfx, 1); inPrefix = (inPrefix << 1) + zgfx->bits; haveBits++; } if (inPrefix == ZGFX_TOKEN_TABLE[opIndex].prefixCode) { if (ZGFX_TOKEN_TABLE[opIndex].tokenType == 0) { /* Literal */ zgfx_GetBits(zgfx, ZGFX_TOKEN_TABLE[opIndex].valueBits); c = (BYTE)(ZGFX_TOKEN_TABLE[opIndex].valueBase + zgfx->bits); zgfx->HistoryBuffer[zgfx->HistoryIndex] = c; if (++zgfx->HistoryIndex == zgfx->HistoryBufferSize) zgfx->HistoryIndex = 0; if (zgfx->OutputCount >= sizeof(zgfx->OutputBuffer)) return FALSE; zgfx->OutputBuffer[zgfx->OutputCount++] = c; } else { zgfx_GetBits(zgfx, ZGFX_TOKEN_TABLE[opIndex].valueBits); distance = ZGFX_TOKEN_TABLE[opIndex].valueBase + zgfx->bits; if (distance != 0) { /* Match */ zgfx_GetBits(zgfx, 1); if (zgfx->bits == 0) { count = 3; } else { count = 4; extra = 2; zgfx_GetBits(zgfx, 1); while (zgfx->bits == 1) { count *= 2; extra++; zgfx_GetBits(zgfx, 1); } zgfx_GetBits(zgfx, extra); count += zgfx->bits; } if (count > sizeof(zgfx->OutputBuffer) - zgfx->OutputCount) return FALSE; zgfx_history_buffer_ring_read(zgfx, distance, &(zgfx->OutputBuffer[zgfx->OutputCount]), count); zgfx_history_buffer_ring_write(zgfx, &(zgfx->OutputBuffer[zgfx->OutputCount]), count); zgfx->OutputCount += count; } else { /* Unencoded */ zgfx_GetBits(zgfx, 15); count = zgfx->bits; zgfx->cBitsRemaining -= zgfx->cBitsCurrent; zgfx->cBitsCurrent = 0; zgfx->BitsCurrent = 0; if (count > sizeof(zgfx->OutputBuffer) - zgfx->OutputCount) return FALSE; CopyMemory(&(zgfx->OutputBuffer[zgfx->OutputCount]), zgfx->pbInputCurrent, count); zgfx_history_buffer_ring_write(zgfx, zgfx->pbInputCurrent, count); zgfx->pbInputCurrent += count; zgfx->cBitsRemaining -= (8 * count); zgfx->OutputCount += count; } } break; } } } return TRUE; } int zgfx_decompress(ZGFX_CONTEXT* zgfx, const BYTE* pSrcData, UINT32 SrcSize, BYTE** ppDstData, UINT32* pDstSize, UINT32 flags) { int status = -1; BYTE descriptor; wStream* stream = Stream_New((BYTE*)pSrcData, SrcSize); if (!stream) return -1; if (Stream_GetRemainingLength(stream) < 1) goto fail; Stream_Read_UINT8(stream, descriptor); /* descriptor (1 byte) */ if (descriptor == ZGFX_SEGMENTED_SINGLE) { if (!zgfx_decompress_segment(zgfx, stream, Stream_GetRemainingLength(stream))) goto fail; *ppDstData = NULL; if (zgfx->OutputCount > 0) *ppDstData = (BYTE*) malloc(zgfx->OutputCount); if (!*ppDstData) goto fail; *pDstSize = zgfx->OutputCount; CopyMemory(*ppDstData, zgfx->OutputBuffer, zgfx->OutputCount); } else if (descriptor == ZGFX_SEGMENTED_MULTIPART) { UINT32 segmentSize; UINT16 segmentNumber; UINT16 segmentCount; UINT32 uncompressedSize; BYTE* pConcatenated; size_t used = 0; if (Stream_GetRemainingLength(stream) < 6) goto fail; Stream_Read_UINT16(stream, segmentCount); /* segmentCount (2 bytes) */ Stream_Read_UINT32(stream, uncompressedSize); /* uncompressedSize (4 bytes) */ if (Stream_GetRemainingLength(stream) < segmentCount * sizeof(UINT32)) goto fail; pConcatenated = (BYTE*) malloc(uncompressedSize); if (!pConcatenated) goto fail; *ppDstData = pConcatenated; *pDstSize = uncompressedSize; for (segmentNumber = 0; segmentNumber < segmentCount; segmentNumber++) { if (Stream_GetRemainingLength(stream) < sizeof(UINT32)) goto fail; Stream_Read_UINT32(stream, segmentSize); /* segmentSize (4 bytes) */ if (!zgfx_decompress_segment(zgfx, stream, segmentSize)) goto fail; if (zgfx->OutputCount > UINT32_MAX - used) goto fail; if (used + zgfx->OutputCount > uncompressedSize) goto fail; CopyMemory(pConcatenated, zgfx->OutputBuffer, zgfx->OutputCount); pConcatenated += zgfx->OutputCount; used += zgfx->OutputCount; } } else { goto fail; } status = 1; fail: Stream_Free(stream, FALSE); return status; } static BOOL zgfx_compress_segment(ZGFX_CONTEXT* zgfx, wStream* s, const BYTE* pSrcData, UINT32 SrcSize, UINT32* pFlags) { /* FIXME: Currently compression not implemented. Just copy the raw source */ if (!Stream_EnsureRemainingCapacity(s, SrcSize + 1)) { WLog_ERR(TAG, "Stream_EnsureRemainingCapacity failed!"); return FALSE; } (*pFlags) |= ZGFX_PACKET_COMPR_TYPE_RDP8; /* RDP 8.0 compression format */ Stream_Write_UINT8(s, (*pFlags)); /* header (1 byte) */ Stream_Write(s, pSrcData, SrcSize); return TRUE; } int zgfx_compress_to_stream(ZGFX_CONTEXT* zgfx, wStream* sDst, const BYTE* pUncompressed, UINT32 uncompressedSize, UINT32* pFlags) { int fragment; UINT16 maxLength; UINT32 totalLength; size_t posSegmentCount = 0; const BYTE* pSrcData; int status = 0; maxLength = ZGFX_SEGMENTED_MAXSIZE; totalLength = uncompressedSize; pSrcData = pUncompressed; for (fragment = 0; (totalLength > 0) || (fragment == 0); fragment++) { UINT32 SrcSize; size_t posDstSize; size_t posDataStart; UINT32 DstSize; SrcSize = (totalLength > maxLength) ? maxLength : totalLength; posDstSize = 0; totalLength -= SrcSize; /* Ensure we have enough space for headers */ if (!Stream_EnsureRemainingCapacity(sDst, 12)) { WLog_ERR(TAG, "Stream_EnsureRemainingCapacity failed!"); return -1; } if (fragment == 0) { /* First fragment */ /* descriptor (1 byte) */ Stream_Write_UINT8(sDst, (totalLength == 0) ? ZGFX_SEGMENTED_SINGLE : ZGFX_SEGMENTED_MULTIPART); if (totalLength > 0) { posSegmentCount = Stream_GetPosition(sDst); /* segmentCount (2 bytes) */ Stream_Seek(sDst, 2); Stream_Write_UINT32(sDst, uncompressedSize); /* uncompressedSize (4 bytes) */ } } if (fragment > 0 || totalLength > 0) { /* Multipart */ posDstSize = Stream_GetPosition(sDst); /* size (4 bytes) */ Stream_Seek(sDst, 4); } posDataStart = Stream_GetPosition(sDst); if (!zgfx_compress_segment(zgfx, sDst, pSrcData, SrcSize, pFlags)) return -1; if (posDstSize) { /* Fill segment data size */ DstSize = Stream_GetPosition(sDst) - posDataStart; Stream_SetPosition(sDst, posDstSize); Stream_Write_UINT32(sDst, DstSize); Stream_SetPosition(sDst, posDataStart + DstSize); } pSrcData += SrcSize; } Stream_SealLength(sDst); /* fill back segmentCount */ if (posSegmentCount) { Stream_SetPosition(sDst, posSegmentCount); Stream_Write_UINT16(sDst, fragment); Stream_SetPosition(sDst, Stream_Length(sDst)); } return status; } int zgfx_compress(ZGFX_CONTEXT* zgfx, const BYTE* pSrcData, UINT32 SrcSize, BYTE** ppDstData, UINT32* pDstSize, UINT32* pFlags) { int status; wStream* s = Stream_New(NULL, SrcSize); status = zgfx_compress_to_stream(zgfx, s, pSrcData, SrcSize, pFlags); (*ppDstData) = Stream_Buffer(s); (*pDstSize) = Stream_GetPosition(s); Stream_Free(s, FALSE); return status; } void zgfx_context_reset(ZGFX_CONTEXT* zgfx, BOOL flush) { zgfx->HistoryIndex = 0; } ZGFX_CONTEXT* zgfx_context_new(BOOL Compressor) { ZGFX_CONTEXT* zgfx; zgfx = (ZGFX_CONTEXT*) calloc(1, sizeof(ZGFX_CONTEXT)); if (zgfx) { zgfx->Compressor = Compressor; zgfx->HistoryBufferSize = sizeof(zgfx->HistoryBuffer); zgfx_context_reset(zgfx, FALSE); } return zgfx; } void zgfx_context_free(ZGFX_CONTEXT* zgfx) { free(zgfx); }
./CrossVul/dataset_final_sorted/CWE-119/c/good_670_0
crossvul-cpp_data_bad_3406_0
/* radare - LGPL - Copyright 2009-2017 - nibble, pancake */ #if 0 * Use RList * Support callback for null command (why?) * Show help of commands - long commands not yet tested at all - added interface to export command list into an autocompletable argc, argv for dietline * r_cmd must provide a nesting char table indexing for commands - this is already partially done - this is pretty similar to r_db - every module can register their own commands - commands can be listed like in a tree #endif #define INTERACTIVE_MAX_REP 1024 #include <r_core.h> #include <r_anal.h> #include <r_cons.h> #include <stdint.h> #include <sys/types.h> #include <ctype.h> #include <stdarg.h> #if __UNIX__ #include <sys/utsname.h> #endif static void cmd_debug_reg(RCore *core, const char *str); #include "cmd_quit.c" #include "cmd_hash.c" #include "cmd_debug.c" #include "cmd_log.c" #include "cmd_zign.c" #include "cmd_section.c" #include "cmd_flag.c" #include "cmd_project.c" #include "cmd_write.c" #include "cmd_cmp.c" #include "cmd_eval.c" #include "cmd_anal.c" #include "cmd_open.c" #include "cmd_meta.c" #include "cmd_type.c" #include "cmd_egg.c" #include "cmd_info.c" #include "cmd_macro.c" #include "cmd_magic.c" #include "cmd_mount.c" #include "cmd_seek.c" #include "cmd_print.c" #include "cmd_help.c" #include "cmd_search.c" static void recursive_help(RCore *core, const char *cmd) { char *nl, *line; if (strchr (cmd, '[')) { // eprintf ("Skip ((%s))\n", cmd); return; } char *msg = r_core_cmd_str (core, cmd); if (!msg) { return; } line = msg; r_cons_print (msg); (void) r_str_ansi_filter (msg, NULL, NULL, strlen (msg)); do { nl = strchr (line, '\n'); if (nl) { *nl = 0; } if (r_cons_is_breaked ()) { break; } char *help_token = strstr (line, "[?]"); if (help_token) { help_token[0] = '?'; help_token[1] = 0; const char *sp = strchr (line, ' '); if (sp) { recursive_help (core, sp + 1); } } line = nl + 1; } while (nl); free (msg); } static int r_core_cmd_nullcallback(void *data) { RCore *core = (RCore*) data; if (core->cons->breaked) { core->cons->breaked = false; return 0; } if (!core->cmdrepeat) { return 0; } r_core_cmd_repeat (core, true); return 1; } // TODO: move somewhere else R_API RAsmOp *r_core_disassemble (RCore *core, ut64 addr) { int delta; ut8 buf[128]; static RBuffer *b = NULL; // XXX: never freed and non-thread safe. move to RCore RAsmOp *op; if (!b) { b = r_buf_new (); if (!b || !r_core_read_at (core, addr, buf, sizeof (buf))) { return NULL; } b->base = addr; r_buf_set_bytes (b, buf, sizeof (buf)); } else { if ((addr < b->base) || addr > (b->base + b->length - 32)) { if (!r_core_read_at (core, addr, buf, sizeof (buf))) { return NULL; } b->base = addr; r_buf_set_bytes (b, buf, sizeof (buf)); } } delta = addr - b->base; op = R_NEW0 (RAsmOp); r_asm_set_pc (core->assembler, addr); if (r_asm_disassemble (core->assembler, op, b->buf + delta, b->length) < 1) { free (op); return NULL; } return op; } static int cmd_uname(void *data, const char *input) { const char* help_msg[] = { "Usage:", "u", "uname or undo write/seek", "u", "", "show system uname", "uw", "", "alias for wc (requires: e io.cache=true)", "us", "", "alias for s- (seek history)", NULL}; switch (input[0]) { case '?': r_core_cmd_help (data, help_msg); return 1; case 's': r_core_cmdf (data, "s-%s", input + 1); return 1; case 'w': r_core_cmdf (data, "wc%s", input + 1); return 1; } #if __UNIX__ struct utsname un; uname (&un); r_cons_printf ("%s %s %s %s\n", un.sysname, un.nodename, un.release, un.machine); #elif __WINDOWS__ r_cons_printf ("windows\n"); #else r_cons_printf ("unknown\n"); #endif return 0; } static int cmd_alias(void *data, const char *input) { int i; char *def, *q, *desc, *buf; RCore *core = (RCore *)data; if (*input == '?') { const char* help_msg[] = { "Usage:", "$alias[=cmd] [args...]", "Alias commands", "$", "", "list all defined aliases", "$*", "", "same as above, but using r2 commands", "$", "dis='af;pdf'", "create command - analyze to show function", "$", "test=#!pipe node /tmp/test.js", "create command - rlangpipe script", "$", "dis=", "undefine alias", "$", "dis", "execute the previously defined alias", "$", "dis?", "show commands aliased by 'analyze'", NULL}; r_core_cmd_help (core, help_msg); return 0; } i = strlen (input); buf = malloc (i + 2); if (!buf) { return 0; } *buf = '$'; // prefix aliases with a dash memcpy (buf + 1, input, i + 1); q = strchr (buf, ' '); def = strchr (buf, '='); desc = strchr (buf, '?'); /* create alias */ if ((def && q && (def < q)) || (def && !q)) { *def++ = 0; size_t len = strlen (def); /* Remove quotes */ if ((def[0] == '\'') && (def[len - 1] == '\'')) { def[len - 1] = 0x00; def++; } if (!q || (q && q>def)) { if (*def) r_cmd_alias_set (core->rcmd, buf, def, 0); else r_cmd_alias_del (core->rcmd, buf); } /* Show command for alias */ } else if (desc && !q) { char *v; *desc = 0; v = r_cmd_alias_get (core->rcmd, buf, 0); if (v) { r_cons_println (v); free (buf); return 1; } else { eprintf ("unknown key '%s'\n", buf); } /* Show aliases */ } else if (buf[1] == '*') { int i, count = 0; char **keys = r_cmd_alias_keys (core->rcmd, &count); for (i = 0; i < count; i++) { const char *v = r_cmd_alias_get (core->rcmd, keys[i], 0); r_cons_printf ("%s=%s\n", keys[i], v); } } else if (!buf[1]) { int i, count = 0; char **keys = r_cmd_alias_keys (core->rcmd, &count); for (i = 0; i < count; i++) { r_cons_println (keys[i]); } /* Execute alias */ } else { char *v; if (q) *q = 0; v = r_cmd_alias_get (core->rcmd, buf, 0); if (v) { if (q) { char *out, *args = q + 1; out = malloc (strlen (v) + strlen (args) + 2); if (out) { //XXX slow strcpy (out, v); strcat (out, " "); strcat (out, args); r_core_cmd0 (core, out); free (out); } else eprintf ("cannot malloc\n"); } else { r_core_cmd0 (core, v); } } else { eprintf ("unknown key '%s'\n", buf); } } free (buf); return 0; } static int getArg(char ch, int def) { switch (ch) { case '&': case '-': return ch; } return def; } static void aliascmd(RCore *core, const char *str) { switch (str[0]) { case '-': if (str[1]) { r_cmd_alias_del (core->rcmd, str + 2); } else { r_cmd_alias_del (core->rcmd, NULL); // r_cmd_alias_reset (core->rcmd); } break; case '?': eprintf ("Usage: =$[-][remotecmd] # remote command alias\n"); eprintf (" =$dr # makes 'dr' alias for =!dr\n"); eprintf (" =$-dr # unset 'dr' alias\n"); break; case 0: r_core_cmd0 (core, "$"); break; default: r_cmd_alias_set (core->rcmd, str, "", 1); break; } } static int cmd_rap(void *data, const char *input) { RCore *core = (RCore *)data; switch (*input) { case '$': aliascmd (core, input + 1); break; case '\0': r_core_rtr_list (core); break; case 'h': r_core_rtr_http (core, getArg (input[1], 'h'), input + 1); break; case 'H': while (input[1] == ' ') { input++; } r_core_rtr_http (core, getArg (input[1], 'H'), input + 1); break; case 'g': r_core_rtr_gdb (core, getArg (input[1], 'g'), input + 1); break; case '?': r_core_rtr_help (core); break; case '+': r_core_rtr_add (core, input + 1); break; case '-': r_core_rtr_remove (core, input + 1); break; case '=': r_core_rtr_session (core, input + 1); break; //case ':': r_core_rtr_cmds (core, input + 1); break; case '<': r_core_rtr_pushout (core, input + 1); break; case '!': if (input[1] == '=') { // swap core->cmdremote = core->cmdremote? 0: 1; core->cmdremote = input[2]? 1: 0; r_cons_println (r_str_bool (core->cmdremote)); } else { r_io_system (core->io, input + 1); } break; default: r_core_rtr_cmd (core, input); break; } return 0; } static int cmd_rap_run(void *data, const char *input) { RCore *core = (RCore *)data; return r_io_system (core->io, input); } static int cmd_yank(void *data, const char *input) { ut64 n; RCore *core = (RCore *)data; switch (input[0]) { case ' ': r_core_yank (core, core->offset, r_num_math (core->num, input + 1)); break; case 'l': core->num->value = core->yank_buf->length; break; case 'y': while (input[1] == ' ') { input++; } n = input[1]? r_num_math (core->num, input + 1): core->offset; r_core_yank_paste (core, n, 0); break; case 'x': r_core_yank_hexdump (core, r_num_math (core->num, input + 1)); break; case 'z': r_core_yank_string (core, core->offset, r_num_math (core->num, input + 1)); break; case 'w': switch (input[1]) { case ' ': r_core_yank_set (core, 0, (const ut8*)input + 2, strlen (input + 2)); break; case 'x': if (input[2] == ' ') { char *out = strdup (input + 3); int len = r_hex_str2bin (input + 3, (ut8*)out); if (len> 0) { r_core_yank_set (core, 0LL, (const ut8*)out, len); } else { eprintf ("Invalid length\n"); } free (out); } else { eprintf ("Usage: ywx [hexpairs]\n"); } // r_core_yank_write_hex (core, input + 2); break; } break; case 'p': r_core_yank_cat (core, r_num_math (core->num, input + 1)); break; case 's': r_core_yank_cat_string (core, r_num_math (core->num, input + 1)); break; case 't': // "wt" if (input[1] == 'f') { // "wtf" const char *file = r_str_chop_ro (input + 2); if (!r_file_dump (file, core->yank_buf->buf, core->yank_buf->length, false)) { eprintf ("Cannot dump to '%s'\n", file); } } else { r_core_yank_to (core, input + 1); } break; case 'f': switch (input[1]) { case ' ': // "wf" r_core_yank_file_ex (core, input + 1); break; case 'a': // "wfa" r_core_yank_file_all (core, input + 2); break; } break; case '\0': r_core_yank_dump (core, r_num_math (core->num, "")); break; default:{ const char* help_msg[] = { "Usage:", "y[ptxy] [len] [[@]addr]", " # See wd? for memcpy, same as 'yf'.", "y", "", "show yank buffer information (srcoff len bytes)", "y", " 16", "copy 16 bytes into clipboard", "y", " 16 0x200", "copy 16 bytes into clipboard from 0x200", "y", " 16 @ 0x200", "copy 16 bytes into clipboard from 0x200", "yz", "", "copy up to blocksize zero terminated string bytes into clipboard", "yz", " 16", "copy up to 16 zero terminated string bytes into clipboard", "yz", " @ 0x200", "copy up to blocksize zero terminated string bytes into clipboard from 0x200", "yz", " 16 @ 0x200", "copy up to 16 zero terminated string bytes into clipboard from 0x200", "yp", "", "print contents of clipboard", "yx", "", "print contents of clipboard in hexadecimal", "ys", "", "print contents of clipboard as string", "yt", " 64 0x200", "copy 64 bytes from current seek to 0x200", "ytf", " file", "dump the clipboard to given file", "yf", " 64 0x200", "file copy 64 bytes from 0x200 from file (opens w/ io), use -1 for all bytes", "yfa", " file copy", "copy all bytes from file (opens w/ io)", "yy", " 0x3344", "paste clipboard", NULL}; r_core_cmd_help (core, help_msg); } break; } return true; } R_API int r_core_run_script (RCore *core, const char *file) { int ret = false; RListIter *iter; RLangPlugin *p; char *name; r_list_foreach (core->scriptstack, iter, name) { if (!strcmp (file, name)) { eprintf ("WARNING: ignored nested source: %s\n", file); return false; } } r_list_push (core->scriptstack, strdup (file)); if (!strcmp (file, "-")) { char *out = r_core_editor (core, NULL, NULL); if (out) { ret = r_core_cmd_lines (core, out); free (out); } } else if (r_parse_is_c_file (file)) { char *out = r_parse_c_file (core->anal, file); if (out) { r_cons_strcat (out); sdb_query_lines (core->anal->sdb_types, out); free (out); } ret = out? true: false; } else { p = r_lang_get_by_extension (core->lang, file); if (p) { r_lang_use (core->lang, p->name); ret = r_lang_run_file (core->lang, file); } else { #if __WINDOWS__ #define cmdstr(x) r_str_newf (x" %s", file); #else #define cmdstr(x) r_str_newf (x" '%s'", file); #endif const char *p = r_str_lchr (file, '.'); if (p) { const char *ext = p + 1; /* TODO: handle this inside r_lang_pipe with new APIs */ if (!strcmp (ext, "js")) { char *cmd = cmdstr ("node"); r_lang_use (core->lang, "pipe"); r_lang_run_file (core->lang, cmd); free (cmd); ret = 1; } else if (!strcmp (ext, "exe")) { #if __WINDOWS__ char *cmd = r_str_newf ("%s", file); #else char *cmd = cmdstr ("wine"); #endif r_lang_use (core->lang, "pipe"); r_lang_run_file (core->lang, cmd); free (cmd); ret = 1; } else if (!strcmp (ext, "d")) { char *cmd = cmdstr ("dmd -run"); r_lang_use (core->lang, "pipe"); r_lang_run_file (core->lang, cmd); free (cmd); ret = 1; } else if (!strcmp (ext, "lsp")) { char *cmd = cmdstr ("newlisp -n"); r_lang_use (core->lang, "pipe"); r_lang_run_file (core->lang, cmd); free (cmd); ret = 1; } else if (!strcmp (ext, "go")) { char *cmd = cmdstr ("go run"); r_lang_use (core->lang, "pipe"); r_lang_run_file (core->lang, cmd); free (cmd); ret = 1; } else if (!strcmp (ext, "es6")) { char *cmd = cmdstr ("babel-node"); r_lang_use (core->lang, "pipe"); r_lang_run_file (core->lang, cmd); free (cmd); ret = 1; } else if (!strcmp (ext, "rb")) { char *cmd = cmdstr ("ruby %s"); r_lang_use (core->lang, "pipe"); r_lang_run_file (core->lang, cmd); free (cmd); ret = 1; } else if (!strcmp (ext, "pl")) { char *cmd = cmdstr ("perl"); r_lang_use (core->lang, "pipe"); r_lang_run_file (core->lang, cmd); free (cmd); ret = 1; } else if (!strcmp (ext, "py")) { char *cmd = cmdstr ("python"); r_lang_use (core->lang, "pipe"); r_lang_run_file (core->lang, cmd); free (cmd); ret = 1; } } if (!ret) { ret = r_core_cmd_file (core, file); } } } free (r_list_pop (core->scriptstack)); return ret; } static int cmd_ls(void *data, const char *input) { if (*input) { char *res = r_syscmd_ls (input + 1); if (res) { r_cons_print (res); free (res); } } return 0; } static int cmd_stdin(void *data, const char *input) { RCore *core = (RCore *)data; if (input[0] == '?') { r_cons_printf ("Usage: '-' '.-' '. -' do the same\n"); return false; } return r_core_run_script (core, "-"); } static int cmd_interpret(void *data, const char *input) { char *str, *ptr, *eol, *rbuf, *filter, *inp; const char *host, *port, *cmd; RCore *core = (RCore *)data; switch (*input) { case '\0': r_core_cmd_repeat (core, 0); break; case ':': if ((ptr = strchr (input + 1, ' '))) { /* .:port cmd */ /* .:host:port cmd */ cmd = ptr + 1; *ptr = 0; eol = strchr (input + 1, ':'); if (eol) { *eol = 0; host = input + 1; port = eol + 1; } else { host = "localhost"; port = input + ((input[1] == ':')? 2: 1); } rbuf = r_core_rtr_cmds_query (core, host, port, cmd); if (rbuf) { r_cons_print (rbuf); free (rbuf); } } else { r_core_rtr_cmds (core, input + 1); } break; case '.': // same as \n r_core_cmd_repeat (core, 1); break; case '-': if (input[1] == '?') { r_cons_printf ("Usage: '-' '.-' '. -' do the same\n"); } else { r_core_run_script (core, "-"); } break; case ' ': if (!r_core_run_script (core, input + 1)) { eprintf ("Cannot find script '%s'\n", input + 1); core->num->value = 1; } else { core->num->value = 0; } break; case '!': /* from command */ r_core_cmd_command (core, input + 1); break; case '(': r_cmd_macro_call (&core->rcmd->macro, input + 1); break; case '?':{ const char* help_msg[] = { "Usage:", ".[r2cmd] | [file] | [!command] | [(macro)]", " # define macro or load r2, cparse or rlang file", ".", "", "repeat last command backward", ".", "r2cmd", "interpret the output of the command as r2 commands", "..", "", "repeat last command forward (same as \\n)", ".:", "8080", "listen for commands on given tcp port", ".", " foo.r2", "interpret r2 script", ".-", "", "open cfg.editor and interpret tmp file", ".!", "rabin -ri $FILE", "interpret output of command", ".", "(foo 1 2 3)", "run macro 'foo' with args 1, 2, 3", "./", " ELF", "interpret output of command /m ELF as r. commands", NULL}; r_core_cmd_help (core, help_msg); } break; default: if (*input >= 0 && *input <= 9) { eprintf ("|ERROR| No .[0..9] to avoid infinite loops\n"); break; } inp = strdup (input); filter = strchr (inp, '~'); if (filter) { *filter = 0; } ptr = str = r_core_cmd_str (core, inp); if (filter) { *filter = '~'; } r_cons_break_push (NULL, NULL); if (ptr) { for (;;) { if (r_cons_is_breaked ()) { break; } eol = strchr (ptr, '\n'); if (eol) *eol = '\0'; if (*ptr) { char *p = r_str_append (strdup (ptr), filter); r_core_cmd0 (core, p); free (p); } if (!eol) break; ptr = eol + 1; } } r_cons_break_pop (); free (str); free (inp); break; } return 0; } static int callback_foreach_kv (void *user, const char *k, const char *v) { r_cons_printf ("%s=%s\n", k, v); return 1; } static int cmd_kuery(void *data, const char *input) { char buf[1024], *out; RCore *core = (RCore*)data; const char *sp, *p = "[sdb]> "; const int buflen = sizeof (buf) - 1; Sdb *s = core->sdb; switch (input[0]) { case ' ': out = sdb_querys (s, NULL, 0, input + 1); if (out) { r_cons_println (out); } free (out); break; //case 's': r_pair_save (s, input + 3); break; //case 'l': r_pair_load (sdb, input + 3); break; case '\0': sdb_foreach (s, callback_foreach_kv, NULL); break; // TODO: add command to list all namespaces // sdb_ns_foreach ? case 's': if (core->http_up) { return false; } if (!r_config_get_i (core->config, "scr.interactive")) { return false; } if (input[1] == ' ') { char *n, *o, *p = strdup (input + 2); // TODO: slash split here? or inside sdb_ns ? for (n = o = p; n; o = n) { n = strchr (o, '/'); // SDB_NS_SEPARATOR NAMESPACE if (n) *n++ = 0; s = sdb_ns (s, o, 1); } free (p); } if (!s) s = core->sdb; for (;;) { r_line_set_prompt (p); if (r_cons_fgets (buf, buflen, 0, NULL) < 1) break; if (!*buf) break; out = sdb_querys (s, NULL, 0, buf); if (out) { r_cons_println (out); } } break; case 'o': if (r_sandbox_enable (0)) { eprintf ("This command is disabled in sandbox mode\n"); return 0; } if (input[1] == ' ') { char *fn = strdup (input + 2); if (!fn) { eprintf("Unable to allocate memory\n"); return 0; } char *ns = strchr (fn, ' '); if (ns) { Sdb *db; *ns++ = 0; if (r_file_exists (fn)) { db = sdb_ns_path (core->sdb, ns, 1); if (db) { Sdb *newdb = sdb_new (NULL, fn, 0); if (newdb) { sdb_drain (db, newdb); } else { eprintf ("Cannot open sdb '%s'\n", fn); } } else eprintf ("Cannot find sdb '%s'\n", ns); } else eprintf ("Cannot open file\n"); } else eprintf ("Missing sdb namespace\n"); free (fn); } else { eprintf ("Usage: ko [file] [namespace]\n"); } break; case 'd': if (r_sandbox_enable (0)) { eprintf ("This command is disabled in sandbox mode\n"); return 0; } if (input[1] == ' ') { char *fn = strdup (input + 2); char *ns = strchr (fn, ' '); if (ns) { *ns++ = 0; Sdb *db = sdb_ns_path (core->sdb, ns, 0); if (db) { sdb_file (db, fn); sdb_sync (db); } else eprintf ("Cannot find sdb '%s'\n", ns); } else eprintf ("Missing sdb namespace\n"); free (fn); } else { eprintf ("Usage: kd [file] [namespace]\n"); } break; case '?': { const char* help_msg[] = { "Usage:", "k[s] [key[=value]]", "Sdb Query", "k", " foo=bar", "set value", "k", " foo", "show value", "k", "", "list keys", "ko", " [file.sdb] [ns]", "open file into namespace", "kd", " [file.sdb] [ns]", "dump namespace to disk", "ks", " [ns]", "enter the sdb query shell", "k", " anal/meta/*", "ist kv from anal > meta namespaces", "k", " anal/**", "list namespaces under anal", "k", " anal/meta/meta.0x80404", "get value for meta.0x80404 key", //"kl", " ha.sdb", "load keyvalue from ha.sdb", //"ks", " ha.sdb", "save keyvalue to ha.sdb", NULL, }; r_core_cmd_help (core, help_msg); } break; } if (input[0] == '\0') { /* nothing more to do, the command has been parsed. */ return 0; } sp = strchr (input + 1, ' '); if (sp) { char *inp = strdup (input); inp [(size_t)(sp - input)] = 0; s = sdb_ns (core->sdb, inp + 1, 1); out = sdb_querys (s, NULL, 0, sp + 1); if (out) { r_cons_println (out); free (out); } free (inp); return 0; } return 0; } static int cmd_bsize(void *data, const char *input) { ut64 n; RFlagItem *flag; RCore *core = (RCore *)data; switch (input[0]) { case 'm': n = r_num_math (core->num, input + 1); if (n > 1) core->blocksize_max = n; else r_cons_printf ("0x%x\n", (ut32)core->blocksize_max); break; case '+': n = r_num_math (core->num, input + 1); r_core_block_size (core, core->blocksize + n); break; case '-': n = r_num_math (core->num, input + 1); r_core_block_size (core, core->blocksize - n); break; case 'f': if (input[1] == ' ') { flag = r_flag_get (core->flags, input + 2); if (flag) { r_core_block_size (core, flag->size); } else { eprintf ("bf: cannot find flag named '%s'\n", input + 2); } } else { eprintf ("Usage: bf [flagname]\n"); } break; case '\0': r_cons_printf ("0x%x\n", core->blocksize); break; case '?':{ const char* help_msg[] = { "Usage:", "b[f] [arg]\n", "Get/Set block size", "b", "", "display current block size", "b", " 33", "set block size to 33", "b", "+3", "increase blocksize by 3", "b", "-16", "decrease blocksize by 16", "b", " eip+4", "numeric argument can be an expression", "bf", " foo", "set block size to flag size", "bm", " 1M", "set max block size", NULL }; r_core_cmd_help (core, help_msg); } break; default: //input = r_str_clean(input); r_core_block_size (core, r_num_math (core->num, input)); break; } return 0; } static int cmd_resize(void *data, const char *input) { RCore *core = (RCore *)data; ut64 oldsize, newsize = 0; st64 delta = 0; int grow, ret; if (core->file && core->file->desc) oldsize = r_io_desc_size (core->io, core->file->desc); else oldsize = 0; switch (*input) { case '2': // TODO: use argv[0] instead of 'radare2' r_sys_cmdf ("radare%s", input); return true; case 'm': if (input[1] == ' ') r_file_rm (input + 2); else eprintf ("Usage: rm [file] # removes a file\n"); return true; case '\0': if (core->file && core->file->desc) { if (oldsize != -1) { r_cons_printf ("%"PFMT64d"\n", oldsize); } } return true; case '+': case '-': delta = (st64)r_num_math (core->num, input); newsize = oldsize + delta; break; case ' ': newsize = r_num_math (core->num, input + 1); if (newsize == 0) { if (input[1] == '0') eprintf ("Invalid size\n"); return false; } break; default: case '?':{ const char* help_msg[] = { "Usage:", "r[+-][ size]", "Resize file", "r", "", "display file size", "r", " size", "expand or truncate file to given size", "r-", "num", "remove num bytes, move following data down", "r+", "num", "insert num bytes, move following data up", "rm" ," [file]", "remove file", "r2" ," [file]", "launch r2", NULL}; r_core_cmd_help (core, help_msg); } return true; } grow = (newsize > oldsize); if (grow) { ret = r_io_resize (core->io, newsize); if (ret < 1) eprintf ("r_io_resize: cannot resize\n"); } if (delta && core->offset < newsize) r_io_shift (core->io, core->offset, grow?newsize:oldsize, delta); if (!grow) { ret = r_io_resize (core->io, newsize); if (ret < 1) eprintf ("r_io_resize: cannot resize\n"); } if (newsize < core->offset+core->blocksize || oldsize < core->offset + core->blocksize) { r_core_block_read (core); } return true; } static int cmd_visual(void *data, const char *input) { RCore *core = (RCore*) data; if (core->http_up) { return false; } if (!r_config_get_i (core->config, "scr.interactive")) { return false; } return r_core_visual ((RCore *)data, input); } static int task_finished(void *user, void *data) { eprintf ("TASK FINISHED\n"); return 0; } static int taskbgrun(RThread *th) { char *res; RCoreTask *task = th->user; RCore *core = task->core; close (2); // no stderr res = r_core_cmd_str (core, task->msg->text); task->msg->res = res; task->state = 'd'; eprintf ("Task %d finished\n", task->id); // TODO: run callback and pass result return 0; } static int cmd_thread(void *data, const char *input) { RCore *core = (RCore*) data; if (r_sandbox_enable (0)) { eprintf ("This command is disabled in sandbox mode\n"); return 0; } switch (input[0]) { case '\0': case 'j': r_core_task_list (core, *input); break; case '&': if (input[1] == '&') { // wait until ^C } else { int tid = r_num_math (core->num, input + 1); if (tid) { RCoreTask *task = r_core_task_get (core, tid); if (task) { r_core_task_join (core, task); } else eprintf ("Cannot find task\n"); } else { r_core_task_run (core, NULL); } } break; case '=': { int tid = r_num_math (core->num, input + 1); if (tid) { RCoreTask *task = r_core_task_get (core, tid); if (task) { r_cons_printf ("Task %d Status %c Command %s\n", task->id, task->state, task->msg->text); if (task->msg->res) r_cons_println (task->msg->res); } else eprintf ("Cannot find task\n"); } else { r_core_task_list (core, 1); }} break; case '+': r_core_task_add (core, r_core_task_new (core, input + 1, (RCoreTaskCallback)task_finished, core)); break; case '-': if (input[1] == '*') { r_core_task_del (core, -1); } else { r_core_task_del (core, r_num_math (core->num, input + 1)); } break; case '?': { helpCmdTasks (core); } break; case ' ': { int tid = r_num_math (core->num, input + 1); if (tid) { RCoreTask *task = r_core_task_get (core, tid); if (task) { r_core_task_join (core, task); } else { eprintf ("Cannot find task\n"); } } else { RCoreTask *task = r_core_task_add (core, r_core_task_new ( core, input + 1, (RCoreTaskCallback)task_finished, core)); RThread *th = r_th_new (taskbgrun, task, 0); task->msg->th = th; } //r_core_cmd0 (core, task->msg->text); //r_core_task_del (core, task->id); } break; default: eprintf ("&?\n"); break; } return 0; } static int cmd_pointer(void *data, const char *input) { RCore *core = (RCore*) data; int ret = true; char *str, *eq; while (*input == ' ') input++; if (!*input || *input == '?') { const char* help_msg[] = { "Usage:", "*<addr>[=[0x]value]", "Pointer read/write data/values", "*", "entry0=cc", "write trap in entrypoint", "*", "entry0+10=0x804800", "write value in delta address", "*", "entry0", "read byte at given address", "TODO: last command should honor asm.bits", "", "", NULL}; r_core_cmd_help (core, help_msg); return ret; } str = strdup (input); eq = strchr (str, '='); if (eq) { *eq++ = 0; if (!strncmp (eq, "0x", 2)) { ret = r_core_cmdf (core, "wv %s@%s", eq, str); } else { ret = r_core_cmdf (core, "wx %s@%s", eq, str); } } else { ret = r_core_cmdf (core, "?v [%s]", input); } free (str); return ret; } static int cmd_env(void *data, const char *input) { RCore *core = (RCore*)data; int ret = true; switch (*input) { case '?': { const char* help_msg[] = { "Usage:", "%[name[=value]]", "Set each NAME to VALUE in the environment", "%", "", "list all environment variables", "%", "SHELL", "prints SHELL value", "%", "TMPDIR=/tmp", "sets TMPDIR value to \"/tmp\"", NULL}; r_core_cmd_help (core, help_msg); } break; default: ret = r_core_cmdf (core, "env %s", input); } return ret; } static int cmd_system(void *data, const char *input) { RCore *core = (RCore*)data; ut64 n; int ret = 0; switch (*input) { case '=': if (input[1] == '?') { r_cons_printf ("Usage: !=[!] - enable/disable remote commands\n"); } else { if (!r_sandbox_enable (0)) { core->cmdremote = input[1]? 1: 0; r_cons_println (r_str_bool (core->cmdremote)); } } break; case '!': if (r_sandbox_enable (0)) { eprintf ("This command is disabled in sandbox mode\n"); return 0; } if (input[1]) { int olen; char *out = NULL; char *cmd = r_core_sysenv_begin (core, input); if (cmd) { ret = r_sys_cmd_str_full (cmd + 1, NULL, &out, &olen, NULL); r_core_sysenv_end (core, input); r_cons_memcat (out, olen); free (out); free (cmd); } //else eprintf ("Error setting up system environment\n"); } else { eprintf ("History saved to "R2_HOMEDIR"/history\n"); r_line_hist_save (R2_HOMEDIR"/history"); } break; case '\0': r_line_hist_list (); break; case '?': r_core_sysenv_help (core); break; default: n = atoi (input); if (*input == '0' || n > 0) { const char *cmd = r_line_hist_get (n); if (cmd) r_core_cmd0 (core, cmd); //else eprintf ("Error setting up system environment\n"); } else { char *cmd = r_core_sysenv_begin (core, input); if (cmd) { ret = r_sys_cmd (cmd); r_core_sysenv_end (core, input); free (cmd); } else eprintf ("Error setting up system environment\n"); } break; } return ret; } R_API int r_core_cmd_pipe(RCore *core, char *radare_cmd, char *shell_cmd) { #if __UNIX__ || __CYGWIN__ int stdout_fd, fds[2]; int child; #endif int si, olen, ret = -1, pipecolor = -1; char *str, *out = NULL; if (r_sandbox_enable (0)) { eprintf ("Pipes are not allowed in sandbox mode\n"); return -1; } si = r_config_get_i (core->config, "scr.interactive"); r_config_set_i (core->config, "scr.interactive", 0); if (!r_config_get_i (core->config, "scr.pipecolor")) { pipecolor = r_config_get_i (core->config, "scr.color"); r_config_set_i (core->config, "scr.color", 0); } if (*shell_cmd=='!') { r_cons_grep_parsecmd (shell_cmd, "\""); olen = 0; out = NULL; // TODO: implement foo str = r_core_cmd_str (core, radare_cmd); r_sys_cmd_str_full (shell_cmd + 1, str, &out, &olen, NULL); free (str); r_cons_memcat (out, olen); free (out); ret = 0; } #if __UNIX__ || __CYGWIN__ radare_cmd = (char*)r_str_trim_head (radare_cmd); shell_cmd = (char*)r_str_trim_head (shell_cmd); signal (SIGPIPE, SIG_IGN); stdout_fd = dup (1); if (stdout_fd != -1) { pipe (fds); child = r_sys_fork (); if (child == -1) { eprintf ("Cannot fork\n"); close (stdout_fd); } else if (child) { dup2 (fds[1], 1); close (fds[1]); close (fds[0]); r_core_cmd (core, radare_cmd, 0); r_cons_flush (); close (1); wait (&ret); dup2 (stdout_fd, 1); close (stdout_fd); } else { close (fds[1]); dup2 (fds[0], 0); //dup2 (1, 2); // stderr goes to stdout r_sandbox_system (shell_cmd, 0); close (stdout_fd); } } #else #ifdef _MSC_VER #pragma message ("r_core_cmd_pipe UNIMPLEMENTED FOR THIS PLATFORM") #else #warning r_core_cmd_pipe UNIMPLEMENTED FOR THIS PLATFORM #endif eprintf ("r_core_cmd_pipe: unimplemented for this platform\n"); #endif if (pipecolor != -1) r_config_set_i (core->config, "scr.color", pipecolor); r_config_set_i (core->config, "scr.interactive", si); return ret; } static char *parse_tmp_evals(RCore *core, const char *str) { char *res = NULL; RStrBuf *buf; char *s = strdup (str); buf = r_strbuf_new (""); int i, argc = r_str_split (s, ','); for (i = 0; i < argc; i++) { char *eq, *kv = (char *)r_str_word_get0 (s, i); if (!kv) { break; } eq = strchr (kv, '='); if (eq) { *eq = 0; const char *ov = r_config_get (core->config, kv); r_strbuf_appendf (buf, "e %s=%s;", kv, ov); r_config_set (core->config, kv, eq + 1); *eq = '='; } else { eprintf ("Missing '=' in e: expression (%s)\n", kv); } } res = r_strbuf_drain (buf); free (s); return res; } static int r_core_cmd_subst_i(RCore *core, char *cmd, char* colon); static int r_core_cmd_subst(RCore *core, char *cmd) { int ret = 0, rep = atoi (cmd), orep; char *cmt, *colon = NULL, *icmd = strdup (cmd); const char *cmdrep = NULL; cmd = r_str_trim_head_tail (icmd); // lines starting with # are ignored (never reach cmd_hash()), except #! and #? if (!icmd || (cmd[0] == '#' && cmd[1] != '!' && cmd[1] != '?')) { goto beach; } cmt = *icmd ? strchr (icmd + 1, '#'): NULL; if (cmt && (cmt[1] == ' ' || cmt[1] == '\t')) { *cmt = 0; } if (*cmd != '"') { if (!strchr (cmd, '\'')) { // allow | awk '{foo;bar}' // ignore ; if there's a single quote if ((colon = strchr (cmd, ';'))) { *colon = 0; } } } else { colon = NULL; } if (rep > 0) { while (IS_DIGIT(*cmd)) { cmd++; } // do not repeat null cmd if (!*cmd) { goto beach; } } if (rep < 1) { rep = 1; } // XXX if output is a pipe then we dont want to be interactive if (rep > 1 && r_sandbox_enable (0)) { eprintf ("Command repeat sugar disabled in sandbox mode (%s)\n", cmd); goto beach; } else { if (rep > INTERACTIVE_MAX_REP) { if (r_config_get_i (core->config, "scr.interactive")) { if (!r_cons_yesno ('n', "Are you sure to repeat this %d times? (y/N)", rep)) { goto beach; } } } } // TODO: store in core->cmdtimes to speedup ? cmdrep = r_config_get (core->config, "cmd.times"); if (!cmdrep) { cmdrep = ""; } orep = rep; int ocur_enabled = core->print->cur_enabled; while (rep-- && *cmd) { core->print->cur_enabled = false; if (ocur_enabled && core->seltab >= 0) { if (core->seltab == core->curtab) { core->print->cur_enabled = true; } } char *cr = strdup (cmdrep); core->break_loop = false; ret = r_core_cmd_subst_i (core, cmd, colon); if (ret && *cmd == 'q') { free (cr); goto beach; } if (core->break_loop) { break; } if (cr && *cr) { if (orep > 1) { // XXX: do not flush here, we need r_cons_push () and r_cons_pop() r_cons_flush (); // XXX: we must import register flags in C (void)r_core_cmd0 (core, ".dr*"); (void)r_core_cmd0 (core, cr); } } free (cr); } core->print->cur_enabled = ocur_enabled; if (colon && colon[1]) { for (++colon; *colon == ';'; colon++); r_core_cmd_subst (core, colon); } else { if (!*icmd) { r_core_cmd_nullcallback (core); } } beach: free (icmd); return ret; } static char *find_eoq(char *p) { for (; *p; p++) { if (*p == '"') { break; } if (*p == '\\' && p[1] == '"') { p++; } } return p; } static char* findSeparator(char *p) { char *q = strchr (p, '+'); if (q) { return q; } return strchr (p, '-'); } static int r_core_cmd_subst_i(RCore *core, char *cmd, char *colon) { const char *quotestr = "`"; const char *tick = NULL; char *ptr, *ptr2, *str; char *arroba = NULL; int i, ret = 0, pipefd; bool usemyblock = false; int scr_html = -1; int scr_color = -1; bool eos = false; bool haveQuote = false; if (!cmd) { return 0; } cmd = r_str_trim_head_tail (cmd); /* quoted / raw command */ switch (*cmd) { case '.': if (cmd[1] == '"') { /* interpret */ return r_cmd_call (core->rcmd, cmd); } break; case '"': for (; *cmd; ) { int pipefd = -1; ut64 oseek = UT64_MAX; char *line, *p; haveQuote = *cmd == '"'; if (haveQuote) { // *cmd = 0; cmd++; p = find_eoq (cmd + 1); if (!p || !*p) { eprintf ("Missing \" in (%s).", cmd); return false; } *p++ = 0; if (!*p) { eos = true; } } else { char *sc = strchr (cmd, ';'); if (sc) { *sc = 0; } r_core_cmd0 (core, cmd); if (!sc) { break; } cmd = sc + 1; continue; } if (p[0]) { // workaround :D if (p[0] == '@') { p--; } while (p[1] == ';' || IS_WHITESPACE (p[1])) { p++; } if (p[1] == '@' || (p[1] && p[2] == '@')) { char *q = strchr (p + 1, '"'); if (q) { *q = 0; } haveQuote = q != NULL; oseek = core->offset; r_core_seek (core, r_num_math (core->num, p + 2), 1); if (q) { *p = '"'; p = q; } else { p = strchr (p + 1, ';'); } } if (p && *p && p[1] == '>') { str = p + 2; while (*str == '>') { str++; } while (IS_WHITESPACE (*str)) { str++; } r_cons_flush (); pipefd = r_cons_pipe_open (str, 1, p[2] == '>'); } } line = strdup (cmd); line = r_str_replace (line, "\\\"", "\"", true); if (p && *p && p[1] == '|') { str = p + 2; while (IS_WHITESPACE (*str)) { str++; } r_core_cmd_pipe (core, cmd, str); } else { r_cmd_call (core->rcmd, line); } free (line); if (oseek != UT64_MAX) { r_core_seek (core, oseek, 1); oseek = UT64_MAX; } if (pipefd != -1) { r_cons_flush (); r_cons_pipe_close (pipefd); } if (!p) { break; } if (eos) { break; } if (haveQuote) { if (*p == ';') { cmd = p + 1; } else { if (*p == '"') { cmd = p + 1; } else { *p = '"'; cmd = p; } } } else { cmd = p + 1; } } return true; case '(': if (cmd[1] != '*') { return r_cmd_call (core->rcmd, cmd); } } // TODO must honor " and ` /* comments */ if (*cmd != '#') { ptr = (char *)r_str_lastbut (cmd, '#', quotestr); if (ptr && (ptr[1] == ' ' || ptr[1] == '\t')) { *ptr = '\0'; } } /* multiple commands */ // TODO: must honor " and ` boundaries //ptr = strrchr (cmd, ';'); if (*cmd != '#') { ptr = (char *)r_str_lastbut (cmd, ';', quotestr); if (colon && ptr) { int ret ; *ptr = '\0'; if (r_core_cmd_subst (core, cmd) == -1) { return -1; } cmd = ptr + 1; ret = r_core_cmd_subst (core, cmd); *ptr = ';'; return ret; //r_cons_flush (); } } // TODO must honor " and ` /* pipe console to shell process */ //ptr = strchr (cmd, '|'); ptr = (char *)r_str_lastbut (cmd, '|', quotestr); if (ptr) { char *ptr2 = strchr (cmd, '`'); if (!ptr2 || (ptr2 && ptr2 > ptr)) { if (!tick || (tick && tick > ptr)) { *ptr = '\0'; cmd = r_str_clean (cmd); if (!strcmp (ptr + 1, "?")) { // "|?" // TODO: should be disable scr.color in pd| ? eprintf ("Usage: <r2command> | <program|H|>\n"); eprintf (" pd|? - show this help\n"); eprintf (" pd| - disable scr.html and scr.color\n"); eprintf (" pd|H - enable scr.html, respect scr.color\n"); return ret; } else if (!strcmp (ptr + 1, "H")) { // "|H" scr_html = r_config_get_i (core->config, "scr.html"); r_config_set_i (core->config, "scr.html", true); } else if (ptr[1]) { // "| grep .." int value = core->num->value; if (*cmd) { r_core_cmd_pipe (core, cmd, ptr + 1); } else { r_io_system (core->io, ptr + 1); } core->num->value = value; return 0; } else { // "|" scr_html = r_config_get_i (core->config, "scr.html"); r_config_set_i (core->config, "scr.html", 0); scr_color = r_config_get_i (core->config, "scr.color"); r_config_set_i (core->config, "scr.color", false); } } } } // TODO must honor " and ` /* bool conditions */ ptr = (char *)r_str_lastbut (cmd, '&', quotestr); //ptr = strchr (cmd, '&'); while (ptr && ptr[1] == '&') { *ptr = '\0'; ret = r_cmd_call (core->rcmd, cmd); if (ret == -1) { eprintf ("command error(%s)\n", cmd); if (scr_html != -1) { r_config_set_i (core->config, "scr.html", scr_html); } if (scr_color != -1) { r_config_set_i (core->config, "scr.color", scr_color); } return ret; } for (cmd = ptr + 2; cmd && *cmd == ' '; cmd++); ptr = strchr (cmd, '&'); } /* Out Of Band Input */ free (core->oobi); core->oobi = NULL; ptr = strstr (cmd, "?*"); if (ptr) { char *prech = ptr - 1; if (*prech != '~') { ptr[1] = 0; if (*cmd != '#' && strlen (cmd) < 5) { r_cons_break_push (NULL, NULL); recursive_help (core, cmd); r_cons_break_pop (); r_cons_grep_parsecmd (ptr + 2, "`"); if (scr_html != -1) { r_config_set_i (core->config, "scr.html", scr_html); } if (scr_color != -1) { r_config_set_i (core->config, "scr.color", scr_color); } return 0; } } } #if 0 ptr = strchr (cmd, '<'); if (ptr) { ptr[0] = '\0'; if (r_cons_singleton()->is_interactive) { if (ptr[1] == '<') { /* this is a bit mess */ //const char *oprompt = strdup (r_line_singleton ()->prompt); //oprompt = ">"; for (str = ptr + 2; str[0] == ' '; str++) { //nothing to see here } eprintf ("==> Reading from stdin until '%s'\n", str); free (core->oobi); core->oobi = malloc (1); if (core->oobi) { core->oobi[0] = '\0'; } core->oobi_len = 0; for (;;) { char buf[1024]; int ret; write (1, "> ", 2); fgets (buf, sizeof (buf) - 1, stdin); // XXX use r_line ?? if (feof (stdin)) { break; } if (*buf) buf[strlen (buf) - 1]='\0'; ret = strlen (buf); core->oobi_len += ret; core->oobi = realloc (core->oobi, core->oobi_len + 1); if (core->oobi) { if (!strcmp (buf, str)) { break; } strcat ((char *)core->oobi, buf); } } //r_line_set_prompt (oprompt); } else { for (str = ptr + 1; *str == ' '; str++) { //nothing to see here } if (!*str) { goto next; } eprintf ("Slurping file '%s'\n", str); free (core->oobi); core->oobi = (ut8*)r_file_slurp (str, &core->oobi_len); if (!core->oobi) { eprintf ("cannot open file\n"); } else if (ptr == cmd) { return r_core_cmd_buffer (core, (const char *)core->oobi); } } } else { eprintf ("Cannot slurp with << in non-interactive mode\n"); return 0; } } next: #endif // TODO must honor " and ` /* pipe console to file */ ptr = strchr (cmd, '>'); if (ptr) { int fdn = 1; int pipecolor = r_config_get_i (core->config, "scr.pipecolor"); int use_editor = false; int ocolor = r_config_get_i (core->config, "scr.color"); *ptr = '\0'; str = r_str_trim_head_tail (ptr + 1 + (ptr[1] == '>')); if (!*str) { eprintf ("No output?\n"); goto next2; } /* r_cons_flush() handles interactive output (to the terminal) * differently (e.g. asking about too long output). This conflicts * with piping to a file. Disable it while piping. */ if (ptr > (cmd + 1) && ISWHITECHAR (ptr[-2])) { char *fdnum = ptr - 1; if (*fdnum == 'H') { // "H>" scr_html = r_config_get_i (core->config, "scr.html"); r_config_set_i (core->config, "scr.html", true); pipecolor = true; *fdnum = 0; } else { if (IS_DIGIT(*fdnum)) { fdn = *fdnum - '0'; } *fdnum = 0; } } r_cons_set_interactive (false); if (!strcmp (str, "-")) { use_editor = true; str = r_file_temp ("dumpedit"); r_config_set (core->config, "scr.color", "false"); } if (fdn > 0) { pipefd = r_cons_pipe_open (str, fdn, ptr[1] == '>'); if (pipefd != -1) { if (!pipecolor) { r_config_set_i (core->config, "scr.color", 0); } ret = r_core_cmd_subst (core, cmd); r_cons_flush (); r_cons_pipe_close (pipefd); } } r_cons_set_last_interactive (); if (!pipecolor) { r_config_set_i (core->config, "scr.color", ocolor); } if (use_editor) { const char *editor = r_config_get (core->config, "cfg.editor"); if (editor && *editor) { r_sys_cmdf ("%s '%s'", editor, str); r_file_rm (str); } else { eprintf ("No cfg.editor configured\n"); } r_config_set_i (core->config, "scr.color", ocolor); free (str); } if (scr_html != -1) { r_config_set_i (core->config, "scr.html", scr_html); } if (scr_color != -1) { r_config_set_i (core->config, "scr.color", scr_color); } return ret; } next2: /* sub commands */ ptr = strchr (cmd, '`'); if (ptr) { int empty = 0; int oneline = 1; if (ptr[1] == '`') { memmove (ptr, ptr + 1, strlen (ptr)); oneline = 0; empty = 1; } ptr2 = strchr (ptr + 1, '`'); if (empty) { /* do nothing */ } else if (!ptr2) { eprintf ("parse: Missing backtick in expression.\n"); goto fail; } else { int value = core->num->value; *ptr = '\0'; *ptr2 = '\0'; if (ptr[1] == '!') { str = r_core_cmd_str_pipe (core, ptr + 1); } else { str = r_core_cmd_str (core, ptr + 1); } if (!str) { goto fail; } // ignore contents if first char is pipe or comment if (*str == '|' || *str == '*') { eprintf ("r_core_cmd_subst_i: invalid backticked command\n"); free (str); goto fail; } if (oneline && str) { for (i = 0; str[i]; i++) { if (str[i] == '\n') { str[i] = ' '; } } } str = r_str_append (str, ptr2 + 1); cmd = r_str_append (strdup (cmd), str); core->num->value = value; ret = r_core_cmd_subst (core, cmd); free (cmd); if (scr_html != -1) { r_config_set_i (core->config, "scr.html", scr_html); } free (str); return ret; } } // TODO must honor " and ` core->fixedblock = false; if (r_str_endswith (cmd, "~?") && cmd[2] == '\0') { r_cons_grep_help (); return true; } if (*cmd != '.') { r_cons_grep_parsecmd (cmd, quotestr); } /* temporary seek commands */ if (*cmd!= '(' && *cmd != '"') { ptr = strchr (cmd, '@'); if (ptr == cmd + 1 && *cmd == '?') { ptr = NULL; } } else { ptr = NULL; } core->tmpseek = ptr? true: false; int rc = 0; if (ptr) { char *f, *ptr2 = strchr (ptr + 1, '!'); ut64 addr = UT64_MAX; const char *tmpbits = NULL; const char *offstr = NULL; ut64 tmpbsz = core->blocksize; char *tmpeval = NULL; ut64 tmpoff = core->offset; char *tmpasm = NULL; int tmpfd = -1; int sz, len; ut8 *buf; *ptr = '\0'; for (ptr++; *ptr == ' '; ptr++) { //nothing to see here } if (*ptr && ptr[1] == ':') { /* do nothing here */ } else { ptr--; } arroba = (ptr[0] && ptr[1] && ptr[2])? strchr (ptr + 2, '@'): NULL; repeat_arroba: if (arroba) { *arroba = 0; } if (ptr[1] == '?') { helpCmdAt (core); } else if (ptr[0] && ptr[1] == ':' && ptr[2]) { usemyblock = true; switch (ptr[0]) { case 'f': // "@f:" // slurp file in block f = r_file_slurp (ptr + 2, &sz); if (f) { buf = malloc (sz); if (buf) { free (core->block); core->block = buf; core->blocksize = sz; memcpy (core->block, f, sz); } else { eprintf ("cannot alloc %d", sz); } free (f); } else { eprintf ("cannot open '%s'\n", ptr + 3); } break; case 'r': // "@r:" // regname if (ptr[1] == ':') { ut64 regval; char *mander = strdup (ptr + 2); char *sep = findSeparator (mander); if (sep) { char ch = *sep; *sep = 0; regval = r_debug_reg_get (core->dbg, mander); *sep = ch; char *numexpr = r_str_newf ("0x%"PFMT64x"%s", regval, sep); regval = r_num_math (core->num, numexpr); free (numexpr); } else { regval = r_debug_reg_get (core->dbg, ptr + 2); } r_core_seek (core, regval, 1); free (mander); } break; case 'b': // "@b:" // bits tmpbits = strdup (r_config_get (core->config, "asm.bits")); r_config_set_i (core->config, "asm.bits", r_num_math (core->num, ptr + 2)); break; case 'i': // "@i:" { ut64 addr = r_num_math (core->num, ptr + 2); if (addr) { r_core_cmdf (core, "so %s", ptr + 2); } } break; case 'e': // "@e:" tmpeval = parse_tmp_evals (core, ptr + 2); break; case 'x': // "@x:" // hexpairs if (ptr[1] == ':') { buf = malloc (strlen (ptr + 2) + 1); if (buf) { len = r_hex_str2bin (ptr + 2, buf); r_core_block_size (core, R_ABS(len)); memcpy (core->block, buf, core->blocksize); core->fixedblock = true; free (buf); } else { eprintf ("cannot allocate\n"); } } else { eprintf ("Invalid @x: syntax\n"); } break; case 'k': // "@k" { char *out = sdb_querys (core->sdb, NULL, 0, ptr + ((ptr[1])? 2: 1)); if (out) { r_core_seek (core, r_num_math (core->num, out), 1); free (out); } } break; case 'o': // "@o:3" if (ptr[1] == ':') { tmpfd = core->io->raised; r_io_raise (core->io, atoi (ptr + 2)); } break; case 'a': // "@a:" if (ptr[1] == ':') { char *q = strchr (ptr + 2, ':'); tmpasm = strdup (r_config_get (core->config, "asm.arch")); if (q) { *q++ = 0; tmpbits = r_config_get (core->config, "asm.bits"); r_config_set (core->config, "asm.bits", q); } r_config_set (core->config, "asm.arch", ptr + 2); // TODO: handle asm.bits } else { eprintf ("Usage: pd 10 @a:arm:32\n"); } break; case 's': // "@s:" len = strlen (ptr + 2); r_core_block_size (core, len); memcpy (core->block, ptr + 2, len); break; default: goto ignore; } *ptr = '@'; goto next_arroba; //ignore; //return ret; } ignore: ptr = r_str_trim_head (ptr + 1); ptr--; cmd = r_str_clean (cmd); if (ptr2) { if (strlen (ptr + 1) == 13 && strlen (ptr2 + 1) == 6 && !memcmp (ptr + 1, "0x", 2) && !memcmp (ptr2 + 1, "0x", 2)) { /* 0xXXXX:0xYYYY */ } else if (strlen (ptr + 1) == 9 && strlen (ptr2 + 1) == 4) { /* XXXX:YYYY */ } else { *ptr2 = '\0'; if (!ptr2[1]) { goto fail; } r_core_block_size ( core, r_num_math (core->num, ptr2 + 1)); } } offstr = r_str_trim_head (ptr + 1); addr = r_num_math (core->num, offstr); if (isalpha ((unsigned char)ptr[1]) && !addr) { if (!r_flag_get (core->flags, ptr + 1)) { eprintf ("Invalid address (%s)\n", ptr + 1); goto fail; } } else { char ch = *offstr; if (ch == '-' || ch == '+') { addr = core->offset + addr; } } next_arroba: if (arroba) { ptr = arroba; arroba = NULL; goto repeat_arroba; } if (ptr[1] == '@') { // TODO: remove temporally seek (should be done by cmd_foreach) if (ptr[2] == '@') { char *rule = ptr + 3; while (*rule && *rule == ' ') rule++; ret = r_core_cmd_foreach3 (core, cmd, rule); } else { ret = r_core_cmd_foreach (core, cmd, ptr + 2); } //ret = -1; /* do not run out-of-foreach cmd */ } else { bool tmpseek = false; const char *fromvars[] = { "anal.from", "diff.from", "graph.from", "io.buffer.from", "lines.from", "search.from", "zoom.from", NULL }; const char *tovars[] = { "anal.to", "diff.to", "graph.to", "io.buffer.to", "lines.to", "search.to", "zoom.to", NULL }; ut64 curfrom[R_ARRAY_SIZE (fromvars) - 1], curto[R_ARRAY_SIZE (tovars) - 1]; // @.. if (ptr[1] == '.' && ptr[2] == '.') { char *range = ptr + 3; char *p = strchr (range, ' '); if (!p) { eprintf ("Usage: / ABCD @..0x1000 0x3000\n"); free (tmpeval); free (tmpasm); goto fail; } *p = '\x00'; ut64 from = r_num_math (core->num, range); ut64 to = r_num_math (core->num, p + 1); // save current ranges for (i = 0; fromvars[i]; i++) { curfrom[i] = r_config_get_i (core->config, fromvars[i]); } for (i = 0; tovars[i]; i++) { curto[i] = r_config_get_i (core->config, tovars[i]); } // set new ranges for (i = 0; fromvars[i]; i++) { r_config_set_i (core->config, fromvars[i], from); } for (i = 0; tovars[i]; i++) { r_config_set_i (core->config, tovars[i], to); } tmpseek = true; } if (usemyblock) { if (addr != UT64_MAX) { core->offset = addr; } ret = r_cmd_call (core->rcmd, r_str_trim_head (cmd)); } else { if (addr != UT64_MAX) { if (!ptr[1] || r_core_seek (core, addr, 1)) { r_core_block_read (core); ret = r_cmd_call (core->rcmd, r_str_trim_head (cmd)); } else { ret = 0; } } } if (tmpseek) { // restore ranges for (i = 0; fromvars[i]; i++) { r_config_set_i (core->config, fromvars[i], curfrom[i]); } for (i = 0; tovars[i]; i++) { r_config_set_i (core->config, tovars[i], curto[i]); } } } if (ptr2) { *ptr2 = '!'; r_core_block_size (core, tmpbsz); } if (tmpasm) { r_config_set (core->config, "asm.arch", tmpasm); tmpasm = NULL; } if (tmpfd != -1) { r_io_raise (core->io, tmpfd); } if (tmpbits) { r_config_set (core->config, "asm.bits", tmpbits); tmpbits = NULL; } if (tmpeval) { r_core_cmd0 (core, tmpeval); R_FREE (tmpeval); } r_core_seek (core, tmpoff, 1); *ptr = '@'; rc = ret; goto beach; } rc = cmd? r_cmd_call (core->rcmd, r_str_trim_head (cmd)): false; beach: if (scr_html != -1) { r_cons_flush (); r_config_set_i (core->config, "scr.html", scr_html); } if (scr_color != -1) { r_config_set_i (core->config, "scr.color", scr_color); } core->fixedblock = false; return rc; fail: rc = -1; goto beach; } static int foreach_comment(void *user, const char *k, const char *v) { RAnalMetaUserItem *ui = user; RCore *core = ui->anal->user; const char *cmd = ui->user; if (!strncmp (k, "meta.C.", 7)) { char *cmt = (char *)sdb_decode (v, 0); if (!cmt) cmt = strdup (""); //eprintf ("--> %s = %s\n", k + 7, cmt); r_core_cmdf (core, "s %s", k + 7); r_core_cmd0 (core, cmd); free (cmt); } return 1; } R_API int r_core_cmd_foreach3(RCore *core, const char *cmd, char *each) { RDebug *dbg = core->dbg; RList *list, *head; RListIter *iter; RFlagItem *flg; int i; switch (each[0]) { case '=': { char *arg; for (arg = each + 1; ; ) { char *next = strchr (arg, ' '); if (next) { *next = 0; } if (arg && *arg) { r_core_cmdf (core, "%s %s", cmd, arg); } if (!next) { break; } arg = next + 1; } } break; case '?': r_cons_printf ("Usage: @@@ [type] # types:\n" " symbols\n" " imports\n" " regs\n" " threads\n" " comments\n" " functions\n" " flags\n"); break; case 'c': switch (each[1]) { case 'a': // call break; default: r_meta_list_cb (core->anal, R_META_TYPE_COMMENT, 0, foreach_comment, (void*)cmd, UT64_MAX); break; } break; case 't': // iterate over all threads if (dbg && dbg->h && dbg->h->threads) { int origpid = dbg->pid; RDebugPid *p; list = dbg->h->threads (dbg, dbg->pid); if (!list) return false; r_list_foreach (list, iter, p) { r_core_cmdf (core, "dp %d", p->pid); r_cons_printf ("PID %d\n", p->pid); r_core_cmd0 (core, cmd); } r_core_cmdf (core, "dp %d", origpid); r_list_free (list); } break; case 'r': // registers { ut64 offorig = core->offset; for (i = 0; i < 128; i++) { RRegItem *item; ut64 value; head = r_reg_get_list (dbg->reg, i); if (!head) { continue; } r_list_foreach (head, iter, item) { if (item->size != core->anal->bits) { continue; } value = r_reg_get_value (dbg->reg, item); r_core_seek (core, value, 1); r_cons_printf ("%s: ", item->name); r_core_cmd0 (core, cmd); } } r_core_seek (core, offorig, 1); } break; case 'i': // imports { RBinImport *imp; ut64 offorig = core->offset; list = r_bin_get_imports (core->bin); r_list_foreach (list, iter, imp) { char *impflag = r_str_newf ("sym.imp.%s", imp->name); ut64 addr = r_num_math (core->num, impflag); if (addr && addr != UT64_MAX) { r_core_seek (core, addr, 1); r_core_cmd0 (core, cmd); } } r_core_seek (core, offorig, 1); } break; case 's': // symbols { RBinSymbol *sym; ut64 offorig = core->offset; list = r_bin_get_symbols (core->bin); r_list_foreach (list, iter, sym) { r_core_seek (core, sym->vaddr, 1); r_core_cmd0 (core, cmd); } r_core_seek (core, offorig, 1); } break; case 'f': switch (each[1]) { case 'l': // flags r_list_foreach (core->flags->flags, iter, flg) { r_core_seek (core, flg->offset, 1); r_core_cmd0 (core, cmd); } break; case 'u': // functions { ut64 offorig = core->offset; RAnalFunction *fcn; list = core->anal->fcns; r_list_foreach (list, iter, fcn) { r_cons_printf ("[0x%08"PFMT64x" %s\n", fcn->addr, fcn->name); r_core_seek (core, fcn->addr, 1); r_core_cmd0 (core, cmd); } r_core_seek (core, offorig, 1); } break; } break; } return 0; } static void foreachOffset (RCore *core, const char *_cmd, const char *each) { char *cmd = strdup (_cmd); char *str = cmd; char *nextLine = NULL; ut64 addr; /* foreach list of items */ while (each) { // skip spaces while (*each == ' ') { each++; } // stahp if empty string if (!*each) { break; } // find newline char *nl = strchr (each, '\n'); if (nl) { *nl = 0; nextLine = nl + 1; } else { nextLine = NULL; } // chop comment in line nl = strchr (each, '#'); if (nl) { *nl = 0; } // space separated numbers while (each && *each) { // find spaces while (*each== ' ') each++; str = strchr (each, ' '); if (str) { *str = '\0'; addr = r_num_math (core->num, each); *str = ' '; each = str + 1; } else { if (!*each) { break; } addr = r_num_math (core->num, each); each = NULL; } r_core_seek (core, addr, 1); r_core_cmd (core, cmd, 0); r_cons_flush (); } each = nextLine; } free (cmd); } R_API int r_core_cmd_foreach(RCore *core, const char *cmd, char *each) { int i, j; char ch; char *word = NULL; char *str, *ostr; RListIter *iter; RFlagItem *flag; ut64 oseek, addr; // for (; *each == ' '; each++); for (; *cmd == ' '; cmd++); oseek = core->offset; ostr = str = strdup (each); r_cons_break_push (NULL, NULL); //pop on return switch (each[0]) { case '/': // "@@/" { char *cmdhit = strdup (r_config_get (core->config, "cmd.hit")); r_config_set (core->config, "cmd.hit", cmd); r_core_cmd0 (core, each); r_config_set (core->config, "cmd.hit", cmdhit); free (cmdhit); } return 0; case '?': helpCmdForeach (core); break; case 'b': // "@@b" - function basic blocks { RListIter *iter; RAnalBlock *bb; RAnalFunction *fcn = r_anal_get_fcn_at (core->anal, core->offset, 0); int bs = core->blocksize; if (fcn) { r_list_sort (fcn->bbs, bb_cmp); r_list_foreach (fcn->bbs, iter, bb) { r_core_block_size (core, bb->size); r_core_seek (core, bb->addr, 1); r_core_cmd (core, cmd, 0); if (r_cons_is_breaked ()) { break; } } } free (ostr); r_core_block_size (core, bs); goto out_finish; } break; case 'i': // "@@i" - function instructions { RListIter *iter; RAnalBlock *bb; int i; RAnalFunction *fcn = r_anal_get_fcn_at (core->anal, core->offset, 0); if (fcn) { r_list_sort (fcn->bbs, bb_cmp); r_list_foreach (fcn->bbs, iter, bb) { for (i = 0; i < bb->op_pos_size; i++) { ut64 addr = bb->addr + bb->op_pos[i]; r_core_seek (core, addr, 1); r_core_cmd (core, cmd, 0); if (r_cons_is_breaked ()) { break; } } } } free (ostr); goto out_finish; } break; case 'f': // "@@f" if (each[1] == ':') { RAnalFunction *fcn; RListIter *iter; if (core->anal) { r_list_foreach (core->anal->fcns, iter, fcn) { if (each[2] && strstr (fcn->name, each + 2)) { r_core_seek (core, fcn->addr, 1); r_core_cmd (core, cmd, 0); if (r_cons_is_breaked ()) { break; } } } } free (ostr); goto out_finish; } else { RAnalFunction *fcn; RListIter *iter; if (core->anal) { RConsGrep grep = core->cons->grep; r_list_foreach (core->anal->fcns, iter, fcn) { char *buf; r_core_seek (core, fcn->addr, 1); r_cons_push (); r_core_cmd (core, cmd, 0); buf = (char *)r_cons_get_buffer (); if (buf) { buf = strdup (buf); } r_cons_pop (); r_cons_strcat (buf); free (buf); if (r_cons_is_breaked ()) { break; } } core->cons->grep = grep; } free (ostr); goto out_finish; } break; case 't': { RDebugPid *p; int pid = core->dbg->pid; if (core->dbg->h && core->dbg->h->pids) { RList *list = core->dbg->h->pids (core->dbg, R_MAX (0, pid)); r_list_foreach (list, iter, p) { r_cons_printf ("# PID %d\n", p->pid); r_debug_select (core->dbg, p->pid, p->pid); r_core_cmd (core, cmd, 0); r_cons_newline (); } r_list_free (list); } r_debug_select (core->dbg, pid, pid); free (ostr); goto out_finish; } break; case 'c': // "@@c:" if (each[1] == ':') { char *arg = r_core_cmd_str (core, each + 2); if (arg) { foreachOffset (core, cmd, arg); } } break; case '=': foreachOffset (core, cmd, str + 1); break; case 'd': if (each[1] == 'b' && each[2] == 't') { ut64 oseek = core->offset; RDebugFrame *frame; RListIter *iter; RList *list; list = r_debug_frames (core->dbg, UT64_MAX); i = 0; r_list_foreach (list, iter, frame) { switch (each[3]) { case 'b': r_core_seek (core, frame->bp, 1); break; case 's': r_core_seek (core, frame->sp, 1); break; default: case 'a': r_core_seek (core, frame->addr, 1); break; } r_core_cmd (core, cmd, 0); r_cons_newline (); i++; } r_core_seek (core, oseek, 0); r_list_free (list); } else { eprintf("Invalid for-each statement. Use @@=dbt[abs]\n"); } break; case 'k': /* foreach list of items */ { char *out = sdb_querys (core->sdb, NULL, 0, str + ((str[1])? 2: 1)); if (out) { each = out; do { while (*each == ' ') each++; if (!*each) { break; } str = strchr (each, ' '); if (str) { *str = '\0'; addr = r_num_math (core->num, each); *str = ' '; } else { addr = r_num_math (core->num, each); } //eprintf ("; 0x%08"PFMT64x":\n", addr); each = str + 1; r_core_seek (core, addr, 1); r_core_cmd (core, cmd, 0); r_cons_flush (); } while (str != NULL); free (out); } } break; case '.': if (each[1] == '(') { char cmd2[1024]; // XXX whats this 999 ? i = 0; for (core->rcmd->macro.counter = 0; i < 999; core->rcmd->macro.counter++) { if (r_cons_is_breaked ()) { break; } r_cmd_macro_call (&core->rcmd->macro, each + 2); if (!core->rcmd->macro.brk_value) { break; } addr = core->rcmd->macro._brk_value; sprintf (cmd2, "%s @ 0x%08"PFMT64x"", cmd, addr); eprintf ("0x%08"PFMT64x" (%s)\n", addr, cmd2); r_core_seek (core, addr, 1); r_core_cmd (core, cmd2, 0); i++; } } else { char buf[1024]; char cmd2[1024]; FILE *fd = r_sandbox_fopen (each + 1, "r"); if (fd) { core->rcmd->macro.counter=0; while (!feof (fd)) { buf[0] = '\0'; if (!fgets (buf, sizeof (buf), fd)) { break; } addr = r_num_math (core->num, buf); eprintf ("0x%08"PFMT64x": %s\n", addr, cmd); sprintf (cmd2, "%s @ 0x%08"PFMT64x"", cmd, addr); r_core_seek (core, addr, 1); // XXX r_core_cmd (core, cmd2, 0); core->rcmd->macro.counter++; } fclose (fd); } else { eprintf ("cannot open file '%s' to read offsets\n", each + 1); } } break; default: core->rcmd->macro.counter = 0; for (; *each == ' '; each++); i = 0; while (str[i]) { j = i; for (; str[j] && str[j] == ' '; j++); // skip spaces for (i = j; str[i] && str[i] != ' '; i++); // find EOS ch = str[i]; str[i] = '\0'; word = strdup (str + j); if (!word) { break; } str[i] = ch; { int flagspace = core->flags->space_idx; /* for all flags in current flagspace */ // XXX: dont ask why, but this only works with _prev.. r_list_foreach (core->flags->flags, iter, flag) { if (r_cons_is_breaked ()) { break; } /* filter per flag spaces */ if ((flagspace != -1) && (flag->space != flagspace)) { continue; } if (r_str_glob (flag->name, word)) { char *buf = NULL; const char *tmp = NULL; r_core_seek (core, flag->offset, 1); r_cons_push (); r_core_cmd (core, cmd, 0); tmp = r_cons_get_buffer (); buf = tmp? strdup (tmp): NULL; r_cons_pop (); r_cons_strcat (buf); free (buf); } } core->flags->space_idx = flagspace; core->rcmd->macro.counter++ ; free (word); word = NULL; } } } r_cons_break_pop (); // XXX: use r_core_seek here core->offset = oseek; free (word); free (ostr); return true; out_finish: r_cons_break_pop (); return false; } R_API int r_core_cmd(RCore *core, const char *cstr, int log) { char *cmd, *ocmd, *ptr, *rcmd; int ret = false, i; r_th_lock_enter (core->lock); if (core->cmdfilter) { const char *invalid_chars = ";|>`@"; for (i = 0; invalid_chars[i]; i++) { if (strchr (cstr, invalid_chars[i])) { ret = true; goto beach; } } if (strncmp (cstr, core->cmdfilter, strlen (core->cmdfilter))) { ret = true; goto beach; } } if (core->cmdremote) { if (*cstr != '=' && *cstr != 'q' && strncmp (cstr, "!=", 2)) { r_io_system (core->io, cstr); goto beach; // false } } if (!cstr || *cstr == '|') { // raw comment syntax goto beach; // false; } if (!strncmp (cstr, "/*", 2)) { if (r_sandbox_enable (0)) { eprintf ("This command is disabled in sandbox mode\n"); goto beach; // false } core->incomment = true; } else if (!strncmp (cstr, "*/", 2)) { core->incomment = false; goto beach; // false } if (core->incomment) { goto beach; // false } if (log && (*cstr && (*cstr != '.' || !strncmp (cstr, ".(", 2)))) { free (core->lastcmd); core->lastcmd = strdup (cstr); } ocmd = cmd = malloc (strlen (cstr) + 4096); if (!ocmd) { goto beach; } r_str_cpy (cmd, cstr); if (log) { r_line_hist_add (cstr); } if (core->cmd_depth < 1) { eprintf ("r_core_cmd: That was too deep (%s)...\n", cmd); free (ocmd); free (core->oobi); core->oobi = NULL; core->oobi_len = 0; goto beach; } core->cmd_depth--; for (rcmd = cmd;;) { ptr = strchr (rcmd, '\n'); if (ptr) { *ptr = '\0'; } ret = r_core_cmd_subst (core, rcmd); if (ret == -1) { eprintf ("|ERROR| Invalid command '%s' (0x%02x)\n", rcmd, *rcmd); break; } if (!ptr) { break; } rcmd = ptr + 1; } r_th_lock_leave (core->lock); /* run pending analysis commands */ if (core->anal->cmdtail) { char *res = core->anal->cmdtail; core->anal->cmdtail = NULL; r_core_cmd_lines (core, res); free (res); } core->cmd_depth++; free (ocmd); free (core->oobi); core->oobi = NULL; core->oobi_len = 0; return ret; beach: r_th_lock_leave (core->lock); /* run pending analysis commands */ if (core->anal->cmdtail) { char *res = core->anal->cmdtail; core->anal->cmdtail = NULL; r_core_cmd0 (core, res); free (res); } return ret; } R_API int r_core_cmd_lines(RCore *core, const char *lines) { int r, ret = true; char *nl, *data, *odata; if (!lines || !*lines) { return true; } data = odata = strdup (lines); if (!odata) { return false; } nl = strchr (odata, '\n'); if (nl) { r_cons_break_push (NULL, NULL); do { if (r_cons_is_breaked ()) { free (odata); r_cons_break_pop (); return ret; } *nl = '\0'; r = r_core_cmd (core, data, 0); if (r < 0) { //== -1) { data = nl + 1; ret = -1; //r; //false; break; } r_cons_flush (); if (data[0] == 'q') { if (data[1] == '!') { ret = -1; } else { eprintf ("'q': quit ignored. Use 'q!'\n"); } data = nl + 1; break; } data = nl + 1; } while ((nl = strchr (data, '\n'))); r_cons_break_pop (); } if (ret >= 0 && data && *data) { r_core_cmd (core, data, 0); } free (odata); return ret; } R_API int r_core_cmd_file(RCore *core, const char *file) { char *data, *odata; data = r_file_abspath (file); if (!data) return false; odata = r_file_slurp (data, NULL); free (data); if (!odata) return false; if (!r_core_cmd_lines (core, odata)) { eprintf ("Failed to run script '%s'\n", file); free (odata); return false; } free (odata); return true; } R_API int r_core_cmd_command(RCore *core, const char *command) { int ret, len; char *buf, *rcmd, *ptr; char *cmd = r_core_sysenv_begin (core, command); rcmd = ptr = buf = r_sys_cmd_str (cmd, 0, &len); if (!buf) { free (cmd); return -1; } ret = r_core_cmd (core, rcmd, 0); r_core_sysenv_end (core, command); free (buf); return ret; } //TODO: Fix disasm loop is mandatory R_API char *r_core_disassemble_instr(RCore *core, ut64 addr, int l) { char *cmd, *ret = NULL; cmd = r_str_newf ("pd %i @ 0x%08"PFMT64x, l, addr); if (cmd) { ret = r_core_cmd_str (core, cmd); free (cmd); } return ret; } R_API char *r_core_disassemble_bytes(RCore *core, ut64 addr, int b) { char *cmd, *ret = NULL; cmd = r_str_newf ("pD %i @ 0x%08"PFMT64x, b, addr); if (cmd) { ret = r_core_cmd_str (core, cmd); free (cmd); } return ret; } R_API int r_core_cmd_buffer(void *user, const char *buf) { char *ptr, *optr, *str = strdup (buf); if (!str) return false; optr = str; ptr = strchr (str, '\n'); while (ptr) { *ptr = '\0'; r_core_cmd (user, optr, 0); optr = ptr + 1; ptr = strchr (str, '\n'); } r_core_cmd (user, optr, 0); free (str); return true; } R_API int r_core_cmdf(void *user, const char *fmt, ...) { char string[4096]; int ret; va_list ap; va_start (ap, fmt); vsnprintf (string, sizeof (string), fmt, ap); ret = r_core_cmd ((RCore *)user, string, 0); va_end (ap); return ret; } R_API int r_core_cmd0(void *user, const char *cmd) { return r_core_cmd ((RCore *)user, cmd, 0); } R_API int r_core_flush(void *user, const char *cmd) { int ret = r_core_cmd ((RCore *)user, cmd, 0); r_cons_flush (); return ret; } R_API char *r_core_cmd_str_pipe(RCore *core, const char *cmd) { char *s, *tmp = NULL; if (r_sandbox_enable (0)) { return r_core_cmd_str (core, cmd); } r_cons_reset (); r_sandbox_disable (1); if (r_file_mkstemp ("cmd", &tmp) != -1) { int pipefd = r_cons_pipe_open (tmp, 1, 0); if (pipefd == -1) { r_sandbox_disable (0); return r_core_cmd_str (core, cmd); } char *_cmd = strdup (cmd); r_core_cmd_subst (core, _cmd); r_cons_flush (); r_cons_pipe_close (pipefd); s = r_file_slurp (tmp, NULL); if (s) { r_file_rm (tmp); r_sandbox_disable (0); free (tmp); free (_cmd); return s; } eprintf ("slurp %s fails\n", tmp); r_file_rm (tmp); free (tmp); free (_cmd); r_sandbox_disable (0); return r_core_cmd_str (core, cmd); } r_sandbox_disable (0); return NULL; } R_API char *r_core_cmd_strf(RCore *core, const char *fmt, ...) { char string[4096]; char *ret; va_list ap; va_start (ap, fmt); vsnprintf (string, sizeof (string), fmt, ap); ret = r_core_cmd_str (core, string); va_end (ap); return ret; } /* return: pointer to a buffer with the output of the command */ R_API char *r_core_cmd_str(RCore *core, const char *cmd) { const char *static_str; char *retstr = NULL; r_cons_push (); if (r_core_cmd (core, cmd, 0) == -1) { //eprintf ("Invalid command: %s\n", cmd); return NULL; } r_cons_filter (); static_str = r_cons_get_buffer (); retstr = strdup (static_str? static_str: ""); r_cons_pop (); return retstr; } R_API void r_core_cmd_repeat(RCore *core, int next) { // Fix for backtickbug px`~` if (core->cmd_depth + 1 < R_CORE_CMD_DEPTH) return; if (core->lastcmd) switch (*core->lastcmd) { case '.': if (core->lastcmd[1] == '(') // macro call r_core_cmd0 (core, core->lastcmd); break; case 'd': // debug r_core_cmd0 (core, core->lastcmd); switch (core->lastcmd[1]) { case 's': case 'c': r_core_cmd0 (core, "sr PC;pd 1"); } break; case 'p': // print case 'x': case '$': if (next) { r_core_seek (core, core->offset + core->blocksize, 1); } else { if (core->blocksize > core->offset) { r_core_seek (core, 0, 1); } else { r_core_seek (core, core->offset - core->blocksize, 1); } } r_core_cmd0 (core, core->lastcmd); break; } } static int cmd_ox(void *data, const char *input) { return r_core_cmdf ((RCore*)data, "s 0%s", input); } R_API void r_core_cmd_init(RCore *core) { core->rcmd = r_cmd_new (); core->rcmd->macro.user = core; core->rcmd->macro.num = core->num; core->rcmd->macro.cmd = r_core_cmd0; core->rcmd->nullcallback = r_core_cmd_nullcallback; core->rcmd->macro.cb_printf = (PrintfCallback)r_cons_printf; r_cmd_set_data (core->rcmd, core); r_cmd_add (core->rcmd, "0x", "alias for px", &cmd_ox); r_cmd_add (core->rcmd, "x", "alias for px", &cmd_hexdump); r_cmd_add (core->rcmd, "mount", "mount filesystem", &cmd_mount); r_cmd_add (core->rcmd, "analysis", "analysis", &cmd_anal); r_cmd_add (core->rcmd, "flag", "get/set flags", &cmd_flag); r_cmd_add (core->rcmd, "g", "egg manipulation", &cmd_egg); r_cmd_add (core->rcmd, "debug", "debugger operations", &cmd_debug); r_cmd_add (core->rcmd, "ls", "list files and directories", &cmd_ls); r_cmd_add (core->rcmd, "info", "get file info", &cmd_info); r_cmd_add (core->rcmd, "cmp", "compare memory", &cmd_cmp); r_cmd_add (core->rcmd, "seek", "seek to an offset", &cmd_seek); r_cmd_add (core->rcmd, "Text", "Text log utility", &cmd_log); r_cmd_add (core->rcmd, "t", "type information (cparse)", &cmd_type); r_cmd_add (core->rcmd, "zign", "zignatures", &cmd_zign); r_cmd_add (core->rcmd, "Section", "setup section io information", &cmd_section); r_cmd_add (core->rcmd, "bsize", "change block size", &cmd_bsize); r_cmd_add (core->rcmd, "kuery", "perform sdb query", &cmd_kuery); r_cmd_add (core->rcmd, "eval", "evaluate configuration variable", &cmd_eval); r_cmd_add (core->rcmd, "print", "print current block", &cmd_print); r_cmd_add (core->rcmd, "write", "write bytes", &cmd_write); r_cmd_add (core->rcmd, "Code", "code metadata", &cmd_meta); r_cmd_add (core->rcmd, "Project", "project", &cmd_project); r_cmd_add (core->rcmd, "open", "open or map file", &cmd_open); r_cmd_add (core->rcmd, "yank", "yank bytes", &cmd_yank); r_cmd_add (core->rcmd, "resize", "change file size", &cmd_resize); r_cmd_add (core->rcmd, "Visual", "enter visual mode", &cmd_visual); r_cmd_add (core->rcmd, "visual", "enter visual mode", &cmd_visual); r_cmd_add (core->rcmd, "*", "pointer read/write", &cmd_pointer); r_cmd_add (core->rcmd, "&", "threading capabilities", &cmd_thread); r_cmd_add (core->rcmd, "%", "short version of 'env' command", &cmd_env); r_cmd_add (core->rcmd, "!", "run system command", &cmd_system); r_cmd_add (core->rcmd, "=", "io pipe", &cmd_rap); r_cmd_add (core->rcmd, "\\", "alias for =!", &cmd_rap_run); r_cmd_add (core->rcmd, "#", "calculate hash", &cmd_hash); r_cmd_add (core->rcmd, "?", "help message", &cmd_help); r_cmd_add (core->rcmd, "$", "alias", &cmd_alias); r_cmd_add (core->rcmd, ".", "interpret", &cmd_interpret); r_cmd_add (core->rcmd, "/", "search kw, pattern aes", &cmd_search); r_cmd_add (core->rcmd, "-", "open cfg.editor and run script", &cmd_stdin); r_cmd_add (core->rcmd, "(", "macro", &cmd_macro); r_cmd_add (core->rcmd, "u", "uname/undo", &cmd_uname); r_cmd_add (core->rcmd, "quit", "exit program session", &cmd_quit); r_cmd_add (core->rcmd, "Q", "alias for q!", &cmd_Quit); r_cmd_add (core->rcmd, "L", "manage dynamically loaded plugins", &cmd_plugins); }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_3406_0
crossvul-cpp_data_bad_5280_2
/* Generated by re2c 0.13.7.5 */ #line 1 "ext/standard/var_unserializer.re" /* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2016 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Sascha Schumann <sascha@schumann.cx> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include "php.h" #include "ext/standard/php_var.h" #include "php_incomplete_class.h" /* {{{ reference-handling for unserializer: var_* */ #define VAR_ENTRIES_MAX 1024 #define VAR_ENTRIES_DBG 0 typedef struct { zval *data[VAR_ENTRIES_MAX]; long used_slots; void *next; } var_entries; static inline void var_push(php_unserialize_data_t *var_hashx, zval **rval) { var_entries *var_hash = (*var_hashx)->last; #if VAR_ENTRIES_DBG fprintf(stderr, "var_push(%ld): %d\n", var_hash?var_hash->used_slots:-1L, Z_TYPE_PP(rval)); #endif if (!var_hash || var_hash->used_slots == VAR_ENTRIES_MAX) { var_hash = emalloc(sizeof(var_entries)); var_hash->used_slots = 0; var_hash->next = 0; if (!(*var_hashx)->first) { (*var_hashx)->first = var_hash; } else { ((var_entries *) (*var_hashx)->last)->next = var_hash; } (*var_hashx)->last = var_hash; } var_hash->data[var_hash->used_slots++] = *rval; } PHPAPI void var_push_dtor(php_unserialize_data_t *var_hashx, zval **rval) { var_entries *var_hash; if (!var_hashx || !*var_hashx) { return; } var_hash = (*var_hashx)->last_dtor; #if VAR_ENTRIES_DBG fprintf(stderr, "var_push_dtor(%p, %ld): %d\n", *rval, var_hash?var_hash->used_slots:-1L, Z_TYPE_PP(rval)); #endif if (!var_hash || var_hash->used_slots == VAR_ENTRIES_MAX) { var_hash = emalloc(sizeof(var_entries)); var_hash->used_slots = 0; var_hash->next = 0; if (!(*var_hashx)->first_dtor) { (*var_hashx)->first_dtor = var_hash; } else { ((var_entries *) (*var_hashx)->last_dtor)->next = var_hash; } (*var_hashx)->last_dtor = var_hash; } Z_ADDREF_PP(rval); var_hash->data[var_hash->used_slots++] = *rval; } PHPAPI void var_push_dtor_no_addref(php_unserialize_data_t *var_hashx, zval **rval) { var_entries *var_hash; if (!var_hashx || !*var_hashx) { return; } var_hash = (*var_hashx)->last_dtor; #if VAR_ENTRIES_DBG fprintf(stderr, "var_push_dtor_no_addref(%p, %ld): %d (%d)\n", *rval, var_hash?var_hash->used_slots:-1L, Z_TYPE_PP(rval), Z_REFCOUNT_PP(rval)); #endif if (!var_hash || var_hash->used_slots == VAR_ENTRIES_MAX) { var_hash = emalloc(sizeof(var_entries)); var_hash->used_slots = 0; var_hash->next = 0; if (!(*var_hashx)->first_dtor) { (*var_hashx)->first_dtor = var_hash; } else { ((var_entries *) (*var_hashx)->last_dtor)->next = var_hash; } (*var_hashx)->last_dtor = var_hash; } var_hash->data[var_hash->used_slots++] = *rval; } PHPAPI void var_replace(php_unserialize_data_t *var_hashx, zval *ozval, zval **nzval) { long i; var_entries *var_hash = (*var_hashx)->first; #if VAR_ENTRIES_DBG fprintf(stderr, "var_replace(%ld): %d\n", var_hash?var_hash->used_slots:-1L, Z_TYPE_PP(nzval)); #endif while (var_hash) { for (i = 0; i < var_hash->used_slots; i++) { if (var_hash->data[i] == ozval) { var_hash->data[i] = *nzval; /* do not break here */ } } var_hash = var_hash->next; } } static int var_access(php_unserialize_data_t *var_hashx, long id, zval ***store) { var_entries *var_hash = (*var_hashx)->first; #if VAR_ENTRIES_DBG fprintf(stderr, "var_access(%ld): %ld\n", var_hash?var_hash->used_slots:-1L, id); #endif while (id >= VAR_ENTRIES_MAX && var_hash && var_hash->used_slots == VAR_ENTRIES_MAX) { var_hash = var_hash->next; id -= VAR_ENTRIES_MAX; } if (!var_hash) return !SUCCESS; if (id < 0 || id >= var_hash->used_slots) return !SUCCESS; *store = &var_hash->data[id]; return SUCCESS; } PHPAPI void var_destroy(php_unserialize_data_t *var_hashx) { void *next; long i; var_entries *var_hash = (*var_hashx)->first; #if VAR_ENTRIES_DBG fprintf(stderr, "var_destroy(%ld)\n", var_hash?var_hash->used_slots:-1L); #endif while (var_hash) { next = var_hash->next; efree(var_hash); var_hash = next; } var_hash = (*var_hashx)->first_dtor; while (var_hash) { for (i = 0; i < var_hash->used_slots; i++) { #if VAR_ENTRIES_DBG fprintf(stderr, "var_destroy dtor(%p, %ld)\n", var_hash->data[i], Z_REFCOUNT_P(var_hash->data[i])); #endif zval_ptr_dtor(&var_hash->data[i]); } next = var_hash->next; efree(var_hash); var_hash = next; } } /* }}} */ static char *unserialize_str(const unsigned char **p, size_t *len, size_t maxlen) { size_t i, j; char *str = safe_emalloc(*len, 1, 1); unsigned char *end = *(unsigned char **)p+maxlen; if (end < *p) { efree(str); return NULL; } for (i = 0; i < *len; i++) { if (*p >= end) { efree(str); return NULL; } if (**p != '\\') { str[i] = (char)**p; } else { unsigned char ch = 0; for (j = 0; j < 2; j++) { (*p)++; if (**p >= '0' && **p <= '9') { ch = (ch << 4) + (**p -'0'); } else if (**p >= 'a' && **p <= 'f') { ch = (ch << 4) + (**p -'a'+10); } else if (**p >= 'A' && **p <= 'F') { ch = (ch << 4) + (**p -'A'+10); } else { efree(str); return NULL; } } str[i] = (char)ch; } (*p)++; } str[i] = 0; *len = i; return str; } #define YYFILL(n) do { } while (0) #define YYCTYPE unsigned char #define YYCURSOR cursor #define YYLIMIT limit #define YYMARKER marker #line 249 "ext/standard/var_unserializer.re" static inline long parse_iv2(const unsigned char *p, const unsigned char **q) { char cursor; long result = 0; int neg = 0; switch (*p) { case '-': neg++; /* fall-through */ case '+': p++; } while (1) { cursor = (char)*p; if (cursor >= '0' && cursor <= '9') { result = result * 10 + (size_t)(cursor - (unsigned char)'0'); } else { break; } p++; } if (q) *q = p; if (neg) return -result; return result; } static inline long parse_iv(const unsigned char *p) { return parse_iv2(p, NULL); } /* no need to check for length - re2c already did */ static inline size_t parse_uiv(const unsigned char *p) { unsigned char cursor; size_t result = 0; if (*p == '+') { p++; } while (1) { cursor = *p; if (cursor >= '0' && cursor <= '9') { result = result * 10 + (size_t)(cursor - (unsigned char)'0'); } else { break; } p++; } return result; } #define UNSERIALIZE_PARAMETER zval **rval, const unsigned char **p, const unsigned char *max, php_unserialize_data_t *var_hash TSRMLS_DC #define UNSERIALIZE_PASSTHRU rval, p, max, var_hash TSRMLS_CC static inline int process_nested_data(UNSERIALIZE_PARAMETER, HashTable *ht, long elements, int objprops) { while (elements-- > 0) { zval *key, *data, **old_data; ALLOC_INIT_ZVAL(key); if (!php_var_unserialize(&key, p, max, NULL TSRMLS_CC)) { var_push_dtor_no_addref(var_hash, &key); return 0; } if (Z_TYPE_P(key) != IS_LONG && Z_TYPE_P(key) != IS_STRING) { var_push_dtor_no_addref(var_hash, &key); return 0; } ALLOC_INIT_ZVAL(data); if (!php_var_unserialize(&data, p, max, var_hash TSRMLS_CC)) { var_push_dtor_no_addref(var_hash, &key); var_push_dtor_no_addref(var_hash, &data); return 0; } if (!objprops) { switch (Z_TYPE_P(key)) { case IS_LONG: if (zend_hash_index_find(ht, Z_LVAL_P(key), (void **)&old_data)==SUCCESS) { var_push_dtor(var_hash, old_data); } zend_hash_index_update(ht, Z_LVAL_P(key), &data, sizeof(data), NULL); break; case IS_STRING: if (zend_symtable_find(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, (void **)&old_data)==SUCCESS) { var_push_dtor(var_hash, old_data); } zend_symtable_update(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, &data, sizeof(data), NULL); break; } } else { /* object properties should include no integers */ convert_to_string(key); if (zend_hash_find(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, (void **)&old_data)==SUCCESS) { var_push_dtor(var_hash, old_data); } zend_hash_update(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, &data, sizeof data, NULL); } var_push_dtor(var_hash, &data); var_push_dtor_no_addref(var_hash, &key); if (elements && *(*p-1) != ';' && *(*p-1) != '}') { (*p)--; return 0; } } return 1; } static inline int finish_nested_data(UNSERIALIZE_PARAMETER) { if (*((*p)++) == '}') return 1; #if SOMETHING_NEW_MIGHT_LEAD_TO_CRASH_ENABLE_IF_YOU_ARE_BRAVE zval_ptr_dtor(rval); #endif return 0; } static inline int object_custom(UNSERIALIZE_PARAMETER, zend_class_entry *ce) { long datalen; datalen = parse_iv2((*p) + 2, p); (*p) += 2; if (datalen < 0 || (max - (*p)) <= datalen) { zend_error(E_WARNING, "Insufficient data for unserializing - %ld required, %ld present", datalen, (long)(max - (*p))); return 0; } if (ce->unserialize == NULL) { zend_error(E_WARNING, "Class %s has no unserializer", ce->name); object_init_ex(*rval, ce); } else if (ce->unserialize(rval, ce, (const unsigned char*)*p, datalen, (zend_unserialize_data *)var_hash TSRMLS_CC) != SUCCESS) { return 0; } (*p) += datalen; return finish_nested_data(UNSERIALIZE_PASSTHRU); } static inline long object_common1(UNSERIALIZE_PARAMETER, zend_class_entry *ce) { long elements; elements = parse_iv2((*p) + 2, p); (*p) += 2; if (ce->serialize == NULL) { object_init_ex(*rval, ce); } else { /* If this class implements Serializable, it should not land here but in object_custom(). The passed string obviously doesn't descend from the regular serializer. */ zend_error(E_WARNING, "Erroneous data format for unserializing '%s'", ce->name); return 0; } return elements; } #ifdef PHP_WIN32 # pragma optimize("", off) #endif static inline int object_common2(UNSERIALIZE_PARAMETER, long elements) { zval *retval_ptr = NULL; zval fname; if (Z_TYPE_PP(rval) != IS_OBJECT) { return 0; } if (!process_nested_data(UNSERIALIZE_PASSTHRU, Z_OBJPROP_PP(rval), elements, 1)) { /* We've got partially constructed object on our hands here. Wipe it. */ if(Z_TYPE_PP(rval) == IS_OBJECT) { zend_hash_clean(Z_OBJPROP_PP(rval)); } ZVAL_NULL(*rval); return 0; } if (Z_TYPE_PP(rval) != IS_OBJECT) { return 0; } if (Z_OBJCE_PP(rval) != PHP_IC_ENTRY && zend_hash_exists(&Z_OBJCE_PP(rval)->function_table, "__wakeup", sizeof("__wakeup"))) { INIT_PZVAL(&fname); ZVAL_STRINGL(&fname, "__wakeup", sizeof("__wakeup") - 1, 0); BG(serialize_lock)++; call_user_function_ex(CG(function_table), rval, &fname, &retval_ptr, 0, 0, 1, NULL TSRMLS_CC); BG(serialize_lock)--; } if (retval_ptr) { zval_ptr_dtor(&retval_ptr); } if (EG(exception)) { return 0; } return finish_nested_data(UNSERIALIZE_PASSTHRU); } #ifdef PHP_WIN32 # pragma optimize("", on) #endif PHPAPI int php_var_unserialize(UNSERIALIZE_PARAMETER) { const unsigned char *cursor, *limit, *marker, *start; zval **rval_ref; limit = max; cursor = *p; if (YYCURSOR >= YYLIMIT) { return 0; } if (var_hash && cursor[0] != 'R') { var_push(var_hash, rval); } start = cursor; #line 495 "ext/standard/var_unserializer.c" { YYCTYPE yych; static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; if ((YYLIMIT - YYCURSOR) < 7) YYFILL(7); yych = *YYCURSOR; switch (yych) { case 'C': case 'O': goto yy13; case 'N': goto yy5; case 'R': goto yy2; case 'S': goto yy10; case 'a': goto yy11; case 'b': goto yy6; case 'd': goto yy8; case 'i': goto yy7; case 'o': goto yy12; case 'r': goto yy4; case 's': goto yy9; case '}': goto yy14; default: goto yy16; } yy2: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy95; yy3: #line 860 "ext/standard/var_unserializer.re" { return 0; } #line 557 "ext/standard/var_unserializer.c" yy4: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy89; goto yy3; yy5: yych = *++YYCURSOR; if (yych == ';') goto yy87; goto yy3; yy6: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy83; goto yy3; yy7: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy77; goto yy3; yy8: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy53; goto yy3; yy9: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy46; goto yy3; yy10: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy39; goto yy3; yy11: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy32; goto yy3; yy12: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy25; goto yy3; yy13: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy17; goto yy3; yy14: ++YYCURSOR; #line 854 "ext/standard/var_unserializer.re" { /* this is the case where we have less data than planned */ php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Unexpected end of serialized data"); return 0; /* not sure if it should be 0 or 1 here? */ } #line 606 "ext/standard/var_unserializer.c" yy16: yych = *++YYCURSOR; goto yy3; yy17: yych = *++YYCURSOR; if (yybm[0+yych] & 128) { goto yy20; } if (yych == '+') goto yy19; yy18: YYCURSOR = YYMARKER; goto yy3; yy19: yych = *++YYCURSOR; if (yybm[0+yych] & 128) { goto yy20; } goto yy18; yy20: ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2); yych = *YYCURSOR; if (yybm[0+yych] & 128) { goto yy20; } if (yych <= '/') goto yy18; if (yych >= ';') goto yy18; yych = *++YYCURSOR; if (yych != '"') goto yy18; ++YYCURSOR; #line 707 "ext/standard/var_unserializer.re" { size_t len, len2, len3, maxlen; long elements; char *class_name; zend_class_entry *ce; zend_class_entry **pce; int incomplete_class = 0; int custom_object = 0; zval *user_func; zval *retval_ptr; zval **args[1]; zval *arg_func_name; if (!var_hash) return 0; if (*start == 'C') { custom_object = 1; } INIT_PZVAL(*rval); len2 = len = parse_uiv(start + 2); maxlen = max - YYCURSOR; if (maxlen < len || len == 0) { *p = start + 2; return 0; } class_name = (char*)YYCURSOR; YYCURSOR += len; if (*(YYCURSOR) != '"') { *p = YYCURSOR; return 0; } if (*(YYCURSOR+1) != ':') { *p = YYCURSOR+1; return 0; } len3 = strspn(class_name, "0123456789_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362\363\364\365\366\367\370\371\372\373\374\375\376\377\\"); if (len3 != len) { *p = YYCURSOR + len3 - len; return 0; } class_name = estrndup(class_name, len); do { /* Try to find class directly */ BG(serialize_lock)++; if (zend_lookup_class(class_name, len2, &pce TSRMLS_CC) == SUCCESS) { BG(serialize_lock)--; if (EG(exception)) { efree(class_name); return 0; } ce = *pce; break; } BG(serialize_lock)--; if (EG(exception)) { efree(class_name); return 0; } /* Check for unserialize callback */ if ((PG(unserialize_callback_func) == NULL) || (PG(unserialize_callback_func)[0] == '\0')) { incomplete_class = 1; ce = PHP_IC_ENTRY; break; } /* Call unserialize callback */ MAKE_STD_ZVAL(user_func); ZVAL_STRING(user_func, PG(unserialize_callback_func), 1); args[0] = &arg_func_name; MAKE_STD_ZVAL(arg_func_name); ZVAL_STRING(arg_func_name, class_name, 1); BG(serialize_lock)++; if (call_user_function_ex(CG(function_table), NULL, user_func, &retval_ptr, 1, args, 0, NULL TSRMLS_CC) != SUCCESS) { BG(serialize_lock)--; if (EG(exception)) { efree(class_name); zval_ptr_dtor(&user_func); zval_ptr_dtor(&arg_func_name); return 0; } php_error_docref(NULL TSRMLS_CC, E_WARNING, "defined (%s) but not found", user_func->value.str.val); incomplete_class = 1; ce = PHP_IC_ENTRY; zval_ptr_dtor(&user_func); zval_ptr_dtor(&arg_func_name); break; } BG(serialize_lock)--; if (retval_ptr) { zval_ptr_dtor(&retval_ptr); } if (EG(exception)) { efree(class_name); zval_ptr_dtor(&user_func); zval_ptr_dtor(&arg_func_name); return 0; } /* The callback function may have defined the class */ if (zend_lookup_class(class_name, len2, &pce TSRMLS_CC) == SUCCESS) { ce = *pce; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Function %s() hasn't defined the class it was called for", user_func->value.str.val); incomplete_class = 1; ce = PHP_IC_ENTRY; } zval_ptr_dtor(&user_func); zval_ptr_dtor(&arg_func_name); break; } while (1); *p = YYCURSOR; if (custom_object) { int ret; ret = object_custom(UNSERIALIZE_PASSTHRU, ce); if (ret && incomplete_class) { php_store_class_name(*rval, class_name, len2); } efree(class_name); return ret; } elements = object_common1(UNSERIALIZE_PASSTHRU, ce); if (incomplete_class) { php_store_class_name(*rval, class_name, len2); } efree(class_name); return object_common2(UNSERIALIZE_PASSTHRU, elements); } #line 784 "ext/standard/var_unserializer.c" yy25: yych = *++YYCURSOR; if (yych <= ',') { if (yych != '+') goto yy18; } else { if (yych <= '-') goto yy26; if (yych <= '/') goto yy18; if (yych <= '9') goto yy27; goto yy18; } yy26: yych = *++YYCURSOR; if (yych <= '/') goto yy18; if (yych >= ':') goto yy18; yy27: ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2); yych = *YYCURSOR; if (yych <= '/') goto yy18; if (yych <= '9') goto yy27; if (yych >= ';') goto yy18; yych = *++YYCURSOR; if (yych != '"') goto yy18; ++YYCURSOR; #line 698 "ext/standard/var_unserializer.re" { if (!var_hash) return 0; INIT_PZVAL(*rval); return object_common2(UNSERIALIZE_PASSTHRU, object_common1(UNSERIALIZE_PASSTHRU, ZEND_STANDARD_CLASS_DEF_PTR)); } #line 818 "ext/standard/var_unserializer.c" yy32: yych = *++YYCURSOR; if (yych == '+') goto yy33; if (yych <= '/') goto yy18; if (yych <= '9') goto yy34; goto yy18; yy33: yych = *++YYCURSOR; if (yych <= '/') goto yy18; if (yych >= ':') goto yy18; yy34: ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2); yych = *YYCURSOR; if (yych <= '/') goto yy18; if (yych <= '9') goto yy34; if (yych >= ';') goto yy18; yych = *++YYCURSOR; if (yych != '{') goto yy18; ++YYCURSOR; #line 677 "ext/standard/var_unserializer.re" { long elements = parse_iv(start + 2); /* use iv() not uiv() in order to check data range */ *p = YYCURSOR; if (!var_hash) return 0; if (elements < 0) { return 0; } INIT_PZVAL(*rval); array_init_size(*rval, elements); if (!process_nested_data(UNSERIALIZE_PASSTHRU, Z_ARRVAL_PP(rval), elements, 0)) { return 0; } return finish_nested_data(UNSERIALIZE_PASSTHRU); } #line 860 "ext/standard/var_unserializer.c" yy39: yych = *++YYCURSOR; if (yych == '+') goto yy40; if (yych <= '/') goto yy18; if (yych <= '9') goto yy41; goto yy18; yy40: yych = *++YYCURSOR; if (yych <= '/') goto yy18; if (yych >= ':') goto yy18; yy41: ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2); yych = *YYCURSOR; if (yych <= '/') goto yy18; if (yych <= '9') goto yy41; if (yych >= ';') goto yy18; yych = *++YYCURSOR; if (yych != '"') goto yy18; ++YYCURSOR; #line 642 "ext/standard/var_unserializer.re" { size_t len, maxlen; char *str; len = parse_uiv(start + 2); maxlen = max - YYCURSOR; if (maxlen < len) { *p = start + 2; return 0; } if ((str = unserialize_str(&YYCURSOR, &len, maxlen)) == NULL) { return 0; } if (*(YYCURSOR) != '"') { efree(str); *p = YYCURSOR; return 0; } if (*(YYCURSOR + 1) != ';') { efree(str); *p = YYCURSOR + 1; return 0; } YYCURSOR += 2; *p = YYCURSOR; INIT_PZVAL(*rval); ZVAL_STRINGL(*rval, str, len, 0); return 1; } #line 916 "ext/standard/var_unserializer.c" yy46: yych = *++YYCURSOR; if (yych == '+') goto yy47; if (yych <= '/') goto yy18; if (yych <= '9') goto yy48; goto yy18; yy47: yych = *++YYCURSOR; if (yych <= '/') goto yy18; if (yych >= ':') goto yy18; yy48: ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2); yych = *YYCURSOR; if (yych <= '/') goto yy18; if (yych <= '9') goto yy48; if (yych >= ';') goto yy18; yych = *++YYCURSOR; if (yych != '"') goto yy18; ++YYCURSOR; #line 609 "ext/standard/var_unserializer.re" { size_t len, maxlen; char *str; len = parse_uiv(start + 2); maxlen = max - YYCURSOR; if (maxlen < len) { *p = start + 2; return 0; } str = (char*)YYCURSOR; YYCURSOR += len; if (*(YYCURSOR) != '"') { *p = YYCURSOR; return 0; } if (*(YYCURSOR + 1) != ';') { *p = YYCURSOR + 1; return 0; } YYCURSOR += 2; *p = YYCURSOR; INIT_PZVAL(*rval); ZVAL_STRINGL(*rval, str, len, 1); return 1; } #line 970 "ext/standard/var_unserializer.c" yy53: yych = *++YYCURSOR; if (yych <= '/') { if (yych <= ',') { if (yych == '+') goto yy57; goto yy18; } else { if (yych <= '-') goto yy55; if (yych <= '.') goto yy60; goto yy18; } } else { if (yych <= 'I') { if (yych <= '9') goto yy58; if (yych <= 'H') goto yy18; goto yy56; } else { if (yych != 'N') goto yy18; } } yych = *++YYCURSOR; if (yych == 'A') goto yy76; goto yy18; yy55: yych = *++YYCURSOR; if (yych <= '/') { if (yych == '.') goto yy60; goto yy18; } else { if (yych <= '9') goto yy58; if (yych != 'I') goto yy18; } yy56: yych = *++YYCURSOR; if (yych == 'N') goto yy72; goto yy18; yy57: yych = *++YYCURSOR; if (yych == '.') goto yy60; if (yych <= '/') goto yy18; if (yych >= ':') goto yy18; yy58: ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 4) YYFILL(4); yych = *YYCURSOR; if (yych <= ':') { if (yych <= '.') { if (yych <= '-') goto yy18; goto yy70; } else { if (yych <= '/') goto yy18; if (yych <= '9') goto yy58; goto yy18; } } else { if (yych <= 'E') { if (yych <= ';') goto yy63; if (yych <= 'D') goto yy18; goto yy65; } else { if (yych == 'e') goto yy65; goto yy18; } } yy60: yych = *++YYCURSOR; if (yych <= '/') goto yy18; if (yych >= ':') goto yy18; yy61: ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 4) YYFILL(4); yych = *YYCURSOR; if (yych <= ';') { if (yych <= '/') goto yy18; if (yych <= '9') goto yy61; if (yych <= ':') goto yy18; } else { if (yych <= 'E') { if (yych <= 'D') goto yy18; goto yy65; } else { if (yych == 'e') goto yy65; goto yy18; } } yy63: ++YYCURSOR; #line 599 "ext/standard/var_unserializer.re" { #if SIZEOF_LONG == 4 use_double: #endif *p = YYCURSOR; INIT_PZVAL(*rval); ZVAL_DOUBLE(*rval, zend_strtod((const char *)start + 2, NULL)); return 1; } #line 1068 "ext/standard/var_unserializer.c" yy65: yych = *++YYCURSOR; if (yych <= ',') { if (yych != '+') goto yy18; } else { if (yych <= '-') goto yy66; if (yych <= '/') goto yy18; if (yych <= '9') goto yy67; goto yy18; } yy66: yych = *++YYCURSOR; if (yych <= ',') { if (yych == '+') goto yy69; goto yy18; } else { if (yych <= '-') goto yy69; if (yych <= '/') goto yy18; if (yych >= ':') goto yy18; } yy67: ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; if (yych <= '/') goto yy18; if (yych <= '9') goto yy67; if (yych == ';') goto yy63; goto yy18; yy69: yych = *++YYCURSOR; if (yych <= '/') goto yy18; if (yych <= '9') goto yy67; goto yy18; yy70: ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 4) YYFILL(4); yych = *YYCURSOR; if (yych <= ';') { if (yych <= '/') goto yy18; if (yych <= '9') goto yy70; if (yych <= ':') goto yy18; goto yy63; } else { if (yych <= 'E') { if (yych <= 'D') goto yy18; goto yy65; } else { if (yych == 'e') goto yy65; goto yy18; } } yy72: yych = *++YYCURSOR; if (yych != 'F') goto yy18; yy73: yych = *++YYCURSOR; if (yych != ';') goto yy18; ++YYCURSOR; #line 584 "ext/standard/var_unserializer.re" { *p = YYCURSOR; INIT_PZVAL(*rval); if (!strncmp(start + 2, "NAN", 3)) { ZVAL_DOUBLE(*rval, php_get_nan()); } else if (!strncmp(start + 2, "INF", 3)) { ZVAL_DOUBLE(*rval, php_get_inf()); } else if (!strncmp(start + 2, "-INF", 4)) { ZVAL_DOUBLE(*rval, -php_get_inf()); } return 1; } #line 1142 "ext/standard/var_unserializer.c" yy76: yych = *++YYCURSOR; if (yych == 'N') goto yy73; goto yy18; yy77: yych = *++YYCURSOR; if (yych <= ',') { if (yych != '+') goto yy18; } else { if (yych <= '-') goto yy78; if (yych <= '/') goto yy18; if (yych <= '9') goto yy79; goto yy18; } yy78: yych = *++YYCURSOR; if (yych <= '/') goto yy18; if (yych >= ':') goto yy18; yy79: ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; if (yych <= '/') goto yy18; if (yych <= '9') goto yy79; if (yych != ';') goto yy18; ++YYCURSOR; #line 557 "ext/standard/var_unserializer.re" { #if SIZEOF_LONG == 4 int digits = YYCURSOR - start - 3; if (start[2] == '-' || start[2] == '+') { digits--; } /* Use double for large long values that were serialized on a 64-bit system */ if (digits >= MAX_LENGTH_OF_LONG - 1) { if (digits == MAX_LENGTH_OF_LONG - 1) { int cmp = strncmp(YYCURSOR - MAX_LENGTH_OF_LONG, long_min_digits, MAX_LENGTH_OF_LONG - 1); if (!(cmp < 0 || (cmp == 0 && start[2] == '-'))) { goto use_double; } } else { goto use_double; } } #endif *p = YYCURSOR; INIT_PZVAL(*rval); ZVAL_LONG(*rval, parse_iv(start + 2)); return 1; } #line 1196 "ext/standard/var_unserializer.c" yy83: yych = *++YYCURSOR; if (yych <= '/') goto yy18; if (yych >= '2') goto yy18; yych = *++YYCURSOR; if (yych != ';') goto yy18; ++YYCURSOR; #line 550 "ext/standard/var_unserializer.re" { *p = YYCURSOR; INIT_PZVAL(*rval); ZVAL_BOOL(*rval, parse_iv(start + 2)); return 1; } #line 1211 "ext/standard/var_unserializer.c" yy87: ++YYCURSOR; #line 543 "ext/standard/var_unserializer.re" { *p = YYCURSOR; INIT_PZVAL(*rval); ZVAL_NULL(*rval); return 1; } #line 1221 "ext/standard/var_unserializer.c" yy89: yych = *++YYCURSOR; if (yych <= ',') { if (yych != '+') goto yy18; } else { if (yych <= '-') goto yy90; if (yych <= '/') goto yy18; if (yych <= '9') goto yy91; goto yy18; } yy90: yych = *++YYCURSOR; if (yych <= '/') goto yy18; if (yych >= ':') goto yy18; yy91: ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; if (yych <= '/') goto yy18; if (yych <= '9') goto yy91; if (yych != ';') goto yy18; ++YYCURSOR; #line 520 "ext/standard/var_unserializer.re" { long id; *p = YYCURSOR; if (!var_hash) return 0; id = parse_iv(start + 2) - 1; if (id == -1 || var_access(var_hash, id, &rval_ref) != SUCCESS) { return 0; } if (*rval == *rval_ref) return 0; if (*rval != NULL) { var_push_dtor_no_addref(var_hash, rval); } *rval = *rval_ref; Z_ADDREF_PP(rval); Z_UNSET_ISREF_PP(rval); return 1; } #line 1267 "ext/standard/var_unserializer.c" yy95: yych = *++YYCURSOR; if (yych <= ',') { if (yych != '+') goto yy18; } else { if (yych <= '-') goto yy96; if (yych <= '/') goto yy18; if (yych <= '9') goto yy97; goto yy18; } yy96: yych = *++YYCURSOR; if (yych <= '/') goto yy18; if (yych >= ':') goto yy18; yy97: ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; if (yych <= '/') goto yy18; if (yych <= '9') goto yy97; if (yych != ';') goto yy18; ++YYCURSOR; #line 499 "ext/standard/var_unserializer.re" { long id; *p = YYCURSOR; if (!var_hash) return 0; id = parse_iv(start + 2) - 1; if (id == -1 || var_access(var_hash, id, &rval_ref) != SUCCESS) { return 0; } if (*rval != NULL) { var_push_dtor_no_addref(var_hash, rval); } *rval = *rval_ref; Z_ADDREF_PP(rval); Z_SET_ISREF_PP(rval); return 1; } #line 1311 "ext/standard/var_unserializer.c" } #line 862 "ext/standard/var_unserializer.re" return 0; }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_5280_2
crossvul-cpp_data_bad_3681_0
/* * The NFC Controller Interface is the communication protocol between an * NFC Controller (NFCC) and a Device Host (DH). * * Copyright (C) 2011 Texas Instruments, Inc. * * Written by Ilan Elias <ilane@ti.com> * * Acknowledgements: * This file is based on hci_event.c, which was written * by Maxim Krasnyansky. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 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 * */ #define pr_fmt(fmt) KBUILD_MODNAME ": %s: " fmt, __func__ #include <linux/types.h> #include <linux/interrupt.h> #include <linux/bitops.h> #include <linux/skbuff.h> #include "../nfc.h" #include <net/nfc/nci.h> #include <net/nfc/nci_core.h> #include <linux/nfc.h> /* Handle NCI Notification packets */ static void nci_core_conn_credits_ntf_packet(struct nci_dev *ndev, struct sk_buff *skb) { struct nci_core_conn_credit_ntf *ntf = (void *) skb->data; int i; pr_debug("num_entries %d\n", ntf->num_entries); if (ntf->num_entries > NCI_MAX_NUM_CONN) ntf->num_entries = NCI_MAX_NUM_CONN; /* update the credits */ for (i = 0; i < ntf->num_entries; i++) { ntf->conn_entries[i].conn_id = nci_conn_id(&ntf->conn_entries[i].conn_id); pr_debug("entry[%d]: conn_id %d, credits %d\n", i, ntf->conn_entries[i].conn_id, ntf->conn_entries[i].credits); if (ntf->conn_entries[i].conn_id == NCI_STATIC_RF_CONN_ID) { /* found static rf connection */ atomic_add(ntf->conn_entries[i].credits, &ndev->credits_cnt); } } /* trigger the next tx */ if (!skb_queue_empty(&ndev->tx_q)) queue_work(ndev->tx_wq, &ndev->tx_work); } static void nci_core_generic_error_ntf_packet(struct nci_dev *ndev, struct sk_buff *skb) { __u8 status = skb->data[0]; pr_debug("status 0x%x\n", status); if (atomic_read(&ndev->state) == NCI_W4_HOST_SELECT) { /* Activation failed, so complete the request (the state remains the same) */ nci_req_complete(ndev, status); } } static void nci_core_conn_intf_error_ntf_packet(struct nci_dev *ndev, struct sk_buff *skb) { struct nci_core_intf_error_ntf *ntf = (void *) skb->data; ntf->conn_id = nci_conn_id(&ntf->conn_id); pr_debug("status 0x%x, conn_id %d\n", ntf->status, ntf->conn_id); /* complete the data exchange transaction, if exists */ if (test_bit(NCI_DATA_EXCHANGE, &ndev->flags)) nci_data_exchange_complete(ndev, NULL, -EIO); } static __u8 *nci_extract_rf_params_nfca_passive_poll(struct nci_dev *ndev, struct rf_tech_specific_params_nfca_poll *nfca_poll, __u8 *data) { nfca_poll->sens_res = __le16_to_cpu(*((__u16 *)data)); data += 2; nfca_poll->nfcid1_len = *data++; pr_debug("sens_res 0x%x, nfcid1_len %d\n", nfca_poll->sens_res, nfca_poll->nfcid1_len); memcpy(nfca_poll->nfcid1, data, nfca_poll->nfcid1_len); data += nfca_poll->nfcid1_len; nfca_poll->sel_res_len = *data++; if (nfca_poll->sel_res_len != 0) nfca_poll->sel_res = *data++; pr_debug("sel_res_len %d, sel_res 0x%x\n", nfca_poll->sel_res_len, nfca_poll->sel_res); return data; } static __u8 *nci_extract_rf_params_nfcb_passive_poll(struct nci_dev *ndev, struct rf_tech_specific_params_nfcb_poll *nfcb_poll, __u8 *data) { nfcb_poll->sensb_res_len = *data++; pr_debug("sensb_res_len %d\n", nfcb_poll->sensb_res_len); memcpy(nfcb_poll->sensb_res, data, nfcb_poll->sensb_res_len); data += nfcb_poll->sensb_res_len; return data; } static __u8 *nci_extract_rf_params_nfcf_passive_poll(struct nci_dev *ndev, struct rf_tech_specific_params_nfcf_poll *nfcf_poll, __u8 *data) { nfcf_poll->bit_rate = *data++; nfcf_poll->sensf_res_len = *data++; pr_debug("bit_rate %d, sensf_res_len %d\n", nfcf_poll->bit_rate, nfcf_poll->sensf_res_len); memcpy(nfcf_poll->sensf_res, data, nfcf_poll->sensf_res_len); data += nfcf_poll->sensf_res_len; return data; } static int nci_add_new_protocol(struct nci_dev *ndev, struct nfc_target *target, __u8 rf_protocol, __u8 rf_tech_and_mode, void *params) { struct rf_tech_specific_params_nfca_poll *nfca_poll; struct rf_tech_specific_params_nfcb_poll *nfcb_poll; struct rf_tech_specific_params_nfcf_poll *nfcf_poll; __u32 protocol; if (rf_protocol == NCI_RF_PROTOCOL_T2T) protocol = NFC_PROTO_MIFARE_MASK; else if (rf_protocol == NCI_RF_PROTOCOL_ISO_DEP) protocol = NFC_PROTO_ISO14443_MASK; else if (rf_protocol == NCI_RF_PROTOCOL_T3T) protocol = NFC_PROTO_FELICA_MASK; else protocol = 0; if (!(protocol & ndev->poll_prots)) { pr_err("the target found does not have the desired protocol\n"); return -EPROTO; } if (rf_tech_and_mode == NCI_NFC_A_PASSIVE_POLL_MODE) { nfca_poll = (struct rf_tech_specific_params_nfca_poll *)params; target->sens_res = nfca_poll->sens_res; target->sel_res = nfca_poll->sel_res; target->nfcid1_len = nfca_poll->nfcid1_len; if (target->nfcid1_len > 0) { memcpy(target->nfcid1, nfca_poll->nfcid1, target->nfcid1_len); } } else if (rf_tech_and_mode == NCI_NFC_B_PASSIVE_POLL_MODE) { nfcb_poll = (struct rf_tech_specific_params_nfcb_poll *)params; target->sensb_res_len = nfcb_poll->sensb_res_len; if (target->sensb_res_len > 0) { memcpy(target->sensb_res, nfcb_poll->sensb_res, target->sensb_res_len); } } else if (rf_tech_and_mode == NCI_NFC_F_PASSIVE_POLL_MODE) { nfcf_poll = (struct rf_tech_specific_params_nfcf_poll *)params; target->sensf_res_len = nfcf_poll->sensf_res_len; if (target->sensf_res_len > 0) { memcpy(target->sensf_res, nfcf_poll->sensf_res, target->sensf_res_len); } } else { pr_err("unsupported rf_tech_and_mode 0x%x\n", rf_tech_and_mode); return -EPROTO; } target->supported_protocols |= protocol; pr_debug("protocol 0x%x\n", protocol); return 0; } static void nci_add_new_target(struct nci_dev *ndev, struct nci_rf_discover_ntf *ntf) { struct nfc_target *target; int i, rc; for (i = 0; i < ndev->n_targets; i++) { target = &ndev->targets[i]; if (target->logical_idx == ntf->rf_discovery_id) { /* This target already exists, add the new protocol */ nci_add_new_protocol(ndev, target, ntf->rf_protocol, ntf->rf_tech_and_mode, &ntf->rf_tech_specific_params); return; } } /* This is a new target, check if we've enough room */ if (ndev->n_targets == NCI_MAX_DISCOVERED_TARGETS) { pr_debug("not enough room, ignoring new target...\n"); return; } target = &ndev->targets[ndev->n_targets]; rc = nci_add_new_protocol(ndev, target, ntf->rf_protocol, ntf->rf_tech_and_mode, &ntf->rf_tech_specific_params); if (!rc) { target->logical_idx = ntf->rf_discovery_id; ndev->n_targets++; pr_debug("logical idx %d, n_targets %d\n", target->logical_idx, ndev->n_targets); } } void nci_clear_target_list(struct nci_dev *ndev) { memset(ndev->targets, 0, (sizeof(struct nfc_target)*NCI_MAX_DISCOVERED_TARGETS)); ndev->n_targets = 0; } static void nci_rf_discover_ntf_packet(struct nci_dev *ndev, struct sk_buff *skb) { struct nci_rf_discover_ntf ntf; __u8 *data = skb->data; bool add_target = true; ntf.rf_discovery_id = *data++; ntf.rf_protocol = *data++; ntf.rf_tech_and_mode = *data++; ntf.rf_tech_specific_params_len = *data++; pr_debug("rf_discovery_id %d\n", ntf.rf_discovery_id); pr_debug("rf_protocol 0x%x\n", ntf.rf_protocol); pr_debug("rf_tech_and_mode 0x%x\n", ntf.rf_tech_and_mode); pr_debug("rf_tech_specific_params_len %d\n", ntf.rf_tech_specific_params_len); if (ntf.rf_tech_specific_params_len > 0) { switch (ntf.rf_tech_and_mode) { case NCI_NFC_A_PASSIVE_POLL_MODE: data = nci_extract_rf_params_nfca_passive_poll(ndev, &(ntf.rf_tech_specific_params.nfca_poll), data); break; case NCI_NFC_B_PASSIVE_POLL_MODE: data = nci_extract_rf_params_nfcb_passive_poll(ndev, &(ntf.rf_tech_specific_params.nfcb_poll), data); break; case NCI_NFC_F_PASSIVE_POLL_MODE: data = nci_extract_rf_params_nfcf_passive_poll(ndev, &(ntf.rf_tech_specific_params.nfcf_poll), data); break; default: pr_err("unsupported rf_tech_and_mode 0x%x\n", ntf.rf_tech_and_mode); data += ntf.rf_tech_specific_params_len; add_target = false; } } ntf.ntf_type = *data++; pr_debug("ntf_type %d\n", ntf.ntf_type); if (add_target == true) nci_add_new_target(ndev, &ntf); if (ntf.ntf_type == NCI_DISCOVER_NTF_TYPE_MORE) { atomic_set(&ndev->state, NCI_W4_ALL_DISCOVERIES); } else { atomic_set(&ndev->state, NCI_W4_HOST_SELECT); nfc_targets_found(ndev->nfc_dev, ndev->targets, ndev->n_targets); } } static int nci_extract_activation_params_iso_dep(struct nci_dev *ndev, struct nci_rf_intf_activated_ntf *ntf, __u8 *data) { struct activation_params_nfca_poll_iso_dep *nfca_poll; struct activation_params_nfcb_poll_iso_dep *nfcb_poll; switch (ntf->activation_rf_tech_and_mode) { case NCI_NFC_A_PASSIVE_POLL_MODE: nfca_poll = &ntf->activation_params.nfca_poll_iso_dep; nfca_poll->rats_res_len = *data++; pr_debug("rats_res_len %d\n", nfca_poll->rats_res_len); if (nfca_poll->rats_res_len > 0) { memcpy(nfca_poll->rats_res, data, nfca_poll->rats_res_len); } break; case NCI_NFC_B_PASSIVE_POLL_MODE: nfcb_poll = &ntf->activation_params.nfcb_poll_iso_dep; nfcb_poll->attrib_res_len = *data++; pr_debug("attrib_res_len %d\n", nfcb_poll->attrib_res_len); if (nfcb_poll->attrib_res_len > 0) { memcpy(nfcb_poll->attrib_res, data, nfcb_poll->attrib_res_len); } break; default: pr_err("unsupported activation_rf_tech_and_mode 0x%x\n", ntf->activation_rf_tech_and_mode); return NCI_STATUS_RF_PROTOCOL_ERROR; } return NCI_STATUS_OK; } static void nci_target_auto_activated(struct nci_dev *ndev, struct nci_rf_intf_activated_ntf *ntf) { struct nfc_target *target; int rc; target = &ndev->targets[ndev->n_targets]; rc = nci_add_new_protocol(ndev, target, ntf->rf_protocol, ntf->activation_rf_tech_and_mode, &ntf->rf_tech_specific_params); if (rc) return; target->logical_idx = ntf->rf_discovery_id; ndev->n_targets++; pr_debug("logical idx %d, n_targets %d\n", target->logical_idx, ndev->n_targets); nfc_targets_found(ndev->nfc_dev, ndev->targets, ndev->n_targets); } static void nci_rf_intf_activated_ntf_packet(struct nci_dev *ndev, struct sk_buff *skb) { struct nci_rf_intf_activated_ntf ntf; __u8 *data = skb->data; int err = NCI_STATUS_OK; ntf.rf_discovery_id = *data++; ntf.rf_interface = *data++; ntf.rf_protocol = *data++; ntf.activation_rf_tech_and_mode = *data++; ntf.max_data_pkt_payload_size = *data++; ntf.initial_num_credits = *data++; ntf.rf_tech_specific_params_len = *data++; pr_debug("rf_discovery_id %d\n", ntf.rf_discovery_id); pr_debug("rf_interface 0x%x\n", ntf.rf_interface); pr_debug("rf_protocol 0x%x\n", ntf.rf_protocol); pr_debug("activation_rf_tech_and_mode 0x%x\n", ntf.activation_rf_tech_and_mode); pr_debug("max_data_pkt_payload_size 0x%x\n", ntf.max_data_pkt_payload_size); pr_debug("initial_num_credits 0x%x\n", ntf.initial_num_credits); pr_debug("rf_tech_specific_params_len %d\n", ntf.rf_tech_specific_params_len); if (ntf.rf_tech_specific_params_len > 0) { switch (ntf.activation_rf_tech_and_mode) { case NCI_NFC_A_PASSIVE_POLL_MODE: data = nci_extract_rf_params_nfca_passive_poll(ndev, &(ntf.rf_tech_specific_params.nfca_poll), data); break; case NCI_NFC_B_PASSIVE_POLL_MODE: data = nci_extract_rf_params_nfcb_passive_poll(ndev, &(ntf.rf_tech_specific_params.nfcb_poll), data); break; case NCI_NFC_F_PASSIVE_POLL_MODE: data = nci_extract_rf_params_nfcf_passive_poll(ndev, &(ntf.rf_tech_specific_params.nfcf_poll), data); break; default: pr_err("unsupported activation_rf_tech_and_mode 0x%x\n", ntf.activation_rf_tech_and_mode); err = NCI_STATUS_RF_PROTOCOL_ERROR; goto exit; } } ntf.data_exch_rf_tech_and_mode = *data++; ntf.data_exch_tx_bit_rate = *data++; ntf.data_exch_rx_bit_rate = *data++; ntf.activation_params_len = *data++; pr_debug("data_exch_rf_tech_and_mode 0x%x\n", ntf.data_exch_rf_tech_and_mode); pr_debug("data_exch_tx_bit_rate 0x%x\n", ntf.data_exch_tx_bit_rate); pr_debug("data_exch_rx_bit_rate 0x%x\n", ntf.data_exch_rx_bit_rate); pr_debug("activation_params_len %d\n", ntf.activation_params_len); if (ntf.activation_params_len > 0) { switch (ntf.rf_interface) { case NCI_RF_INTERFACE_ISO_DEP: err = nci_extract_activation_params_iso_dep(ndev, &ntf, data); break; case NCI_RF_INTERFACE_FRAME: /* no activation params */ break; default: pr_err("unsupported rf_interface 0x%x\n", ntf.rf_interface); err = NCI_STATUS_RF_PROTOCOL_ERROR; break; } } exit: if (err == NCI_STATUS_OK) { ndev->max_data_pkt_payload_size = ntf.max_data_pkt_payload_size; ndev->initial_num_credits = ntf.initial_num_credits; /* set the available credits to initial value */ atomic_set(&ndev->credits_cnt, ndev->initial_num_credits); } if (atomic_read(&ndev->state) == NCI_DISCOVERY) { /* A single target was found and activated automatically */ atomic_set(&ndev->state, NCI_POLL_ACTIVE); if (err == NCI_STATUS_OK) nci_target_auto_activated(ndev, &ntf); } else { /* ndev->state == NCI_W4_HOST_SELECT */ /* A selected target was activated, so complete the request */ atomic_set(&ndev->state, NCI_POLL_ACTIVE); nci_req_complete(ndev, err); } } static void nci_rf_deactivate_ntf_packet(struct nci_dev *ndev, struct sk_buff *skb) { struct nci_rf_deactivate_ntf *ntf = (void *) skb->data; pr_debug("entry, type 0x%x, reason 0x%x\n", ntf->type, ntf->reason); /* drop tx data queue */ skb_queue_purge(&ndev->tx_q); /* drop partial rx data packet */ if (ndev->rx_data_reassembly) { kfree_skb(ndev->rx_data_reassembly); ndev->rx_data_reassembly = NULL; } /* complete the data exchange transaction, if exists */ if (test_bit(NCI_DATA_EXCHANGE, &ndev->flags)) nci_data_exchange_complete(ndev, NULL, -EIO); nci_clear_target_list(ndev); atomic_set(&ndev->state, NCI_IDLE); nci_req_complete(ndev, NCI_STATUS_OK); } void nci_ntf_packet(struct nci_dev *ndev, struct sk_buff *skb) { __u16 ntf_opcode = nci_opcode(skb->data); pr_debug("NCI RX: MT=ntf, PBF=%d, GID=0x%x, OID=0x%x, plen=%d\n", nci_pbf(skb->data), nci_opcode_gid(ntf_opcode), nci_opcode_oid(ntf_opcode), nci_plen(skb->data)); /* strip the nci control header */ skb_pull(skb, NCI_CTRL_HDR_SIZE); switch (ntf_opcode) { case NCI_OP_CORE_CONN_CREDITS_NTF: nci_core_conn_credits_ntf_packet(ndev, skb); break; case NCI_OP_CORE_GENERIC_ERROR_NTF: nci_core_generic_error_ntf_packet(ndev, skb); break; case NCI_OP_CORE_INTF_ERROR_NTF: nci_core_conn_intf_error_ntf_packet(ndev, skb); break; case NCI_OP_RF_DISCOVER_NTF: nci_rf_discover_ntf_packet(ndev, skb); break; case NCI_OP_RF_INTF_ACTIVATED_NTF: nci_rf_intf_activated_ntf_packet(ndev, skb); break; case NCI_OP_RF_DEACTIVATE_NTF: nci_rf_deactivate_ntf_packet(ndev, skb); break; default: pr_err("unknown ntf opcode 0x%x\n", ntf_opcode); break; } kfree_skb(skb); }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_3681_0
crossvul-cpp_data_bad_1850_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % SSSSS U U N N % % SS U U NN N % % SSS U U N N N % % SS U U N NN % % SSSSS UUU N N % % % % % % Read/Write Sun Rasterfile Image Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2015 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colormap.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/string_.h" #include "MagickCore/module.h" /* Forward declarations. */ static MagickBooleanType WriteSUNImage(const ImageInfo *,Image *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s S U N % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsSUN() returns MagickTrue if the image format type, identified by the % magick string, is SUN. % % The format of the IsSUN method is: % % MagickBooleanType IsSUN(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsSUN(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (memcmp(magick,"\131\246\152\225",4) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e c o d e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DecodeImage unpacks the packed image pixels into runlength-encoded pixel % packets. % % The format of the DecodeImage method is: % % MagickBooleanType DecodeImage(const unsigned char *compressed_pixels, % const size_t length,unsigned char *pixels) % % A description of each parameter follows: % % o compressed_pixels: The address of a byte (8 bits) array of compressed % pixel data. % % o length: An integer value that is the total number of bytes of the % source image (as just read by ReadBlob) % % o pixels: The address of a byte (8 bits) array of pixel data created by % the uncompression process. The number of bytes in this array % must be at least equal to the number columns times the number of rows % of the source pixels. % */ static MagickBooleanType DecodeImage(const unsigned char *compressed_pixels, const size_t length,unsigned char *pixels,size_t maxpixels) { register const unsigned char *l, *p; register unsigned char *q; ssize_t count; unsigned char byte; (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(compressed_pixels != (unsigned char *) NULL); assert(pixels != (unsigned char *) NULL); p=compressed_pixels; q=pixels; l=q+maxpixels; while (((size_t) (p-compressed_pixels) < length) && (q < l)) { byte=(*p++); if (byte != 128U) *q++=byte; else { /* Runlength-encoded packet: <count><byte> */ count=(ssize_t) (*p++); if (count > 0) byte=(*p++); while ((count >= 0) && (q < l)) { *q++=byte; count--; } } } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d S U N I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadSUNImage() reads a SUN image file and returns it. It allocates % the memory necessary for the new Image structure and returns a pointer to % the new image. % % The format of the ReadSUNImage method is: % % Image *ReadSUNImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadSUNImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define RMT_EQUAL_RGB 1 #define RMT_NONE 0 #define RMT_RAW 2 #define RT_STANDARD 1 #define RT_ENCODED 2 #define RT_FORMAT_RGB 3 typedef struct _SUNInfo { unsigned int magic, width, height, depth, length, type, maptype, maplength; } SUNInfo; Image *image; int bit; MagickBooleanType status; MagickSizeType number_pixels; register Quantum *q; register ssize_t i, x; register unsigned char *p; size_t bytes_per_line, extent, length; ssize_t count, y; SUNInfo sun_info; unsigned char *sun_data, *sun_pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read SUN raster header. */ (void) ResetMagickMemory(&sun_info,0,sizeof(sun_info)); sun_info.magic=ReadBlobMSBLong(image); do { /* Verify SUN identifier. */ if (sun_info.magic != 0x59a66a95) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); sun_info.width=ReadBlobMSBLong(image); sun_info.height=ReadBlobMSBLong(image); sun_info.depth=ReadBlobMSBLong(image); sun_info.length=ReadBlobMSBLong(image); sun_info.type=ReadBlobMSBLong(image); sun_info.maptype=ReadBlobMSBLong(image); sun_info.maplength=ReadBlobMSBLong(image); extent=sun_info.height*sun_info.width; if ((sun_info.height != 0) && (sun_info.width != extent/sun_info.height)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.type != RT_STANDARD) && (sun_info.type != RT_ENCODED) && (sun_info.type != RT_FORMAT_RGB)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.maptype == RMT_NONE) && (sun_info.maplength != 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.depth == 0) || (sun_info.depth > 32)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.maptype != RMT_NONE) && (sun_info.maptype != RMT_EQUAL_RGB) && (sun_info.maptype != RMT_RAW)) ThrowReaderException(CoderError,"ColormapTypeNotSupported"); image->columns=sun_info.width; image->rows=sun_info.height; image->depth=sun_info.depth <= 8 ? sun_info.depth : MAGICKCORE_QUANTUM_DEPTH; if (sun_info.depth < 24) { size_t one; image->storage_class=PseudoClass; image->colors=sun_info.maplength; one=1; if (sun_info.maptype == RMT_NONE) image->colors=one << sun_info.depth; if (sun_info.maptype == RMT_EQUAL_RGB) image->colors=sun_info.maplength/3; } switch (sun_info.maptype) { case RMT_NONE: { if (sun_info.depth < 24) { /* Create linear color ramp. */ if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } break; } case RMT_EQUAL_RGB: { unsigned char *sun_colormap; /* Read SUN raster colormap. */ if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); sun_colormap=(unsigned char *) AcquireQuantumMemory(image->colors, sizeof(*sun_colormap)); if (sun_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,image->colors,sun_colormap); if (count != (ssize_t) image->colors) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].red=(MagickRealType) ScaleCharToQuantum( sun_colormap[i]); count=ReadBlob(image,image->colors,sun_colormap); if (count != (ssize_t) image->colors) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].green=(MagickRealType) ScaleCharToQuantum( sun_colormap[i]); count=ReadBlob(image,image->colors,sun_colormap); if (count != (ssize_t) image->colors) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum( sun_colormap[i]); sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap); break; } case RMT_RAW: { unsigned char *sun_colormap; /* Read SUN raster colormap. */ sun_colormap=(unsigned char *) AcquireQuantumMemory(sun_info.maplength, sizeof(*sun_colormap)); if (sun_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,sun_info.maplength,sun_colormap); if (count != (ssize_t) sun_info.maplength) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap); break; } default: ThrowReaderException(CoderError,"ColormapTypeNotSupported"); } image->alpha_trait=sun_info.depth == 32 ? BlendPixelTrait : UndefinedPixelTrait; image->columns=sun_info.width; image->rows=sun_info.height; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); if ((sun_info.length*sizeof(*sun_data))/sizeof(*sun_data) != sun_info.length || !sun_info.length) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); number_pixels=(MagickSizeType) image->columns*image->rows; if ((sun_info.type != RT_ENCODED) && (sun_info.depth >= 8) && ((number_pixels*((sun_info.depth+7)/8)) > sun_info.length)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); bytes_per_line=sun_info.width*sun_info.depth; sun_data=(unsigned char *) AcquireQuantumMemory((size_t) MagickMax( sun_info.length,bytes_per_line*sun_info.width),sizeof(*sun_data)); if (sun_data == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=(ssize_t) ReadBlob(image,sun_info.length,sun_data); if (count != (ssize_t) sun_info.length) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); sun_pixels=sun_data; bytes_per_line=0; if (sun_info.type == RT_ENCODED) { size_t height; /* Read run-length encoded raster pixels. */ height=sun_info.height; if ((height == 0) || (sun_info.width == 0) || (sun_info.depth == 0) || ((bytes_per_line/sun_info.depth) != sun_info.width)) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); bytes_per_line+=15; bytes_per_line<<=1; if ((bytes_per_line >> 1) != (sun_info.width*sun_info.depth+15)) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); bytes_per_line>>=4; sun_pixels=(unsigned char *) AcquireQuantumMemory(height, bytes_per_line*sizeof(*sun_pixels)); if (sun_pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) DecodeImage(sun_data,sun_info.length,sun_pixels,bytes_per_line* height); sun_data=(unsigned char *) RelinquishMagickMemory(sun_data); } /* Convert SUN raster image to pixel packets. */ p=sun_pixels; if (sun_info.depth == 1) for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < ((ssize_t) image->columns-7); x+=8) { for (bit=7; bit >= 0; bit--) { SetPixelIndex(image,(Quantum) ((*p) & (0x01 << bit) ? 0x00 : 0x01), q); q+=GetPixelChannels(image); } p++; } if ((image->columns % 8) != 0) { for (bit=7; bit >= (int) (8-(image->columns % 8)); bit--) { SetPixelIndex(image,(Quantum) ((*p) & (0x01 << bit) ? 0x00 : 0x01),q); q+=GetPixelChannels(image); } p++; } if ((((image->columns/8)+(image->columns % 8 ? 1 : 0)) % 2) != 0) p++; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } else if (image->storage_class == PseudoClass) { if (bytes_per_line == 0) bytes_per_line=image->columns; length=image->rows*(image->columns+image->columns % 2); if (((sun_info.type == RT_ENCODED) && (length > (bytes_per_line*image->rows))) || ((sun_info.type != RT_ENCODED) && (length > sun_info.length))) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelIndex(image,*p++,q); q+=GetPixelChannels(image); } if ((image->columns % 2) != 0) p++; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else { size_t bytes_per_pixel; bytes_per_pixel=3; if (image->alpha_trait != UndefinedPixelTrait) bytes_per_pixel++; if (bytes_per_line == 0) bytes_per_line=bytes_per_pixel*image->columns; length=image->rows*(bytes_per_line+image->columns % 2); if (((sun_info.type == RT_ENCODED) && (length > (bytes_per_line*image->rows))) || ((sun_info.type != RT_ENCODED) && (length > sun_info.length))) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ScaleCharToQuantum(*p++),q); if (sun_info.type == RT_STANDARD) { SetPixelBlue(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelRed(image,ScaleCharToQuantum(*p++),q); } else { SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelBlue(image,ScaleCharToQuantum(*p++),q); } if (image->colors != 0) { SetPixelRed(image,ClampToQuantum(image->colormap[(ssize_t) GetPixelRed(image,q)].red),q); SetPixelGreen(image,ClampToQuantum(image->colormap[(ssize_t) GetPixelGreen(image,q)].green),q); SetPixelBlue(image,ClampToQuantum(image->colormap[(ssize_t) GetPixelBlue(image,q)].blue),q); } q+=GetPixelChannels(image); } if (((bytes_per_pixel*image->columns) % 2) != 0) p++; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } if (image->storage_class == PseudoClass) (void) SyncImage(image,exception); sun_pixels=(unsigned char *) RelinquishMagickMemory(sun_pixels); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; sun_info.magic=ReadBlobMSBLong(image); if (sun_info.magic == 0x59a66a95) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (sun_info.magic == 0x59a66a95); (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r S U N I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterSUNImage() adds attributes for the SUN image format to % the list of supported formats. The attributes include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterSUNImage method is: % % size_t RegisterSUNImage(void) % */ ModuleExport size_t RegisterSUNImage(void) { MagickInfo *entry; entry=SetMagickInfo("RAS"); entry->decoder=(DecodeImageHandler *) ReadSUNImage; entry->encoder=(EncodeImageHandler *) WriteSUNImage; entry->magick=(IsImageFormatHandler *) IsSUN; entry->description=ConstantString("SUN Rasterfile"); entry->module=ConstantString("SUN"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("SUN"); entry->decoder=(DecodeImageHandler *) ReadSUNImage; entry->encoder=(EncodeImageHandler *) WriteSUNImage; entry->description=ConstantString("SUN Rasterfile"); entry->module=ConstantString("SUN"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r S U N I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterSUNImage() removes format registrations made by the % SUN module from the list of supported formats. % % The format of the UnregisterSUNImage method is: % % UnregisterSUNImage(void) % */ ModuleExport void UnregisterSUNImage(void) { (void) UnregisterMagickInfo("RAS"); (void) UnregisterMagickInfo("SUN"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e S U N I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteSUNImage() writes an image in the SUN rasterfile format. % % The format of the WriteSUNImage method is: % % MagickBooleanType WriteSUNImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WriteSUNImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { #define RMT_EQUAL_RGB 1 #define RMT_NONE 0 #define RMT_RAW 2 #define RT_STANDARD 1 #define RT_FORMAT_RGB 3 typedef struct _SUNInfo { unsigned int magic, width, height, depth, length, type, maptype, maplength; } SUNInfo; MagickBooleanType status; MagickOffsetType scene; MagickSizeType number_pixels; register const Quantum *p; register ssize_t i, x; ssize_t y; SUNInfo sun_info; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); scene=0; do { /* Initialize SUN raster file header. */ (void) TransformImageColorspace(image,sRGBColorspace,exception); sun_info.magic=0x59a66a95; if ((image->columns != (unsigned int) image->columns) || (image->rows != (unsigned int) image->rows)) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); sun_info.width=(unsigned int) image->columns; sun_info.height=(unsigned int) image->rows; sun_info.type=(unsigned int) (image->storage_class == DirectClass ? RT_FORMAT_RGB : RT_STANDARD); sun_info.maptype=RMT_NONE; sun_info.maplength=0; number_pixels=(MagickSizeType) image->columns*image->rows; if ((4*number_pixels) != (size_t) (4*number_pixels)) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if (image->storage_class == DirectClass) { /* Full color SUN raster. */ sun_info.depth=(unsigned int) image->alpha_trait != UndefinedPixelTrait ? 32U : 24U; sun_info.length=(unsigned int) ((image->alpha_trait != UndefinedPixelTrait ? 4 : 3)*number_pixels); sun_info.length+=sun_info.length & 0x01 ? (unsigned int) image->rows : 0; } else if (IsImageMonochrome(image,exception) != MagickFalse) { /* Monochrome SUN raster. */ sun_info.depth=1; sun_info.length=(unsigned int) (((image->columns+7) >> 3)* image->rows); sun_info.length+=(unsigned int) (((image->columns/8)+(image->columns % 8 ? 1 : 0)) % 2 ? image->rows : 0); } else { /* Colormapped SUN raster. */ sun_info.depth=8; sun_info.length=(unsigned int) number_pixels; sun_info.length+=(unsigned int) (image->columns & 0x01 ? image->rows : 0); sun_info.maptype=RMT_EQUAL_RGB; sun_info.maplength=(unsigned int) (3*image->colors); } /* Write SUN header. */ (void) WriteBlobMSBLong(image,sun_info.magic); (void) WriteBlobMSBLong(image,sun_info.width); (void) WriteBlobMSBLong(image,sun_info.height); (void) WriteBlobMSBLong(image,sun_info.depth); (void) WriteBlobMSBLong(image,sun_info.length); (void) WriteBlobMSBLong(image,sun_info.type); (void) WriteBlobMSBLong(image,sun_info.maptype); (void) WriteBlobMSBLong(image,sun_info.maplength); /* Convert MIFF to SUN raster pixels. */ x=0; y=0; if (image->storage_class == DirectClass) { register unsigned char *q; size_t bytes_per_pixel, length; unsigned char *pixels; /* Allocate memory for pixels. */ bytes_per_pixel=3; if (image->alpha_trait != UndefinedPixelTrait) bytes_per_pixel++; length=image->columns; pixels=(unsigned char *) AcquireQuantumMemory(length,4*sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Convert DirectClass packet to SUN RGB pixel. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels; for (x=0; x < (ssize_t) image->columns; x++) { if (image->alpha_trait != UndefinedPixelTrait) *q++=ScaleQuantumToChar(GetPixelAlpha(image,p)); *q++=ScaleQuantumToChar(GetPixelRed(image,p)); *q++=ScaleQuantumToChar(GetPixelGreen(image,p)); *q++=ScaleQuantumToChar(GetPixelBlue(image,p)); p+=GetPixelChannels(image); } if (((bytes_per_pixel*image->columns) & 0x01) != 0) *q++='\0'; /* pad scanline */ (void) WriteBlob(image,(size_t) (q-pixels),pixels); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } pixels=(unsigned char *) RelinquishMagickMemory(pixels); } else if (IsImageMonochrome(image,exception) != MagickFalse) { register unsigned char bit, byte; /* Convert PseudoClass image to a SUN monochrome image. */ (void) SetImageType(image,BilevelType,exception); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; bit=0; byte=0; for (x=0; x < (ssize_t) image->columns; x++) { byte<<=1; if (GetPixelLuma(image,p) < (QuantumRange/2.0)) byte|=0x01; bit++; if (bit == 8) { (void) WriteBlobByte(image,byte); bit=0; byte=0; } p+=GetPixelChannels(image); } if (bit != 0) (void) WriteBlobByte(image,(unsigned char) (byte << (8-bit))); if ((((image->columns/8)+ (image->columns % 8 ? 1 : 0)) % 2) != 0) (void) WriteBlobByte(image,0); /* pad scanline */ if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else { /* Dump colormap to file. */ for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar( ClampToQuantum(image->colormap[i].red))); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar( ClampToQuantum(image->colormap[i].green))); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar( ClampToQuantum(image->colormap[i].blue))); /* Convert PseudoClass packet to SUN colormapped pixel. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { (void) WriteBlobByte(image,(unsigned char) GetPixelIndex(image,p)); p+=GetPixelChannels(image); } if (image->columns & 0x01) (void) WriteBlobByte(image,0); /* pad scanline */ if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(MagickTrue); }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_1850_0
crossvul-cpp_data_bad_4779_4
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % TTTTT IIIII FFFFF FFFFF % % T I F F % % T I FFF FFF % % T I F F % % T IIIII F F % % % % % % Read/Write TIFF Image Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-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/color.h" #include "magick/color-private.h" #include "magick/colormap.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/constitute.h" #include "magick/draw.h" #include "magick/enhance.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/geometry.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/log.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/memory-private.h" #include "magick/module.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/option.h" #include "magick/pixel-accessor.h" #include "magick/pixel-private.h" #include "magick/profile.h" #include "magick/property.h" #include "magick/quantum.h" #include "magick/quantum-private.h" #include "magick/resize.h" #include "magick/resource_.h" #include "magick/semaphore.h" #include "magick/splay-tree.h" #include "magick/static.h" #include "magick/statistic.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/thread_.h" #include "magick/token.h" #include "magick/utility.h" #if defined(MAGICKCORE_TIFF_DELEGATE) # if defined(MAGICKCORE_HAVE_TIFFCONF_H) # include "tiffconf.h" # endif # include "tiff.h" # include "tiffio.h" # if !defined(COMPRESSION_ADOBE_DEFLATE) # define COMPRESSION_ADOBE_DEFLATE 8 # endif # if !defined(PREDICTOR_HORIZONTAL) # define PREDICTOR_HORIZONTAL 2 # endif # if !defined(TIFFTAG_COPYRIGHT) # define TIFFTAG_COPYRIGHT 33432 # endif # if !defined(TIFFTAG_OPIIMAGEID) # define TIFFTAG_OPIIMAGEID 32781 # endif #include "psd-private.h" /* Typedef declarations. */ typedef enum { ReadSingleSampleMethod, ReadRGBAMethod, ReadCMYKAMethod, ReadYCCKMethod, ReadStripMethod, ReadTileMethod, ReadGenericMethod } TIFFMethodType; #if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY) typedef struct _ExifInfo { unsigned int tag, type, variable_length; const char *property; } ExifInfo; static const ExifInfo exif_info[] = { { EXIFTAG_EXPOSURETIME, TIFF_RATIONAL, 0, "exif:ExposureTime" }, { EXIFTAG_FNUMBER, TIFF_RATIONAL, 0, "exif:FNumber" }, { EXIFTAG_EXPOSUREPROGRAM, TIFF_SHORT, 0, "exif:ExposureProgram" }, { EXIFTAG_SPECTRALSENSITIVITY, TIFF_ASCII, 0, "exif:SpectralSensitivity" }, { EXIFTAG_ISOSPEEDRATINGS, TIFF_SHORT, 1, "exif:ISOSpeedRatings" }, { EXIFTAG_OECF, TIFF_NOTYPE, 0, "exif:OptoelectricConversionFactor" }, { EXIFTAG_EXIFVERSION, TIFF_NOTYPE, 0, "exif:ExifVersion" }, { EXIFTAG_DATETIMEORIGINAL, TIFF_ASCII, 0, "exif:DateTimeOriginal" }, { EXIFTAG_DATETIMEDIGITIZED, TIFF_ASCII, 0, "exif:DateTimeDigitized" }, { EXIFTAG_COMPONENTSCONFIGURATION, TIFF_NOTYPE, 0, "exif:ComponentsConfiguration" }, { EXIFTAG_COMPRESSEDBITSPERPIXEL, TIFF_RATIONAL, 0, "exif:CompressedBitsPerPixel" }, { EXIFTAG_SHUTTERSPEEDVALUE, TIFF_SRATIONAL, 0, "exif:ShutterSpeedValue" }, { EXIFTAG_APERTUREVALUE, TIFF_RATIONAL, 0, "exif:ApertureValue" }, { EXIFTAG_BRIGHTNESSVALUE, TIFF_SRATIONAL, 0, "exif:BrightnessValue" }, { EXIFTAG_EXPOSUREBIASVALUE, TIFF_SRATIONAL, 0, "exif:ExposureBiasValue" }, { EXIFTAG_MAXAPERTUREVALUE, TIFF_RATIONAL, 0, "exif:MaxApertureValue" }, { EXIFTAG_SUBJECTDISTANCE, TIFF_RATIONAL, 0, "exif:SubjectDistance" }, { EXIFTAG_METERINGMODE, TIFF_SHORT, 0, "exif:MeteringMode" }, { EXIFTAG_LIGHTSOURCE, TIFF_SHORT, 0, "exif:LightSource" }, { EXIFTAG_FLASH, TIFF_SHORT, 0, "exif:Flash" }, { EXIFTAG_FOCALLENGTH, TIFF_RATIONAL, 0, "exif:FocalLength" }, { EXIFTAG_SUBJECTAREA, TIFF_NOTYPE, 0, "exif:SubjectArea" }, { EXIFTAG_MAKERNOTE, TIFF_NOTYPE, 0, "exif:MakerNote" }, { EXIFTAG_USERCOMMENT, TIFF_NOTYPE, 0, "exif:UserComment" }, { EXIFTAG_SUBSECTIME, TIFF_ASCII, 0, "exif:SubSecTime" }, { EXIFTAG_SUBSECTIMEORIGINAL, TIFF_ASCII, 0, "exif:SubSecTimeOriginal" }, { EXIFTAG_SUBSECTIMEDIGITIZED, TIFF_ASCII, 0, "exif:SubSecTimeDigitized" }, { EXIFTAG_FLASHPIXVERSION, TIFF_NOTYPE, 0, "exif:FlashpixVersion" }, { EXIFTAG_PIXELXDIMENSION, TIFF_LONG, 0, "exif:PixelXDimension" }, { EXIFTAG_PIXELYDIMENSION, TIFF_LONG, 0, "exif:PixelYDimension" }, { EXIFTAG_RELATEDSOUNDFILE, TIFF_ASCII, 0, "exif:RelatedSoundFile" }, { EXIFTAG_FLASHENERGY, TIFF_RATIONAL, 0, "exif:FlashEnergy" }, { EXIFTAG_SPATIALFREQUENCYRESPONSE, TIFF_NOTYPE, 0, "exif:SpatialFrequencyResponse" }, { EXIFTAG_FOCALPLANEXRESOLUTION, TIFF_RATIONAL, 0, "exif:FocalPlaneXResolution" }, { EXIFTAG_FOCALPLANEYRESOLUTION, TIFF_RATIONAL, 0, "exif:FocalPlaneYResolution" }, { EXIFTAG_FOCALPLANERESOLUTIONUNIT, TIFF_SHORT, 0, "exif:FocalPlaneResolutionUnit" }, { EXIFTAG_SUBJECTLOCATION, TIFF_SHORT, 0, "exif:SubjectLocation" }, { EXIFTAG_EXPOSUREINDEX, TIFF_RATIONAL, 0, "exif:ExposureIndex" }, { EXIFTAG_SENSINGMETHOD, TIFF_SHORT, 0, "exif:SensingMethod" }, { EXIFTAG_FILESOURCE, TIFF_NOTYPE, 0, "exif:FileSource" }, { EXIFTAG_SCENETYPE, TIFF_NOTYPE, 0, "exif:SceneType" }, { EXIFTAG_CFAPATTERN, TIFF_NOTYPE, 0, "exif:CFAPattern" }, { EXIFTAG_CUSTOMRENDERED, TIFF_SHORT, 0, "exif:CustomRendered" }, { EXIFTAG_EXPOSUREMODE, TIFF_SHORT, 0, "exif:ExposureMode" }, { EXIFTAG_WHITEBALANCE, TIFF_SHORT, 0, "exif:WhiteBalance" }, { EXIFTAG_DIGITALZOOMRATIO, TIFF_RATIONAL, 0, "exif:DigitalZoomRatio" }, { EXIFTAG_FOCALLENGTHIN35MMFILM, TIFF_SHORT, 0, "exif:FocalLengthIn35mmFilm" }, { EXIFTAG_SCENECAPTURETYPE, TIFF_SHORT, 0, "exif:SceneCaptureType" }, { EXIFTAG_GAINCONTROL, TIFF_RATIONAL, 0, "exif:GainControl" }, { EXIFTAG_CONTRAST, TIFF_SHORT, 0, "exif:Contrast" }, { EXIFTAG_SATURATION, TIFF_SHORT, 0, "exif:Saturation" }, { EXIFTAG_SHARPNESS, TIFF_SHORT, 0, "exif:Sharpness" }, { EXIFTAG_DEVICESETTINGDESCRIPTION, TIFF_NOTYPE, 0, "exif:DeviceSettingDescription" }, { EXIFTAG_SUBJECTDISTANCERANGE, TIFF_SHORT, 0, "exif:SubjectDistanceRange" }, { EXIFTAG_IMAGEUNIQUEID, TIFF_ASCII, 0, "exif:ImageUniqueID" }, { 0, 0, 0, (char *) NULL } }; #endif #endif /* MAGICKCORE_TIFF_DELEGATE */ /* Global declarations. */ static MagickThreadKey tiff_exception; static SemaphoreInfo *tiff_semaphore = (SemaphoreInfo *) NULL; static TIFFErrorHandler error_handler, warning_handler; static volatile MagickBooleanType instantiate_key = MagickFalse; /* Forward declarations. */ #if defined(MAGICKCORE_TIFF_DELEGATE) static Image * ReadTIFFImage(const ImageInfo *,ExceptionInfo *); static MagickBooleanType WriteGROUP4Image(const ImageInfo *,Image *), WritePTIFImage(const ImageInfo *,Image *), WriteTIFFImage(const ImageInfo *,Image *); #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s T I F F % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsTIFF() returns MagickTrue if the image format type, identified by the % magick string, is TIFF. % % The format of the IsTIFF method is: % % MagickBooleanType IsTIFF(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsTIFF(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (memcmp(magick,"\115\115\000\052",4) == 0) return(MagickTrue); if (memcmp(magick,"\111\111\052\000",4) == 0) return(MagickTrue); #if defined(TIFF_VERSION_BIG) if (length < 8) return(MagickFalse); if (memcmp(magick,"\115\115\000\053\000\010\000\000",8) == 0) return(MagickTrue); if (memcmp(magick,"\111\111\053\000\010\000\000\000",8) == 0) return(MagickTrue); #endif return(MagickFalse); } #if defined(MAGICKCORE_TIFF_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d G R O U P 4 I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadGROUP4Image() reads a raw CCITT Group 4 image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadGROUP4Image method is: % % Image *ReadGROUP4Image(const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static inline size_t WriteLSBLong(FILE *file,const size_t value) { unsigned char buffer[4]; buffer[0]=(unsigned char) value; buffer[1]=(unsigned char) (value >> 8); buffer[2]=(unsigned char) (value >> 16); buffer[3]=(unsigned char) (value >> 24); return(fwrite(buffer,1,4,file)); } static Image *ReadGROUP4Image(const ImageInfo *image_info, ExceptionInfo *exception) { char filename[MaxTextExtent]; FILE *file; Image *image; ImageInfo *read_info; int c, unique_file; MagickBooleanType status; size_t length; ssize_t offset, strip_offset; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == 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); } /* Write raw CCITT Group 4 wrapped as a TIFF image file. */ file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); if (unique_file != -1) file=fdopen(unique_file,"wb"); if ((unique_file == -1) || (file == (FILE *) NULL)) ThrowImageException(FileOpenError,"UnableToCreateTemporaryFile"); length=fwrite("\111\111\052\000\010\000\000\000\016\000",1,10,file); length=fwrite("\376\000\003\000\001\000\000\000\000\000\000\000",1,12,file); length=fwrite("\000\001\004\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,image->columns); length=fwrite("\001\001\004\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,image->rows); length=fwrite("\002\001\003\000\001\000\000\000\001\000\000\000",1,12,file); length=fwrite("\003\001\003\000\001\000\000\000\004\000\000\000",1,12,file); length=fwrite("\006\001\003\000\001\000\000\000\000\000\000\000",1,12,file); length=fwrite("\021\001\003\000\001\000\000\000",1,8,file); strip_offset=10+(12*14)+4+8; length=WriteLSBLong(file,(size_t) strip_offset); length=fwrite("\022\001\003\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,(size_t) image_info->orientation); length=fwrite("\025\001\003\000\001\000\000\000\001\000\000\000",1,12,file); length=fwrite("\026\001\004\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,image->rows); length=fwrite("\027\001\004\000\001\000\000\000\000\000\000\000",1,12,file); offset=(ssize_t) ftell(file)-4; length=fwrite("\032\001\005\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,(size_t) (strip_offset-8)); length=fwrite("\033\001\005\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,(size_t) (strip_offset-8)); length=fwrite("\050\001\003\000\001\000\000\000\002\000\000\000",1,12,file); length=fwrite("\000\000\000\000",1,4,file); length=WriteLSBLong(file,(size_t) (image->x_resolution+0.5)); length=WriteLSBLong(file,1); status=MagickTrue; for (length=0; (c=ReadBlobByte(image)) != EOF; length++) if (fputc(c,file) != c) status=MagickFalse; offset=(ssize_t) fseek(file,(ssize_t) offset,SEEK_SET); length=WriteLSBLong(file,(unsigned int) length); (void) fclose(file); (void) CloseBlob(image); image=DestroyImage(image); /* Read TIFF image. */ read_info=CloneImageInfo((ImageInfo *) NULL); (void) FormatLocaleString(read_info->filename,MaxTextExtent,"%s",filename); image=ReadTIFFImage(read_info,exception); read_info=DestroyImageInfo(read_info); if (image != (Image *) NULL) { (void) CopyMagickString(image->filename,image_info->filename, MaxTextExtent); (void) CopyMagickString(image->magick_filename,image_info->filename, MaxTextExtent); (void) CopyMagickString(image->magick,"GROUP4",MaxTextExtent); } (void) RelinquishUniqueFileResource(filename); if (status == MagickFalse) image=DestroyImage(image); return(image); } #endif #if defined(MAGICKCORE_TIFF_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d T I F F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadTIFFImage() reads a Tagged image file and returns it. It allocates the % memory necessary for the new Image structure and returns a pointer to the % new image. % % The format of the ReadTIFFImage method is: % % Image *ReadTIFFImage(const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static inline unsigned char ClampYCC(double value) { value=255.0-value; if (value < 0.0) return((unsigned char)0); if (value > 255.0) return((unsigned char)255); return((unsigned char)(value)); } static MagickBooleanType DecodeLabImage(Image *image,ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; ssize_t y; status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double a, b; a=QuantumScale*GetPixela(q)+0.5; if (a > 1.0) a-=1.0; b=QuantumScale*GetPixelb(q)+0.5; if (b > 1.0) b-=1.0; SetPixela(q,QuantumRange*a); SetPixelb(q,QuantumRange*b); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status); } static MagickBooleanType ReadProfile(Image *image,const char *name, const unsigned char *datum,ssize_t length) { MagickBooleanType status; StringInfo *profile; if (length < 4) return(MagickFalse); profile=BlobToStringInfo(datum,(size_t) length); if (profile == (StringInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=SetImageProfile(image,name,profile); profile=DestroyStringInfo(profile); if (status == MagickFalse) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); return(MagickTrue); } #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static int TIFFCloseBlob(thandle_t image) { (void) CloseBlob((Image *) image); return(0); } static void TIFFErrors(const char *module,const char *format,va_list error) { char message[MaxTextExtent]; ExceptionInfo *exception; #if defined(MAGICKCORE_HAVE_VSNPRINTF) (void) vsnprintf(message,MaxTextExtent,format,error); #else (void) vsprintf(message,format,error); #endif (void) ConcatenateMagickString(message,".",MaxTextExtent); exception=(ExceptionInfo *) GetMagickThreadValue(tiff_exception); if (exception != (ExceptionInfo *) NULL) (void) ThrowMagickException(exception,GetMagickModule(),CoderError,message, "`%s'",module); } static toff_t TIFFGetBlobSize(thandle_t image) { return((toff_t) GetBlobSize((Image *) image)); } static void TIFFGetProfiles(TIFF *tiff,Image *image,MagickBooleanType ping) { uint32 length; unsigned char *profile; length=0; if (ping == MagickFalse) { #if defined(TIFFTAG_ICCPROFILE) if ((TIFFGetField(tiff,TIFFTAG_ICCPROFILE,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) (void) ReadProfile(image,"icc",profile,(ssize_t) length); #endif #if defined(TIFFTAG_PHOTOSHOP) if ((TIFFGetField(tiff,TIFFTAG_PHOTOSHOP,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) (void) ReadProfile(image,"8bim",profile,(ssize_t) length); #endif #if defined(TIFFTAG_RICHTIFFIPTC) if ((TIFFGetField(tiff,TIFFTAG_RICHTIFFIPTC,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) { if (TIFFIsByteSwapped(tiff) != 0) TIFFSwabArrayOfLong((uint32 *) profile,(size_t) length); (void) ReadProfile(image,"iptc",profile,4L*length); } #endif #if defined(TIFFTAG_XMLPACKET) if ((TIFFGetField(tiff,TIFFTAG_XMLPACKET,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) (void) ReadProfile(image,"xmp",profile,(ssize_t) length); #endif if ((TIFFGetField(tiff,34118,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) (void) ReadProfile(image,"tiff:34118",profile,(ssize_t) length); } if ((TIFFGetField(tiff,37724,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) (void) ReadProfile(image,"tiff:37724",profile,(ssize_t) length); } static void TIFFGetProperties(TIFF *tiff,Image *image) { char message[MaxTextExtent], *text; uint32 count, length, type; unsigned long *tietz; if (TIFFGetField(tiff,TIFFTAG_ARTIST,&text) == 1) (void) SetImageProperty(image,"tiff:artist",text); if (TIFFGetField(tiff,TIFFTAG_COPYRIGHT,&text) == 1) (void) SetImageProperty(image,"tiff:copyright",text); if (TIFFGetField(tiff,TIFFTAG_DATETIME,&text) == 1) (void) SetImageProperty(image,"tiff:timestamp",text); if (TIFFGetField(tiff,TIFFTAG_DOCUMENTNAME,&text) == 1) (void) SetImageProperty(image,"tiff:document",text); if (TIFFGetField(tiff,TIFFTAG_HOSTCOMPUTER,&text) == 1) (void) SetImageProperty(image,"tiff:hostcomputer",text); if (TIFFGetField(tiff,TIFFTAG_IMAGEDESCRIPTION,&text) == 1) (void) SetImageProperty(image,"comment",text); if (TIFFGetField(tiff,TIFFTAG_MAKE,&text) == 1) (void) SetImageProperty(image,"tiff:make",text); if (TIFFGetField(tiff,TIFFTAG_MODEL,&text) == 1) (void) SetImageProperty(image,"tiff:model",text); if (TIFFGetField(tiff,TIFFTAG_OPIIMAGEID,&count,&text) == 1) { if (count >= MaxTextExtent) count=MaxTextExtent-1; (void) CopyMagickString(message,text,count+1); (void) SetImageProperty(image,"tiff:image-id",message); } if (TIFFGetField(tiff,TIFFTAG_PAGENAME,&text) == 1) (void) SetImageProperty(image,"label",text); if (TIFFGetField(tiff,TIFFTAG_SOFTWARE,&text) == 1) (void) SetImageProperty(image,"tiff:software",text); if (TIFFGetField(tiff,33423,&count,&text) == 1) { if (count >= MaxTextExtent) count=MaxTextExtent-1; (void) CopyMagickString(message,text,count+1); (void) SetImageProperty(image,"tiff:kodak-33423",message); } if (TIFFGetField(tiff,36867,&count,&text) == 1) { if (count >= MaxTextExtent) count=MaxTextExtent-1; (void) CopyMagickString(message,text,count+1); (void) SetImageProperty(image,"tiff:kodak-36867",message); } if (TIFFGetField(tiff,TIFFTAG_SUBFILETYPE,&type) == 1) switch (type) { case 0x01: { (void) SetImageProperty(image,"tiff:subfiletype","REDUCEDIMAGE"); break; } case 0x02: { (void) SetImageProperty(image,"tiff:subfiletype","PAGE"); break; } case 0x04: { (void) SetImageProperty(image,"tiff:subfiletype","MASK"); break; } default: break; } if (TIFFGetField(tiff,37706,&length,&tietz) == 1) { (void) FormatLocaleString(message,MaxTextExtent,"%lu",tietz[0]); (void) SetImageProperty(image,"tiff:tietz_offset",message); } } static void TIFFGetEXIFProperties(TIFF *tiff,Image *image) { #if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY) char value[MaxTextExtent]; register ssize_t i; tdir_t directory; #if defined(TIFF_VERSION_BIG) uint64 #else uint32 #endif offset; void *sans; /* Read EXIF properties. */ offset=0; if (TIFFGetField(tiff,TIFFTAG_EXIFIFD,&offset) != 1) return; directory=TIFFCurrentDirectory(tiff); if (TIFFReadEXIFDirectory(tiff,offset) != 1) { TIFFSetDirectory(tiff,directory); return; } sans=NULL; for (i=0; exif_info[i].tag != 0; i++) { *value='\0'; switch (exif_info[i].type) { case TIFF_ASCII: { char *ascii; ascii=(char *) NULL; if ((TIFFGetField(tiff,exif_info[i].tag,&ascii,&sans,&sans) == 1) && (ascii != (char *) NULL) && (*ascii != '\0')) (void) CopyMagickString(value,ascii,MaxTextExtent); break; } case TIFF_SHORT: { if (exif_info[i].variable_length == 0) { uint16 shorty; shorty=0; if (TIFFGetField(tiff,exif_info[i].tag,&shorty,&sans,&sans) == 1) (void) FormatLocaleString(value,MaxTextExtent,"%d",shorty); } else { int tiff_status; uint16 *shorty; uint16 shorty_num; tiff_status=TIFFGetField(tiff,exif_info[i].tag,&shorty_num,&shorty, &sans,&sans); if (tiff_status == 1) (void) FormatLocaleString(value,MaxTextExtent,"%d", shorty_num != 0 ? shorty[0] : 0); } break; } case TIFF_LONG: { uint32 longy; longy=0; if (TIFFGetField(tiff,exif_info[i].tag,&longy,&sans,&sans) == 1) (void) FormatLocaleString(value,MaxTextExtent,"%d",longy); break; } #if defined(TIFF_VERSION_BIG) case TIFF_LONG8: { uint64 long8y; long8y=0; if (TIFFGetField(tiff,exif_info[i].tag,&long8y,&sans,&sans) == 1) (void) FormatLocaleString(value,MaxTextExtent,"%.20g",(double) ((MagickOffsetType) long8y)); break; } #endif case TIFF_RATIONAL: case TIFF_SRATIONAL: case TIFF_FLOAT: { float floaty; floaty=0.0; if (TIFFGetField(tiff,exif_info[i].tag,&floaty,&sans,&sans) == 1) (void) FormatLocaleString(value,MaxTextExtent,"%g",(double) floaty); break; } case TIFF_DOUBLE: { double doubley; doubley=0.0; if (TIFFGetField(tiff,exif_info[i].tag,&doubley,&sans,&sans) == 1) (void) FormatLocaleString(value,MaxTextExtent,"%g",doubley); break; } default: break; } if (*value != '\0') (void) SetImageProperty(image,exif_info[i].property,value); } TIFFSetDirectory(tiff,directory); #else (void) tiff; (void) image; #endif } static int TIFFMapBlob(thandle_t image,tdata_t *base,toff_t *size) { *base=(tdata_t *) GetBlobStreamData((Image *) image); if (*base != (tdata_t *) NULL) *size=(toff_t) GetBlobSize((Image *) image); if (*base != (tdata_t *) NULL) return(1); return(0); } static tsize_t TIFFReadBlob(thandle_t image,tdata_t data,tsize_t size) { tsize_t count; count=(tsize_t) ReadBlob((Image *) image,(size_t) size, (unsigned char *) data); return(count); } static int32 TIFFReadPixels(TIFF *tiff,size_t bits_per_sample, tsample_t sample,ssize_t row,tdata_t scanline) { int32 status; (void) bits_per_sample; status=TIFFReadScanline(tiff,scanline,(uint32) row,sample); return(status); } static toff_t TIFFSeekBlob(thandle_t image,toff_t offset,int whence) { return((toff_t) SeekBlob((Image *) image,(MagickOffsetType) offset,whence)); } static void TIFFUnmapBlob(thandle_t image,tdata_t base,toff_t size) { (void) image; (void) base; (void) size; } static void TIFFWarnings(const char *module,const char *format,va_list warning) { char message[MaxTextExtent]; ExceptionInfo *exception; #if defined(MAGICKCORE_HAVE_VSNPRINTF) (void) vsnprintf(message,MaxTextExtent,format,warning); #else (void) vsprintf(message,format,warning); #endif (void) ConcatenateMagickString(message,".",MaxTextExtent); exception=(ExceptionInfo *) GetMagickThreadValue(tiff_exception); if (exception != (ExceptionInfo *) NULL) (void) ThrowMagickException(exception,GetMagickModule(),CoderWarning, message,"`%s'",module); } static tsize_t TIFFWriteBlob(thandle_t image,tdata_t data,tsize_t size) { tsize_t count; count=(tsize_t) WriteBlob((Image *) image,(size_t) size, (unsigned char *) data); return(count); } static TIFFMethodType GetJPEGMethod(Image* image,TIFF *tiff,uint16 photometric, uint16 bits_per_sample,uint16 samples_per_pixel) { #define BUFFER_SIZE 2048 MagickOffsetType position, offset; register size_t i; TIFFMethodType method; #if defined(TIFF_VERSION_BIG) uint64 #else uint32 #endif **value; unsigned char buffer[BUFFER_SIZE+32]; unsigned short length; /* only support 8 bit for now */ if ((photometric != PHOTOMETRIC_SEPARATED) || (bits_per_sample != 8) || (samples_per_pixel != 4)) return(ReadGenericMethod); /* Search for Adobe APP14 JPEG Marker */ if (!TIFFGetField(tiff,TIFFTAG_STRIPOFFSETS,&value)) return(ReadRGBAMethod); position=TellBlob(image); offset=(MagickOffsetType) (value[0]); if (SeekBlob(image,offset,SEEK_SET) != offset) return(ReadRGBAMethod); method=ReadRGBAMethod; if (ReadBlob(image,BUFFER_SIZE,buffer) == BUFFER_SIZE) { for (i=0; i < BUFFER_SIZE; i++) { while (i < BUFFER_SIZE) { if (buffer[i++] == 255) break; } while (i < BUFFER_SIZE) { if (buffer[++i] != 255) break; } if (buffer[i++] == 216) /* JPEG_MARKER_SOI */ continue; length=(unsigned short) (((unsigned int) (buffer[i] << 8) | (unsigned int) buffer[i+1]) & 0xffff); if (i+(size_t) length >= BUFFER_SIZE) break; if (buffer[i-1] == 238) /* JPEG_MARKER_APP0+14 */ { if (length != 14) break; /* 0 == CMYK, 1 == YCbCr, 2 = YCCK */ if (buffer[i+13] == 2) method=ReadYCCKMethod; break; } i+=(size_t) length; } } (void) SeekBlob(image,position,SEEK_SET); return(method); } static void TIFFReadPhotoshopLayers(Image* image,const ImageInfo *image_info, ExceptionInfo *exception) { const char *option; const StringInfo *layer_info; Image *layers; PSDInfo info; register ssize_t i; if (GetImageListLength(image) != 1) return; if ((image_info->number_scenes == 1) && (image_info->scene == 0)) return; option=GetImageOption(image_info,"tiff:ignore-layers"); if (option != (const char * ) NULL) return; layer_info=GetImageProfile(image,"tiff:37724"); if (layer_info == (const StringInfo *) NULL) return; for (i=0; i < (ssize_t) layer_info->length-8; i++) { if (LocaleNCompare((const char *) (layer_info->datum+i), image->endian == MSBEndian ? "8BIM" : "MIB8",4) != 0) continue; i+=4; if ((LocaleNCompare((const char *) (layer_info->datum+i), image->endian == MSBEndian ? "Layr" : "ryaL",4) == 0) || (LocaleNCompare((const char *) (layer_info->datum+i), image->endian == MSBEndian ? "LMsk" : "ksML",4) == 0) || (LocaleNCompare((const char *) (layer_info->datum+i), image->endian == MSBEndian ? "Lr16" : "61rL",4) == 0) || (LocaleNCompare((const char *) (layer_info->datum+i), image->endian == MSBEndian ? "Lr32" : "23rL",4) == 0)) break; } i+=4; if (i >= (ssize_t) (layer_info->length-8)) return; layers=CloneImage(image,image->columns,image->rows,MagickTrue,exception); (void) DeleteImageProfile(layers,"tiff:37724"); AttachBlob(layers->blob,layer_info->datum,layer_info->length); SeekBlob(layers,(MagickOffsetType) i,SEEK_SET); info.version=1; info.columns=layers->columns; info.rows=layers->rows; /* Setting the mode to a value that won't change the colorspace */ info.mode=10; if (IsGrayImage(image,&image->exception) != MagickFalse) info.channels=(image->matte != MagickFalse ? 2UL : 1UL); else if (image->storage_class == PseudoClass) info.channels=(image->matte != MagickFalse ? 2UL : 1UL); else { if (image->colorspace != CMYKColorspace) info.channels=(image->matte != MagickFalse ? 4UL : 3UL); else info.channels=(image->matte != MagickFalse ? 5UL : 4UL); } (void) ReadPSDLayers(layers,image_info,&info,MagickFalse,exception); InheritException(exception,&layers->exception); DeleteImageFromList(&layers); if (layers != (Image *) NULL) { SetImageArtifact(image,"tiff:has-layers","true"); AppendImageToList(&image,layers); while (layers != (Image *) NULL) { SetImageArtifact(layers,"tiff:has-layers","true"); DetachBlob(layers->blob); layers=GetNextImageInList(layers); } } } #if defined(__cplusplus) || defined(c_plusplus) } #endif static Image *ReadTIFFImage(const ImageInfo *image_info, ExceptionInfo *exception) { const char *option; float *chromaticity, x_position, y_position, x_resolution, y_resolution; Image *image; int tiff_status; MagickBooleanType status; MagickSizeType number_pixels; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; size_t pad; ssize_t y; TIFF *tiff; TIFFMethodType method; uint16 compress_tag, bits_per_sample, endian, extra_samples, interlace, max_sample_value, min_sample_value, orientation, pages, photometric, *sample_info, sample_format, samples_per_pixel, units, value; uint32 height, rows_per_strip, width; unsigned char *pixels; /* Open image. */ 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); } (void) SetMagickThreadValue(tiff_exception,exception); tiff=TIFFClientOpen(image->filename,"rb",(thandle_t) image,TIFFReadBlob, TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob, TIFFUnmapBlob); if (tiff == (TIFF *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } if (image_info->number_scenes != 0) { /* Generate blank images for subimage specification (e.g. image.tif[4]. We need to check the number of directores because it is possible that the subimage(s) are stored in the photoshop profile. */ if (image_info->scene < (size_t)TIFFNumberOfDirectories(tiff)) { for (i=0; i < (ssize_t) image_info->scene; i++) { status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse; if (status == MagickFalse) { TIFFClose(tiff); image=DestroyImageList(image); return((Image *) NULL); } AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { TIFFClose(tiff); image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); } } } do { DisableMSCWarning(4127) if (0 && (image_info->verbose != MagickFalse)) TIFFPrintDirectory(tiff,stdout,MagickFalse); RestoreMSCWarning if ((TIFFGetField(tiff,TIFFTAG_IMAGEWIDTH,&width) != 1) || (TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&height) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_COMPRESSION,&compress_tag) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_PLANARCONFIG,&interlace) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,&samples_per_pixel) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,&bits_per_sample) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLEFORMAT,&sample_format) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_MINSAMPLEVALUE,&min_sample_value) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_MAXSAMPLEVALUE,&max_sample_value) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_PHOTOMETRIC,&photometric) != 1)) { TIFFClose(tiff); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (sample_format == SAMPLEFORMAT_IEEEFP) (void) SetImageProperty(image,"quantum:format","floating-point"); switch (photometric) { case PHOTOMETRIC_MINISBLACK: { (void) SetImageProperty(image,"tiff:photometric","min-is-black"); break; } case PHOTOMETRIC_MINISWHITE: { (void) SetImageProperty(image,"tiff:photometric","min-is-white"); break; } case PHOTOMETRIC_PALETTE: { (void) SetImageProperty(image,"tiff:photometric","palette"); break; } case PHOTOMETRIC_RGB: { (void) SetImageProperty(image,"tiff:photometric","RGB"); break; } case PHOTOMETRIC_CIELAB: { (void) SetImageProperty(image,"tiff:photometric","CIELAB"); break; } case PHOTOMETRIC_LOGL: { (void) SetImageProperty(image,"tiff:photometric","CIE Log2(L)"); break; } case PHOTOMETRIC_LOGLUV: { (void) SetImageProperty(image,"tiff:photometric","LOGLUV"); break; } #if defined(PHOTOMETRIC_MASK) case PHOTOMETRIC_MASK: { (void) SetImageProperty(image,"tiff:photometric","MASK"); break; } #endif case PHOTOMETRIC_SEPARATED: { (void) SetImageProperty(image,"tiff:photometric","separated"); break; } case PHOTOMETRIC_YCBCR: { (void) SetImageProperty(image,"tiff:photometric","YCBCR"); break; } default: { (void) SetImageProperty(image,"tiff:photometric","unknown"); break; } } if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Geometry: %ux%u", (unsigned int) width,(unsigned int) height); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Interlace: %u", interlace); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Bits per sample: %u",bits_per_sample); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Min sample value: %u",min_sample_value); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Max sample value: %u",max_sample_value); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Photometric " "interpretation: %s",GetImageProperty(image,"tiff:photometric")); } image->columns=(size_t) width; image->rows=(size_t) height; image->depth=(size_t) bits_per_sample; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Image depth: %.20g", (double) image->depth); image->endian=MSBEndian; if (endian == FILLORDER_LSB2MSB) image->endian=LSBEndian; #if defined(MAGICKCORE_HAVE_TIFFISBIGENDIAN) if (TIFFIsBigEndian(tiff) == 0) { (void) SetImageProperty(image,"tiff:endian","lsb"); image->endian=LSBEndian; } else { (void) SetImageProperty(image,"tiff:endian","msb"); image->endian=MSBEndian; } #endif if ((photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) SetImageColorspace(image,GRAYColorspace); if (photometric == PHOTOMETRIC_SEPARATED) SetImageColorspace(image,CMYKColorspace); if (photometric == PHOTOMETRIC_CIELAB) SetImageColorspace(image,LabColorspace); TIFFGetProfiles(tiff,image,image_info->ping); TIFFGetProperties(tiff,image); option=GetImageOption(image_info,"tiff:exif-properties"); if ((option == (const char *) NULL) || (IsMagickTrue(option) != MagickFalse)) TIFFGetEXIFProperties(tiff,image); if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XRESOLUTION,&x_resolution) == 1) && (TIFFGetFieldDefaulted(tiff,TIFFTAG_YRESOLUTION,&y_resolution) == 1)) { image->x_resolution=x_resolution; image->y_resolution=y_resolution; } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_RESOLUTIONUNIT,&units) == 1) { if (units == RESUNIT_INCH) image->units=PixelsPerInchResolution; if (units == RESUNIT_CENTIMETER) image->units=PixelsPerCentimeterResolution; } if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XPOSITION,&x_position) == 1) && (TIFFGetFieldDefaulted(tiff,TIFFTAG_YPOSITION,&y_position) == 1)) { image->page.x=(ssize_t) ceil(x_position*image->x_resolution-0.5); image->page.y=(ssize_t) ceil(y_position*image->y_resolution-0.5); } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_ORIENTATION,&orientation) == 1) image->orientation=(OrientationType) orientation; if (TIFFGetField(tiff,TIFFTAG_WHITEPOINT,&chromaticity) == 1) { if (chromaticity != (float *) NULL) { image->chromaticity.white_point.x=chromaticity[0]; image->chromaticity.white_point.y=chromaticity[1]; } } if (TIFFGetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,&chromaticity) == 1) { if (chromaticity != (float *) NULL) { image->chromaticity.red_primary.x=chromaticity[0]; image->chromaticity.red_primary.y=chromaticity[1]; image->chromaticity.green_primary.x=chromaticity[2]; image->chromaticity.green_primary.y=chromaticity[3]; image->chromaticity.blue_primary.x=chromaticity[4]; image->chromaticity.blue_primary.y=chromaticity[5]; } } #if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919) if ((compress_tag != COMPRESSION_NONE) && (TIFFIsCODECConfigured(compress_tag) == 0)) { TIFFClose(tiff); ThrowReaderException(CoderError,"CompressNotSupported"); } #endif switch (compress_tag) { case COMPRESSION_NONE: image->compression=NoCompression; break; case COMPRESSION_CCITTFAX3: image->compression=FaxCompression; break; case COMPRESSION_CCITTFAX4: image->compression=Group4Compression; break; case COMPRESSION_JPEG: { image->compression=JPEGCompression; #if defined(JPEG_SUPPORT) { char sampling_factor[MaxTextExtent]; int tiff_status; uint16 horizontal, vertical; tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_YCBCRSUBSAMPLING, &horizontal,&vertical); if (tiff_status == 1) { (void) FormatLocaleString(sampling_factor,MaxTextExtent,"%dx%d", horizontal,vertical); (void) SetImageProperty(image,"jpeg:sampling-factor", sampling_factor); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Sampling Factors: %s",sampling_factor); } } #endif break; } case COMPRESSION_OJPEG: image->compression=JPEGCompression; break; #if defined(COMPRESSION_LZMA) case COMPRESSION_LZMA: image->compression=LZMACompression; break; #endif case COMPRESSION_LZW: image->compression=LZWCompression; break; case COMPRESSION_DEFLATE: image->compression=ZipCompression; break; case COMPRESSION_ADOBE_DEFLATE: image->compression=ZipCompression; break; default: image->compression=RLECompression; break; } /* Allocate memory for the image and pixel buffer. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } if (sample_format == SAMPLEFORMAT_UINT) status=SetQuantumFormat(image,quantum_info,UnsignedQuantumFormat); if (sample_format == SAMPLEFORMAT_INT) status=SetQuantumFormat(image,quantum_info,SignedQuantumFormat); if (sample_format == SAMPLEFORMAT_IEEEFP) status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) { TIFFClose(tiff); quantum_info=DestroyQuantumInfo(quantum_info); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } status=MagickTrue; switch (photometric) { case PHOTOMETRIC_MINISBLACK: { quantum_info->min_is_white=MagickFalse; break; } case PHOTOMETRIC_MINISWHITE: { quantum_info->min_is_white=MagickTrue; break; } default: break; } tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_EXTRASAMPLES,&extra_samples, &sample_info); if (tiff_status == 1) { (void) SetImageProperty(image,"tiff:alpha","unspecified"); if (extra_samples == 0) { if ((samples_per_pixel == 4) && (photometric == PHOTOMETRIC_RGB)) image->matte=MagickTrue; } else for (i=0; i < extra_samples; i++) { image->matte=MagickTrue; if (sample_info[i] == EXTRASAMPLE_ASSOCALPHA) { SetQuantumAlphaType(quantum_info,DisassociatedQuantumAlpha); (void) SetImageProperty(image,"tiff:alpha","associated"); } else if (sample_info[i] == EXTRASAMPLE_UNASSALPHA) (void) SetImageProperty(image,"tiff:alpha","unassociated"); } } if ((photometric == PHOTOMETRIC_PALETTE) && (pow(2.0,1.0*bits_per_sample) <= MaxColormapSize)) { size_t colors; colors=(size_t) GetQuantumRange(bits_per_sample)+1; if (AcquireImageColormap(image,colors) == MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_PAGENUMBER,&value,&pages) == 1) image->scene=value; if (image->storage_class == PseudoClass) { int tiff_status; size_t range; uint16 *blue_colormap, *green_colormap, *red_colormap; /* Initialize colormap. */ tiff_status=TIFFGetField(tiff,TIFFTAG_COLORMAP,&red_colormap, &green_colormap,&blue_colormap); if (tiff_status == 1) { if ((red_colormap != (uint16 *) NULL) && (green_colormap != (uint16 *) NULL) && (blue_colormap != (uint16 *) NULL)) { range=255; /* might be old style 8-bit colormap */ for (i=0; i < (ssize_t) image->colors; i++) if ((red_colormap[i] >= 256) || (green_colormap[i] >= 256) || (blue_colormap[i] >= 256)) { range=65535; break; } for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=ClampToQuantum(((double) QuantumRange*red_colormap[i])/range); image->colormap[i].green=ClampToQuantum(((double) QuantumRange*green_colormap[i])/range); image->colormap[i].blue=ClampToQuantum(((double) QuantumRange*blue_colormap[i])/range); } } } if (image->matte == MagickFalse) image->depth=GetImageDepth(image,exception); } if (image_info->ping != MagickFalse) { if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) { quantum_info=DestroyQuantumInfo(quantum_info); break; } goto next_tiff_frame; } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } method=ReadGenericMethod; if (TIFFGetField(tiff,TIFFTAG_ROWSPERSTRIP,&rows_per_strip) == 1) { char value[MaxTextExtent]; method=ReadStripMethod; (void) FormatLocaleString(value,MaxTextExtent,"%u",(unsigned int) rows_per_strip); (void) SetImageProperty(image,"tiff:rows-per-strip",value); } if ((samples_per_pixel >= 2) && (interlace == PLANARCONFIG_CONTIG)) method=ReadRGBAMethod; if ((samples_per_pixel >= 2) && (interlace == PLANARCONFIG_SEPARATE)) method=ReadCMYKAMethod; if ((photometric != PHOTOMETRIC_RGB) && (photometric != PHOTOMETRIC_CIELAB) && (photometric != PHOTOMETRIC_SEPARATED)) method=ReadGenericMethod; if (image->storage_class == PseudoClass) method=ReadSingleSampleMethod; if ((photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) method=ReadSingleSampleMethod; if ((photometric != PHOTOMETRIC_SEPARATED) && (interlace == PLANARCONFIG_SEPARATE) && (bits_per_sample < 64)) method=ReadGenericMethod; if (image->compression == JPEGCompression) method=GetJPEGMethod(image,tiff,photometric,bits_per_sample, samples_per_pixel); if (compress_tag == COMPRESSION_JBIG) method=ReadStripMethod; if (TIFFIsTiled(tiff) != MagickFalse) method=ReadTileMethod; quantum_info->endian=LSBEndian; quantum_type=RGBQuantum; pixels=GetQuantumPixels(quantum_info); switch (method) { case ReadSingleSampleMethod: { /* Convert TIFF image to PseudoClass MIFF image. */ quantum_type=IndexQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0); if (image->matte != MagickFalse) { if (image->storage_class != PseudoClass) { quantum_type=samples_per_pixel == 1 ? AlphaQuantum : GrayAlphaQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0); } else { quantum_type=IndexAlphaQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0); } } else if (image->storage_class != PseudoClass) { quantum_type=GrayQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0); } status=SetQuantumPad(image,quantum_info,pad*pow(2,ceil(log( bits_per_sample)/log(2)))); if (status == MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { int status; register PixelPacket *magick_restrict q; status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadRGBAMethod: { /* Convert TIFF image to DirectClass MIFF image. */ pad=(size_t) MagickMax((size_t) samples_per_pixel-3,0); quantum_type=RGBQuantum; if (image->matte != MagickFalse) { quantum_type=RGBAQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0); } if (image->colorspace == CMYKColorspace) { pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0); quantum_type=CMYKQuantum; if (image->matte != MagickFalse) { quantum_type=CMYKAQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-5,0); } } status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3)); if (status == MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { int status; register PixelPacket *magick_restrict q; status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadCMYKAMethod: { /* Convert TIFF image to DirectClass MIFF image. */ for (i=0; i < (ssize_t) samples_per_pixel; i++) { for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; int status; status=TIFFReadPixels(tiff,bits_per_sample,(tsample_t) i,y,(char *) pixels); if (status == -1) break; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; if (image->colorspace != CMYKColorspace) switch (i) { case 0: quantum_type=RedQuantum; break; case 1: quantum_type=GreenQuantum; break; case 2: quantum_type=BlueQuantum; break; case 3: quantum_type=AlphaQuantum; break; default: quantum_type=UndefinedQuantum; break; } else switch (i) { case 0: quantum_type=CyanQuantum; break; case 1: quantum_type=MagentaQuantum; break; case 2: quantum_type=YellowQuantum; break; case 3: quantum_type=BlackQuantum; break; case 4: quantum_type=AlphaQuantum; break; default: quantum_type=UndefinedQuantum; break; } (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadYCCKMethod: { pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { int status; register IndexPacket *indexes; register PixelPacket *magick_restrict q; register ssize_t x; unsigned char *p; status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); p=pixels; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelCyan(q,ScaleCharToQuantum(ClampYCC((double) *p+ (1.402*(double) *(p+2))-179.456))); SetPixelMagenta(q,ScaleCharToQuantum(ClampYCC((double) *p- (0.34414*(double) *(p+1))-(0.71414*(double ) *(p+2))+ 135.45984))); SetPixelYellow(q,ScaleCharToQuantum(ClampYCC((double) *p+ (1.772*(double) *(p+1))-226.816))); SetPixelBlack(indexes+x,ScaleCharToQuantum((unsigned char)*(p+3))); q++; p+=4; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadStripMethod: { register uint32 *p; /* Convert stripped TIFF image to DirectClass MIFF image. */ i=0; p=(uint32 *) NULL; for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register PixelPacket *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; if (i == 0) { if (TIFFReadRGBAStrip(tiff,(tstrip_t) y,(uint32 *) pixels) == 0) break; i=(ssize_t) MagickMin((ssize_t) rows_per_strip,(ssize_t) image->rows-y); } i--; p=((uint32 *) pixels)+image->columns*i; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) (TIFFGetR(*p)))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) (TIFFGetG(*p)))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) (TIFFGetB(*p)))); if (image->matte != MagickFalse) SetPixelOpacity(q,ScaleCharToQuantum((unsigned char) (TIFFGetA(*p)))); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadTileMethod: { register uint32 *p; uint32 *tile_pixels, columns, rows; /* Convert tiled TIFF image to DirectClass MIFF image. */ if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) != 1) || (TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) != 1)) { TIFFClose(tiff); ThrowReaderException(CoderError,"ImageIsNotTiled"); } (void) SetImageStorageClass(image,DirectClass); number_pixels=(MagickSizeType) columns*rows; if (HeapOverflowSanityCheck(rows,sizeof(*tile_pixels)) != MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } tile_pixels=(uint32 *) AcquireQuantumMemory(columns, rows*sizeof(*tile_pixels)); if (tile_pixels == (uint32 *) NULL) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } for (y=0; y < (ssize_t) image->rows; y+=rows) { PixelPacket *tile; register ssize_t x; register PixelPacket *magick_restrict q; size_t columns_remaining, rows_remaining; rows_remaining=image->rows-y; if ((ssize_t) (y+rows) < (ssize_t) image->rows) rows_remaining=rows; tile=QueueAuthenticPixels(image,0,y,image->columns,rows_remaining, exception); if (tile == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x+=columns) { size_t column, row; if (TIFFReadRGBATile(tiff,(uint32) x,(uint32) y,tile_pixels) == 0) break; columns_remaining=image->columns-x; if ((ssize_t) (x+columns) < (ssize_t) image->columns) columns_remaining=columns; p=tile_pixels+(rows-rows_remaining)*columns; q=tile+(image->columns*(rows_remaining-1)+x); for (row=rows_remaining; row > 0; row--) { if (image->matte != MagickFalse) for (column=columns_remaining; column > 0; column--) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) TIFFGetR(*p))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) TIFFGetG(*p))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) TIFFGetB(*p))); SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) TIFFGetA(*p))); q++; p++; } else for (column=columns_remaining; column > 0; column--) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) TIFFGetR(*p))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) TIFFGetG(*p))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) TIFFGetB(*p))); q++; p++; } p+=columns-columns_remaining; q-=(image->columns+columns_remaining); } } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } tile_pixels=(uint32 *) RelinquishMagickMemory(tile_pixels); break; } case ReadGenericMethod: default: { MemoryInfo *pixel_info; register uint32 *p; uint32 *pixels; /* Convert TIFF image to DirectClass MIFF image. */ number_pixels=(MagickSizeType) image->columns*image->rows; if (HeapOverflowSanityCheck(image->rows,sizeof(*pixels)) != MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixel_info=AcquireVirtualMemory(image->columns,image->rows* sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=(uint32 *) GetVirtualMemoryBlob(pixel_info); (void) TIFFReadRGBAImage(tiff,(uint32) image->columns,(uint32) image->rows,(uint32 *) pixels,0); /* Convert image to DirectClass pixel packets. */ p=pixels+number_pixels-1; for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register PixelPacket *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; q+=image->columns-1; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) TIFFGetR(*p))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) TIFFGetG(*p))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) TIFFGetB(*p))); if (image->matte != MagickFalse) SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) TIFFGetA(*p))); p--; q--; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } pixel_info=RelinquishVirtualMemory(pixel_info); break; } } SetQuantumImageType(image,quantum_type); next_tiff_frame: quantum_info=DestroyQuantumInfo(quantum_info); if (photometric == PHOTOMETRIC_CIELAB) DecodeLabImage(image,exception); if ((photometric == PHOTOMETRIC_LOGL) || (photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) { image->type=GrayscaleType; if (bits_per_sample == 1) image->type=BilevelType; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse; if (status != MagickFalse) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,image->scene-1, image->scene); if (status == MagickFalse) break; } } while (status != MagickFalse); TIFFClose(tiff); TIFFReadPhotoshopLayers(image,image_info,exception); if (image_info->number_scenes != 0) { if (image_info->scene >= GetImageListLength(image)) { /* Subimage was not found in the Photoshop layer */ image = DestroyImageList(image); return((Image *)NULL); } } return(GetFirstImageInList(image)); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r T I F F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterTIFFImage() adds properties for the TIFF image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterTIFFImage method is: % % size_t RegisterTIFFImage(void) % */ #if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER) static TIFFExtendProc tag_extender = (TIFFExtendProc) NULL; static void TIFFIgnoreTags(TIFF *tiff) { char *q; const char *p, *tags; Image *image; register ssize_t i; size_t count; TIFFFieldInfo *ignore; if (TIFFGetReadProc(tiff) != TIFFReadBlob) return; image=(Image *)TIFFClientdata(tiff); tags=GetImageArtifact(image,"tiff:ignore-tags"); if (tags == (const char *) NULL) return; count=0; p=tags; while (*p != '\0') { while ((isspace((int) ((unsigned char) *p)) != 0)) p++; (void) strtol(p,&q,10); if (p == q) return; p=q; count++; while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) p++; } if (count == 0) return; i=0; p=tags; ignore=(TIFFFieldInfo *) AcquireQuantumMemory(count,sizeof(*ignore)); /* This also sets field_bit to 0 (FIELD_IGNORE) */ ResetMagickMemory(ignore,0,count*sizeof(*ignore)); while (*p != '\0') { while ((isspace((int) ((unsigned char) *p)) != 0)) p++; ignore[i].field_tag=(ttag_t) strtol(p,&q,10); p=q; i++; while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) p++; } (void) TIFFMergeFieldInfo(tiff,ignore,(uint32) count); ignore=(TIFFFieldInfo *) RelinquishMagickMemory(ignore); } static void TIFFTagExtender(TIFF *tiff) { static const TIFFFieldInfo TIFFExtensions[] = { { 37724, -3, -3, TIFF_UNDEFINED, FIELD_CUSTOM, 1, 1, (char *) "PhotoshopLayerData" }, { 34118, -3, -3, TIFF_UNDEFINED, FIELD_CUSTOM, 1, 1, (char *) "Microscope" } }; TIFFMergeFieldInfo(tiff,TIFFExtensions,sizeof(TIFFExtensions)/ sizeof(*TIFFExtensions)); if (tag_extender != (TIFFExtendProc) NULL) (*tag_extender)(tiff); TIFFIgnoreTags(tiff); } #endif ModuleExport size_t RegisterTIFFImage(void) { #define TIFFDescription "Tagged Image File Format" char version[MaxTextExtent]; MagickInfo *entry; if (tiff_semaphore == (SemaphoreInfo *) NULL) ActivateSemaphoreInfo(&tiff_semaphore); LockSemaphoreInfo(tiff_semaphore); if (instantiate_key == MagickFalse) { if (CreateMagickThreadKey(&tiff_exception,NULL) == MagickFalse) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); error_handler=TIFFSetErrorHandler(TIFFErrors); warning_handler=TIFFSetWarningHandler(TIFFWarnings); #if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER) if (tag_extender == (TIFFExtendProc) NULL) tag_extender=TIFFSetTagExtender(TIFFTagExtender); #endif instantiate_key=MagickTrue; } UnlockSemaphoreInfo(tiff_semaphore); *version='\0'; #if defined(TIFF_VERSION) (void) FormatLocaleString(version,MaxTextExtent,"%d",TIFF_VERSION); #endif #if defined(MAGICKCORE_TIFF_DELEGATE) { const char *p; register ssize_t i; p=TIFFGetVersion(); for (i=0; (i < (MaxTextExtent-1)) && (*p != 0) && (*p != '\n'); i++) version[i]=(*p++); version[i]='\0'; } #endif entry=SetMagickInfo("GROUP4"); #if defined(MAGICKCORE_TIFF_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadGROUP4Image; entry->encoder=(EncodeImageHandler *) WriteGROUP4Image; #endif entry->raw=MagickTrue; entry->endian_support=MagickTrue; entry->adjoin=MagickFalse; entry->format_type=ImplicitFormatType; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Raw CCITT Group4"); entry->mime_type=ConstantString("image/tiff"); entry->module=ConstantString("TIFF"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PTIF"); #if defined(MAGICKCORE_TIFF_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadTIFFImage; entry->encoder=(EncodeImageHandler *) WritePTIFImage; #endif entry->endian_support=MagickTrue; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Pyramid encoded TIFF"); entry->mime_type=ConstantString("image/tiff"); entry->module=ConstantString("TIFF"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("TIF"); #if defined(MAGICKCORE_TIFF_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadTIFFImage; entry->encoder=(EncodeImageHandler *) WriteTIFFImage; #endif entry->endian_support=MagickTrue; entry->seekable_stream=MagickTrue; entry->stealth=MagickTrue; entry->description=ConstantString(TIFFDescription); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/tiff"); entry->module=ConstantString("TIFF"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("TIFF"); #if defined(MAGICKCORE_TIFF_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadTIFFImage; entry->encoder=(EncodeImageHandler *) WriteTIFFImage; #endif entry->magick=(IsImageFormatHandler *) IsTIFF; entry->endian_support=MagickTrue; entry->seekable_stream=MagickTrue; entry->description=ConstantString(TIFFDescription); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/tiff"); entry->module=ConstantString("TIFF"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("TIFF64"); #if defined(TIFF_VERSION_BIG) entry->decoder=(DecodeImageHandler *) ReadTIFFImage; entry->encoder=(EncodeImageHandler *) WriteTIFFImage; #endif entry->adjoin=MagickFalse; entry->endian_support=MagickTrue; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Tagged Image File Format (64-bit)"); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/tiff"); entry->module=ConstantString("TIFF"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r T I F F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterTIFFImage() removes format registrations made by the TIFF module % from the list of supported formats. % % The format of the UnregisterTIFFImage method is: % % UnregisterTIFFImage(void) % */ ModuleExport void UnregisterTIFFImage(void) { (void) UnregisterMagickInfo("TIFF64"); (void) UnregisterMagickInfo("TIFF"); (void) UnregisterMagickInfo("TIF"); (void) UnregisterMagickInfo("PTIF"); if (tiff_semaphore == (SemaphoreInfo *) NULL) ActivateSemaphoreInfo(&tiff_semaphore); LockSemaphoreInfo(tiff_semaphore); if (instantiate_key != MagickFalse) { if (DeleteMagickThreadKey(tiff_exception) == MagickFalse) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); #if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER) if (tag_extender == (TIFFExtendProc) NULL) (void) TIFFSetTagExtender(tag_extender); #endif (void) TIFFSetWarningHandler(warning_handler); (void) TIFFSetErrorHandler(error_handler); instantiate_key=MagickFalse; } UnlockSemaphoreInfo(tiff_semaphore); DestroySemaphoreInfo(&tiff_semaphore); } #if defined(MAGICKCORE_TIFF_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e G R O U P 4 I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteGROUP4Image() writes an image in the raw CCITT Group 4 image format. % % The format of the WriteGROUP4Image method is: % % MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info, % Image *image) % % A description of each parameter follows: % % o image_info: the image info. % % o image: The image. % */ static MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info, Image *image) { char filename[MaxTextExtent]; FILE *file; Image *huffman_image; ImageInfo *write_info; int unique_file; MagickBooleanType status; register ssize_t i; ssize_t count; TIFF *tiff; toff_t *byte_count, strip_size; unsigned char *buffer; /* Write image as CCITT Group4 TIFF image to a temporary file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == 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); huffman_image=CloneImage(image,0,0,MagickTrue,&image->exception); if (huffman_image == (Image *) NULL) { (void) CloseBlob(image); return(MagickFalse); } huffman_image->endian=MSBEndian; file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); if (unique_file != -1) file=fdopen(unique_file,"wb"); if ((unique_file == -1) || (file == (FILE *) NULL)) { ThrowFileException(&image->exception,FileOpenError, "UnableToCreateTemporaryFile",filename); return(MagickFalse); } (void) FormatLocaleString(huffman_image->filename,MaxTextExtent,"tiff:%s", filename); (void) SetImageType(huffman_image,BilevelType); write_info=CloneImageInfo((ImageInfo *) NULL); SetImageInfoFile(write_info,file); (void) SetImageType(image,BilevelType); (void) SetImageDepth(image,1); write_info->compression=Group4Compression; write_info->type=BilevelType; (void) SetImageOption(write_info,"quantum:polarity","min-is-white"); status=WriteTIFFImage(write_info,huffman_image); (void) fflush(file); write_info=DestroyImageInfo(write_info); if (status == MagickFalse) { InheritException(&image->exception,&huffman_image->exception); huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); return(MagickFalse); } tiff=TIFFOpen(filename,"rb"); if (tiff == (TIFF *) NULL) { huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); ThrowFileException(&image->exception,FileOpenError,"UnableToOpenFile", image_info->filename); return(MagickFalse); } /* Allocate raw strip buffer. */ if (TIFFGetField(tiff,TIFFTAG_STRIPBYTECOUNTS,&byte_count) != 1) { TIFFClose(tiff); huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); return(MagickFalse); } strip_size=byte_count[0]; for (i=1; i < (ssize_t) TIFFNumberOfStrips(tiff); i++) if (byte_count[i] > strip_size) strip_size=byte_count[i]; buffer=(unsigned char *) AcquireQuantumMemory((size_t) strip_size, sizeof(*buffer)); if (buffer == (unsigned char *) NULL) { TIFFClose(tiff); huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image_info->filename); } /* Compress runlength encoded to 2D Huffman pixels. */ for (i=0; i < (ssize_t) TIFFNumberOfStrips(tiff); i++) { count=(ssize_t) TIFFReadRawStrip(tiff,(uint32) i,buffer,strip_size); if (WriteBlob(image,(size_t) count,buffer) != count) status=MagickFalse; } buffer=(unsigned char *) RelinquishMagickMemory(buffer); TIFFClose(tiff); huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); (void) CloseBlob(image); return(status); } #endif #if defined(MAGICKCORE_TIFF_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P T I F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePTIFImage() writes an image in the pyrimid-encoded Tagged image file % format. % % The format of the WritePTIFImage method is: % % MagickBooleanType WritePTIFImage(const ImageInfo *image_info, % Image *image) % % A description of each parameter follows: % % o image_info: the image info. % % o image: The image. % */ static MagickBooleanType WritePTIFImage(const ImageInfo *image_info, Image *image) { ExceptionInfo *exception; Image *images, *next, *pyramid_image; ImageInfo *write_info; MagickBooleanType status; PointInfo resolution; size_t columns, rows; /* Create pyramid-encoded TIFF image. */ exception=(&image->exception); images=NewImageList(); for (next=image; next != (Image *) NULL; next=GetNextImageInList(next)) { Image *clone_image; clone_image=CloneImage(next,0,0,MagickFalse,exception); if (clone_image == (Image *) NULL) break; clone_image->previous=NewImageList(); clone_image->next=NewImageList(); (void) SetImageProperty(clone_image,"tiff:subfiletype","none"); AppendImageToList(&images,clone_image); columns=next->columns; rows=next->rows; resolution.x=next->x_resolution; resolution.y=next->y_resolution; while ((columns > 64) && (rows > 64)) { columns/=2; rows/=2; resolution.x/=2.0; resolution.y/=2.0; pyramid_image=ResizeImage(next,columns,rows,image->filter,image->blur, exception); if (pyramid_image == (Image *) NULL) break; pyramid_image->x_resolution=resolution.x; pyramid_image->y_resolution=resolution.y; (void) SetImageProperty(pyramid_image,"tiff:subfiletype","REDUCEDIMAGE"); AppendImageToList(&images,pyramid_image); } } /* Write pyramid-encoded TIFF image. */ write_info=CloneImageInfo(image_info); write_info->adjoin=MagickTrue; status=WriteTIFFImage(write_info,GetFirstImageInList(images)); images=DestroyImageList(images); write_info=DestroyImageInfo(write_info); return(status); } #endif #if defined(MAGICKCORE_TIFF_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % W r i t e T I F F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteTIFFImage() writes an image in the Tagged image file format. % % The format of the WriteTIFFImage method is: % % MagickBooleanType WriteTIFFImage(const ImageInfo *image_info, % Image *image) % % A description of each parameter follows: % % o image_info: the image info. % % o image: The image. % */ typedef struct _TIFFInfo { RectangleInfo tile_geometry; unsigned char *scanline, *scanlines, *pixels; } TIFFInfo; static void DestroyTIFFInfo(TIFFInfo *tiff_info) { assert(tiff_info != (TIFFInfo *) NULL); if (tiff_info->scanlines != (unsigned char *) NULL) tiff_info->scanlines=(unsigned char *) RelinquishMagickMemory( tiff_info->scanlines); if (tiff_info->pixels != (unsigned char *) NULL) tiff_info->pixels=(unsigned char *) RelinquishMagickMemory( tiff_info->pixels); } static MagickBooleanType EncodeLabImage(Image *image,ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; ssize_t y; status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double a, b; a=QuantumScale*GetPixela(q)-0.5; if (a < 0.0) a+=1.0; b=QuantumScale*GetPixelb(q)-0.5; if (b < 0.0) b+=1.0; SetPixela(q,QuantumRange*a); SetPixelb(q,QuantumRange*b); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status); } static MagickBooleanType GetTIFFInfo(const ImageInfo *image_info,TIFF *tiff, TIFFInfo *tiff_info) { const char *option; MagickStatusType flags; uint32 tile_columns, tile_rows; assert(tiff_info != (TIFFInfo *) NULL); (void) ResetMagickMemory(tiff_info,0,sizeof(*tiff_info)); option=GetImageOption(image_info,"tiff:tile-geometry"); if (option == (const char *) NULL) return(MagickTrue); flags=ParseAbsoluteGeometry(option,&tiff_info->tile_geometry); if ((flags & HeightValue) == 0) tiff_info->tile_geometry.height=tiff_info->tile_geometry.width; tile_columns=(uint32) tiff_info->tile_geometry.width; tile_rows=(uint32) tiff_info->tile_geometry.height; TIFFDefaultTileSize(tiff,&tile_columns,&tile_rows); (void) TIFFSetField(tiff,TIFFTAG_TILEWIDTH,tile_columns); (void) TIFFSetField(tiff,TIFFTAG_TILELENGTH,tile_rows); tiff_info->tile_geometry.width=tile_columns; tiff_info->tile_geometry.height=tile_rows; tiff_info->scanlines=(unsigned char *) AcquireQuantumMemory((size_t) tile_rows*TIFFScanlineSize(tiff),sizeof(*tiff_info->scanlines)); tiff_info->pixels=(unsigned char *) AcquireQuantumMemory((size_t) tile_rows*TIFFTileSize(tiff),sizeof(*tiff_info->scanlines)); if ((tiff_info->scanlines == (unsigned char *) NULL) || (tiff_info->pixels == (unsigned char *) NULL)) { DestroyTIFFInfo(tiff_info); return(MagickFalse); } return(MagickTrue); } static int32 TIFFWritePixels(TIFF *tiff,TIFFInfo *tiff_info,ssize_t row, tsample_t sample,Image *image) { int32 status; register ssize_t i; register unsigned char *p, *q; size_t number_tiles, tile_width; ssize_t bytes_per_pixel, j, k, l; if (TIFFIsTiled(tiff) == 0) return(TIFFWriteScanline(tiff,tiff_info->scanline,(uint32) row,sample)); /* Fill scanlines to tile height. */ i=(ssize_t) (row % tiff_info->tile_geometry.height)*TIFFScanlineSize(tiff); (void) CopyMagickMemory(tiff_info->scanlines+i,(char *) tiff_info->scanline, (size_t) TIFFScanlineSize(tiff)); if (((size_t) (row % tiff_info->tile_geometry.height) != (tiff_info->tile_geometry.height-1)) && (row != (ssize_t) (image->rows-1))) return(0); /* Write tile to TIFF image. */ status=0; bytes_per_pixel=TIFFTileSize(tiff)/(ssize_t) (tiff_info->tile_geometry.height* tiff_info->tile_geometry.width); number_tiles=(image->columns+tiff_info->tile_geometry.width)/ tiff_info->tile_geometry.width; for (i=0; i < (ssize_t) number_tiles; i++) { tile_width=(i == (ssize_t) (number_tiles-1)) ? image->columns-(i* tiff_info->tile_geometry.width) : tiff_info->tile_geometry.width; for (j=0; j < (ssize_t) ((row % tiff_info->tile_geometry.height)+1); j++) for (k=0; k < (ssize_t) tile_width; k++) { if (bytes_per_pixel == 0) { p=tiff_info->scanlines+(j*TIFFScanlineSize(tiff)+(i* tiff_info->tile_geometry.width+k)/8); q=tiff_info->pixels+(j*TIFFTileRowSize(tiff)+k/8); *q++=(*p++); continue; } p=tiff_info->scanlines+(j*TIFFScanlineSize(tiff)+(i* tiff_info->tile_geometry.width+k)*bytes_per_pixel); q=tiff_info->pixels+(j*TIFFTileRowSize(tiff)+k*bytes_per_pixel); for (l=0; l < bytes_per_pixel; l++) *q++=(*p++); } if ((i*tiff_info->tile_geometry.width) != image->columns) status=TIFFWriteTile(tiff,tiff_info->pixels,(uint32) (i* tiff_info->tile_geometry.width),(uint32) ((row/ tiff_info->tile_geometry.height)*tiff_info->tile_geometry.height),0, sample); if (status < 0) break; } return(status); } static void TIFFSetProfiles(TIFF *tiff,Image *image) { const char *name; const StringInfo *profile; if (image->profiles == (void *) NULL) return; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (GetStringInfoLength(profile) == 0) { name=GetNextImageProfile(image); continue; } #if defined(TIFFTAG_XMLPACKET) if (LocaleCompare(name,"xmp") == 0) (void) TIFFSetField(tiff,TIFFTAG_XMLPACKET,(uint32) GetStringInfoLength( profile),GetStringInfoDatum(profile)); #endif #if defined(TIFFTAG_ICCPROFILE) if (LocaleCompare(name,"icc") == 0) (void) TIFFSetField(tiff,TIFFTAG_ICCPROFILE,(uint32) GetStringInfoLength( profile),GetStringInfoDatum(profile)); #endif if (LocaleCompare(name,"iptc") == 0) { size_t length; StringInfo *iptc_profile; iptc_profile=CloneStringInfo(profile); length=GetStringInfoLength(profile)+4-(GetStringInfoLength(profile) & 0x03); SetStringInfoLength(iptc_profile,length); if (TIFFIsByteSwapped(tiff)) TIFFSwabArrayOfLong((uint32 *) GetStringInfoDatum(iptc_profile), (unsigned long) (length/4)); (void) TIFFSetField(tiff,TIFFTAG_RICHTIFFIPTC,(uint32) GetStringInfoLength(iptc_profile)/4,GetStringInfoDatum(iptc_profile)); iptc_profile=DestroyStringInfo(iptc_profile); } #if defined(TIFFTAG_PHOTOSHOP) if (LocaleCompare(name,"8bim") == 0) (void) TIFFSetField(tiff,TIFFTAG_PHOTOSHOP,(uint32) GetStringInfoLength(profile),GetStringInfoDatum(profile)); #endif if (LocaleCompare(name,"tiff:37724") == 0) (void) TIFFSetField(tiff,37724,(uint32) GetStringInfoLength(profile), GetStringInfoDatum(profile)); if (LocaleCompare(name,"tiff:34118") == 0) (void) TIFFSetField(tiff,34118,(uint32) GetStringInfoLength(profile), GetStringInfoDatum(profile)); name=GetNextImageProfile(image); } } static void TIFFSetProperties(TIFF *tiff,const ImageInfo *image_info, Image *image) { const char *value; value=GetImageArtifact(image,"tiff:document"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_DOCUMENTNAME,value); value=GetImageArtifact(image,"tiff:hostcomputer"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_HOSTCOMPUTER,value); value=GetImageArtifact(image,"tiff:artist"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_ARTIST,value); value=GetImageArtifact(image,"tiff:timestamp"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_DATETIME,value); value=GetImageArtifact(image,"tiff:make"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_MAKE,value); value=GetImageArtifact(image,"tiff:model"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_MODEL,value); value=GetImageArtifact(image,"tiff:software"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_SOFTWARE,value); value=GetImageArtifact(image,"tiff:copyright"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_COPYRIGHT,value); value=GetImageArtifact(image,"kodak-33423"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,33423,value); value=GetImageArtifact(image,"kodak-36867"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,36867,value); value=GetImageProperty(image,"label"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_PAGENAME,value); value=GetImageProperty(image,"comment"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_IMAGEDESCRIPTION,value); value=GetImageArtifact(image,"tiff:subfiletype"); if (value != (const char *) NULL) { if (LocaleCompare(value,"REDUCEDIMAGE") == 0) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE); else if (LocaleCompare(value,"PAGE") == 0) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE); else if (LocaleCompare(value,"MASK") == 0) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_MASK); } else { uint16 page, pages; page=(uint16) image->scene; pages=(uint16) GetImageListLength(image); if ((image_info->adjoin != MagickFalse) && (pages > 1)) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE); (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages); } } static void TIFFSetEXIFProperties(TIFF *tiff,Image *image) { #if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY) const char *value; register ssize_t i; uint32 offset; /* Write EXIF properties. */ offset=0; (void) TIFFSetField(tiff,TIFFTAG_SUBIFD,1,&offset); for (i=0; exif_info[i].tag != 0; i++) { value=GetImageProperty(image,exif_info[i].property); if (value == (const char *) NULL) continue; switch (exif_info[i].type) { case TIFF_ASCII: { (void) TIFFSetField(tiff,exif_info[i].tag,value); break; } case TIFF_SHORT: { uint16 field; field=(uint16) StringToLong(value); (void) TIFFSetField(tiff,exif_info[i].tag,field); break; } case TIFF_LONG: { uint16 field; field=(uint16) StringToLong(value); (void) TIFFSetField(tiff,exif_info[i].tag,field); break; } case TIFF_RATIONAL: case TIFF_SRATIONAL: { float field; field=StringToDouble(value,(char **) NULL); (void) TIFFSetField(tiff,exif_info[i].tag,field); break; } default: break; } } /* (void) TIFFSetField(tiff,TIFFTAG_EXIFIFD,offset); */ #else (void) tiff; (void) image; #endif } static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info, Image *image) { #if !defined(TIFFDefaultStripSize) #define TIFFDefaultStripSize(tiff,request) (8192UL/TIFFScanlineSize(tiff)) #endif const char *mode, *option; CompressionType compression; EndianType endian_type; MagickBooleanType debug, status; MagickOffsetType scene; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; ssize_t y; TIFF *tiff; TIFFInfo tiff_info; uint16 bits_per_sample, compress_tag, endian, photometric; uint32 rows_per_strip; unsigned char *pixels; /* Open TIFF file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); (void) SetMagickThreadValue(tiff_exception,&image->exception); endian_type=UndefinedEndian; option=GetImageOption(image_info,"tiff:endian"); if (option != (const char *) NULL) { if (LocaleNCompare(option,"msb",3) == 0) endian_type=MSBEndian; if (LocaleNCompare(option,"lsb",3) == 0) endian_type=LSBEndian;; } switch (endian_type) { case LSBEndian: mode="wl"; break; case MSBEndian: mode="wb"; break; default: mode="w"; break; } #if defined(TIFF_VERSION_BIG) if (LocaleCompare(image_info->magick,"TIFF64") == 0) switch (endian_type) { case LSBEndian: mode="wl8"; break; case MSBEndian: mode="wb8"; break; default: mode="w8"; break; } #endif tiff=TIFFClientOpen(image->filename,mode,(thandle_t) image,TIFFReadBlob, TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob, TIFFUnmapBlob); if (tiff == (TIFF *) NULL) return(MagickFalse); scene=0; debug=IsEventLogging(); (void) debug; do { /* Initialize TIFF fields. */ if ((image_info->type != UndefinedType) && (image_info->type != OptimizeType)) (void) SetImageType(image,image_info->type); compression=UndefinedCompression; if (image->compression != JPEGCompression) compression=image->compression; if (image_info->compression != UndefinedCompression) compression=image_info->compression; switch (compression) { case FaxCompression: case Group4Compression: { (void) SetImageType(image,BilevelType); (void) SetImageDepth(image,1); break; } case JPEGCompression: { (void) SetImageStorageClass(image,DirectClass); (void) SetImageDepth(image,8); break; } default: break; } quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if ((image->storage_class != PseudoClass) && (image->depth >= 32) && (quantum_info->format == UndefinedQuantumFormat) && (IsHighDynamicRangeImage(image,&image->exception) != MagickFalse)) { status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } if ((LocaleCompare(image_info->magick,"PTIF") == 0) && (GetPreviousImageInList(image) != (Image *) NULL)) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE); if ((image->columns != (uint32) image->columns) || (image->rows != (uint32) image->rows)) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); (void) TIFFSetField(tiff,TIFFTAG_IMAGELENGTH,(uint32) image->rows); (void) TIFFSetField(tiff,TIFFTAG_IMAGEWIDTH,(uint32) image->columns); switch (compression) { case FaxCompression: { compress_tag=COMPRESSION_CCITTFAX3; SetQuantumMinIsWhite(quantum_info,MagickTrue); break; } case Group4Compression: { compress_tag=COMPRESSION_CCITTFAX4; SetQuantumMinIsWhite(quantum_info,MagickTrue); break; } #if defined(COMPRESSION_JBIG) case JBIG1Compression: { compress_tag=COMPRESSION_JBIG; break; } #endif case JPEGCompression: { compress_tag=COMPRESSION_JPEG; break; } #if defined(COMPRESSION_LZMA) case LZMACompression: { compress_tag=COMPRESSION_LZMA; break; } #endif case LZWCompression: { compress_tag=COMPRESSION_LZW; break; } case RLECompression: { compress_tag=COMPRESSION_PACKBITS; break; } case ZipCompression: { compress_tag=COMPRESSION_ADOBE_DEFLATE; break; } case NoCompression: default: { compress_tag=COMPRESSION_NONE; break; } } #if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919) if ((compress_tag != COMPRESSION_NONE) && (TIFFIsCODECConfigured(compress_tag) == 0)) { (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"CompressionNotSupported","`%s'",CommandOptionToMnemonic( MagickCompressOptions,(ssize_t) compression)); compress_tag=COMPRESSION_NONE; } #else switch (compress_tag) { #if defined(CCITT_SUPPORT) case COMPRESSION_CCITTFAX3: case COMPRESSION_CCITTFAX4: #endif #if defined(YCBCR_SUPPORT) && defined(JPEG_SUPPORT) case COMPRESSION_JPEG: #endif #if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA) case COMPRESSION_LZMA: #endif #if defined(LZW_SUPPORT) case COMPRESSION_LZW: #endif #if defined(PACKBITS_SUPPORT) case COMPRESSION_PACKBITS: #endif #if defined(ZIP_SUPPORT) case COMPRESSION_ADOBE_DEFLATE: #endif case COMPRESSION_NONE: break; default: { (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"CompressionNotSupported","`%s'",CommandOptionToMnemonic( MagickCompressOptions,(ssize_t) compression)); compress_tag=COMPRESSION_NONE; break; } } #endif if (image->colorspace == CMYKColorspace) { photometric=PHOTOMETRIC_SEPARATED; (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,4); (void) TIFFSetField(tiff,TIFFTAG_INKSET,INKSET_CMYK); } else { /* Full color TIFF raster. */ if (image->colorspace == LabColorspace) { photometric=PHOTOMETRIC_CIELAB; EncodeLabImage(image,&image->exception); } else if (image->colorspace == YCbCrColorspace) { photometric=PHOTOMETRIC_YCBCR; (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,1,1); (void) SetImageStorageClass(image,DirectClass); (void) SetImageDepth(image,8); } else photometric=PHOTOMETRIC_RGB; (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,3); if ((image_info->type != TrueColorType) && (image_info->type != TrueColorMatteType)) { if ((image_info->type != PaletteType) && (SetImageGray(image,&image->exception) != MagickFalse)) { photometric=(uint16) (quantum_info->min_is_white != MagickFalse ? PHOTOMETRIC_MINISWHITE : PHOTOMETRIC_MINISBLACK); (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1); if ((image->depth == 1) && (image->matte == MagickFalse)) SetImageMonochrome(image,&image->exception); } else if (image->storage_class == PseudoClass) { size_t depth; /* Colormapped TIFF raster. */ (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1); photometric=PHOTOMETRIC_PALETTE; depth=1; while ((GetQuantumRange(depth)+1) < image->colors) depth<<=1; status=SetQuantumDepth(image,quantum_info,depth); if (status == MagickFalse) ThrowWriterException(ResourceLimitError, "MemoryAllocationFailed"); } } } (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian); if ((compress_tag == COMPRESSION_CCITTFAX3) && (photometric != PHOTOMETRIC_MINISWHITE)) { compress_tag=COMPRESSION_NONE; endian=FILLORDER_MSB2LSB; } else if ((compress_tag == COMPRESSION_CCITTFAX4) && (photometric != PHOTOMETRIC_MINISWHITE)) { compress_tag=COMPRESSION_NONE; endian=FILLORDER_MSB2LSB; } option=GetImageOption(image_info,"tiff:fill-order"); if (option != (const char *) NULL) { if (LocaleNCompare(option,"msb",3) == 0) endian=FILLORDER_MSB2LSB; if (LocaleNCompare(option,"lsb",3) == 0) endian=FILLORDER_LSB2MSB; } (void) TIFFSetField(tiff,TIFFTAG_COMPRESSION,compress_tag); (void) TIFFSetField(tiff,TIFFTAG_FILLORDER,endian); (void) TIFFSetField(tiff,TIFFTAG_BITSPERSAMPLE,quantum_info->depth); if (image->matte != MagickFalse) { uint16 extra_samples, sample_info[1], samples_per_pixel; /* TIFF has a matte channel. */ extra_samples=1; sample_info[0]=EXTRASAMPLE_UNASSALPHA; option=GetImageOption(image_info,"tiff:alpha"); if (option != (const char *) NULL) { if (LocaleCompare(option,"associated") == 0) sample_info[0]=EXTRASAMPLE_ASSOCALPHA; else if (LocaleCompare(option,"unspecified") == 0) sample_info[0]=EXTRASAMPLE_UNSPECIFIED; } (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL, &samples_per_pixel); (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,samples_per_pixel+1); (void) TIFFSetField(tiff,TIFFTAG_EXTRASAMPLES,extra_samples, &sample_info); if (sample_info[0] == EXTRASAMPLE_ASSOCALPHA) SetQuantumAlphaType(quantum_info,AssociatedQuantumAlpha); } (void) TIFFSetField(tiff,TIFFTAG_PHOTOMETRIC,photometric); switch (quantum_info->format) { case FloatingPointQuantumFormat: { (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_IEEEFP); (void) TIFFSetField(tiff,TIFFTAG_SMINSAMPLEVALUE,quantum_info->minimum); (void) TIFFSetField(tiff,TIFFTAG_SMAXSAMPLEVALUE,quantum_info->maximum); break; } case SignedQuantumFormat: { (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_INT); break; } case UnsignedQuantumFormat: { (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_UINT); break; } default: break; } (void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,ORIENTATION_TOPLEFT); (void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_CONTIG); if (photometric == PHOTOMETRIC_RGB) if ((image_info->interlace == PlaneInterlace) || (image_info->interlace == PartitionInterlace)) (void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_SEPARATE); rows_per_strip=TIFFDefaultStripSize(tiff,0); option=GetImageOption(image_info,"tiff:rows-per-strip"); if (option != (const char *) NULL) rows_per_strip=(size_t) strtol(option,(char **) NULL,10); switch (compress_tag) { case COMPRESSION_JPEG: { #if defined(JPEG_SUPPORT) const char *sampling_factor; GeometryInfo geometry_info; MagickStatusType flags; rows_per_strip+=(16-(rows_per_strip % 16)); if (image_info->quality != UndefinedCompressionQuality) (void) TIFFSetField(tiff,TIFFTAG_JPEGQUALITY,image_info->quality); (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RAW); if (IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) { const char *value; (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RGB); sampling_factor=(const char *) NULL; value=GetImageProperty(image,"jpeg:sampling-factor"); if (value != (char *) NULL) { sampling_factor=value; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Input sampling-factors=%s",sampling_factor); } if (image_info->sampling_factor != (char *) NULL) sampling_factor=image_info->sampling_factor; if (sampling_factor != (const char *) NULL) { flags=ParseGeometry(sampling_factor,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=geometry_info.rho; if (image->colorspace == YCbCrColorspace) (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,(uint16) geometry_info.rho,(uint16) geometry_info.sigma); } } (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (bits_per_sample == 12) (void) TIFFSetField(tiff,TIFFTAG_JPEGTABLESMODE,JPEGTABLESMODE_QUANT); #endif break; } case COMPRESSION_ADOBE_DEFLATE: { rows_per_strip=(uint32) image->rows; (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL); (void) TIFFSetField(tiff,TIFFTAG_ZIPQUALITY,(long) ( image_info->quality == UndefinedCompressionQuality ? 7 : MagickMin((ssize_t) image_info->quality/10,9))); break; } case COMPRESSION_CCITTFAX3: { /* Byte-aligned EOL. */ rows_per_strip=(uint32) image->rows; (void) TIFFSetField(tiff,TIFFTAG_GROUP3OPTIONS,4); break; } case COMPRESSION_CCITTFAX4: { rows_per_strip=(uint32) image->rows; break; } #if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA) case COMPRESSION_LZMA: { if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL); (void) TIFFSetField(tiff,TIFFTAG_LZMAPRESET,(long) ( image_info->quality == UndefinedCompressionQuality ? 7 : MagickMin((ssize_t) image_info->quality/10,9))); break; } #endif case COMPRESSION_LZW: { (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL); break; } default: break; } if (rows_per_strip < 1) rows_per_strip=1; if ((image->rows/rows_per_strip) >= (1UL << 15)) rows_per_strip=(uint32) (image->rows >> 15); (void) TIFFSetField(tiff,TIFFTAG_ROWSPERSTRIP,rows_per_strip); if ((image->x_resolution != 0.0) && (image->y_resolution != 0.0)) { unsigned short units; /* Set image resolution. */ units=RESUNIT_NONE; if (image->units == PixelsPerInchResolution) units=RESUNIT_INCH; if (image->units == PixelsPerCentimeterResolution) units=RESUNIT_CENTIMETER; (void) TIFFSetField(tiff,TIFFTAG_RESOLUTIONUNIT,(uint16) units); (void) TIFFSetField(tiff,TIFFTAG_XRESOLUTION,image->x_resolution); (void) TIFFSetField(tiff,TIFFTAG_YRESOLUTION,image->y_resolution); if ((image->page.x < 0) || (image->page.y < 0)) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"TIFF: negative image positions unsupported","%s", image->filename); if ((image->page.x > 0) && (image->x_resolution > 0.0)) { /* Set horizontal image position. */ (void) TIFFSetField(tiff,TIFFTAG_XPOSITION,(float) image->page.x/ image->x_resolution); } if ((image->page.y > 0) && (image->y_resolution > 0.0)) { /* Set vertical image position. */ (void) TIFFSetField(tiff,TIFFTAG_YPOSITION,(float) image->page.y/ image->y_resolution); } } if (image->chromaticity.white_point.x != 0.0) { float chromaticity[6]; /* Set image chromaticity. */ chromaticity[0]=(float) image->chromaticity.red_primary.x; chromaticity[1]=(float) image->chromaticity.red_primary.y; chromaticity[2]=(float) image->chromaticity.green_primary.x; chromaticity[3]=(float) image->chromaticity.green_primary.y; chromaticity[4]=(float) image->chromaticity.blue_primary.x; chromaticity[5]=(float) image->chromaticity.blue_primary.y; (void) TIFFSetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,chromaticity); chromaticity[0]=(float) image->chromaticity.white_point.x; chromaticity[1]=(float) image->chromaticity.white_point.y; (void) TIFFSetField(tiff,TIFFTAG_WHITEPOINT,chromaticity); } if ((LocaleCompare(image_info->magick,"PTIF") != 0) && (image_info->adjoin != MagickFalse) && (GetImageListLength(image) > 1)) { (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE); if (image->scene != 0) (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,(uint16) image->scene, GetImageListLength(image)); } if (image->orientation != UndefinedOrientation) (void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,(uint16) image->orientation); (void) TIFFSetProfiles(tiff,image); { uint16 page, pages; page=(uint16) scene; pages=(uint16) GetImageListLength(image); if ((LocaleCompare(image_info->magick,"PTIF") != 0) && (image_info->adjoin != MagickFalse) && (pages > 1)) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE); (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages); } (void) TIFFSetProperties(tiff,image_info,image); DisableMSCWarning(4127) if (0) RestoreMSCWarning (void) TIFFSetEXIFProperties(tiff,image); /* Write image scanlines. */ if (GetTIFFInfo(image_info,tiff,&tiff_info) == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); quantum_info->endian=LSBEndian; pixels=GetQuantumPixels(quantum_info); tiff_info.scanline=GetQuantumPixels(quantum_info); switch (photometric) { case PHOTOMETRIC_CIELAB: case PHOTOMETRIC_YCBCR: case PHOTOMETRIC_RGB: { /* RGB TIFF image. */ switch (image_info->interlace) { case NoInterlace: default: { quantum_type=RGBQuantum; if (image->matte != MagickFalse) quantum_type=RGBAQuantum; for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,quantum_type,pixels,&image->exception); if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } break; } case PlaneInterlace: case PartitionInterlace: { /* Plane interlacing: RRRRRR...GGGGGG...BBBBBB... */ for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RedQuantum,pixels,&image->exception); if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,100,400); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GreenQuantum,pixels,&image->exception); if (TIFFWritePixels(tiff,&tiff_info,y,1,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,200,400); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,BlueQuantum,pixels,&image->exception); if (TIFFWritePixels(tiff,&tiff_info,y,2,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,300,400); if (status == MagickFalse) break; } if (image->matte != MagickFalse) for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,AlphaQuantum,pixels,&image->exception); if (TIFFWritePixels(tiff,&tiff_info,y,3,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,400,400); if (status == MagickFalse) break; } break; } } break; } case PHOTOMETRIC_SEPARATED: { /* CMYK TIFF image. */ quantum_type=CMYKQuantum; if (image->matte != MagickFalse) quantum_type=CMYKAQuantum; if (image->colorspace != CMYKColorspace) (void) TransformImageColorspace(image,CMYKColorspace); for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,quantum_type,pixels,&image->exception); if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case PHOTOMETRIC_PALETTE: { uint16 *blue, *green, *red; /* Colormapped TIFF image. */ red=(uint16 *) AcquireQuantumMemory(65536,sizeof(*red)); green=(uint16 *) AcquireQuantumMemory(65536,sizeof(*green)); blue=(uint16 *) AcquireQuantumMemory(65536,sizeof(*blue)); if ((red == (uint16 *) NULL) || (green == (uint16 *) NULL) || (blue == (uint16 *) NULL)) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize TIFF colormap. */ (void) ResetMagickMemory(red,0,65536*sizeof(*red)); (void) ResetMagickMemory(green,0,65536*sizeof(*green)); (void) ResetMagickMemory(blue,0,65536*sizeof(*blue)); for (i=0; i < (ssize_t) image->colors; i++) { red[i]=ScaleQuantumToShort(image->colormap[i].red); green[i]=ScaleQuantumToShort(image->colormap[i].green); blue[i]=ScaleQuantumToShort(image->colormap[i].blue); } (void) TIFFSetField(tiff,TIFFTAG_COLORMAP,red,green,blue); red=(uint16 *) RelinquishMagickMemory(red); green=(uint16 *) RelinquishMagickMemory(green); blue=(uint16 *) RelinquishMagickMemory(blue); } default: { /* Convert PseudoClass packets to contiguous grayscale scanlines. */ quantum_type=IndexQuantum; if (image->matte != MagickFalse) { if (photometric != PHOTOMETRIC_PALETTE) quantum_type=GrayAlphaQuantum; else quantum_type=IndexAlphaQuantum; } else if (photometric != PHOTOMETRIC_PALETTE) quantum_type=GrayQuantum; for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,quantum_type,pixels,&image->exception); if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } } quantum_info=DestroyQuantumInfo(quantum_info); if (image->colorspace == LabColorspace) DecodeLabImage(image,&image->exception); DestroyTIFFInfo(&tiff_info); DisableMSCWarning(4127) if (0 && (image_info->verbose != MagickFalse)) RestoreMSCWarning TIFFPrintDirectory(tiff,stdout,MagickFalse); (void) TIFFWriteDirectory(tiff); image=SyncNextImageInList(image); if (image == (Image *) NULL) break; status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); TIFFClose(tiff); return(MagickTrue); } #endif
./CrossVul/dataset_final_sorted/CWE-119/c/bad_4779_4
crossvul-cpp_data_bad_346_2
/* * card-muscle.c: Support for MuscleCard Applet from musclecard.com * * Copyright (C) 2006, Identity Alliance, Thomas Harning <support@identityalliance.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <string.h> #include "internal.h" #include "cardctl.h" #include "muscle.h" #include "muscle-filesystem.h" #include "types.h" #include "opensc.h" static struct sc_card_operations muscle_ops; static const struct sc_card_operations *iso_ops = NULL; static struct sc_card_driver muscle_drv = { "MuscleApplet", "muscle", &muscle_ops, NULL, 0, NULL }; static struct sc_atr_table muscle_atrs[] = { /* Tyfone JCOP 242R2 cards */ { "3b:6d:00:00:ff:54:79:66:6f:6e:65:20:32:34:32:52:32", NULL, NULL, SC_CARD_TYPE_MUSCLE_JCOP242R2_NO_EXT_APDU, 0, NULL }, /* Aladdin eToken PRO USB 72K Java */ { "3b:d5:18:00:81:31:3a:7d:80:73:c8:21:10:30", NULL, NULL, SC_CARD_TYPE_MUSCLE_ETOKEN_72K, 0, NULL }, /* JCOP31 v2.4.1 contact interface */ { "3b:f8:13:00:00:81:31:fe:45:4a:43:4f:50:76:32:34:31:b7", NULL, NULL, SC_CARD_TYPE_MUSCLE_JCOP241, 0, NULL }, /* JCOP31 v2.4.1 RF interface */ { "3b:88:80:01:4a:43:4f:50:76:32:34:31:5e", NULL, NULL, SC_CARD_TYPE_MUSCLE_JCOP241, 0, NULL }, { NULL, NULL, NULL, 0, 0, NULL } }; #define MUSCLE_DATA(card) ( (muscle_private_t*)card->drv_data ) #define MUSCLE_FS(card) ( ((muscle_private_t*)card->drv_data)->fs ) typedef struct muscle_private { sc_security_env_t env; unsigned short verifiedPins; mscfs_t *fs; int rsa_key_ref; } muscle_private_t; static int muscle_finish(sc_card_t *card) { muscle_private_t *priv = MUSCLE_DATA(card); mscfs_free(priv->fs); free(priv); return 0; } static u8 muscleAppletId[] = { 0xA0, 0x00,0x00,0x00, 0x01, 0x01 }; static int muscle_match_card(sc_card_t *card) { sc_apdu_t apdu; u8 response[64]; int r; /* Since we send an APDU, the card's logout function may be called... * however it's not always properly nulled out... */ card->ops->logout = NULL; if (msc_select_applet(card, muscleAppletId, sizeof muscleAppletId) == 1) { /* Muscle applet is present, check the protocol version to be sure */ sc_format_apdu(card, &apdu, SC_APDU_CASE_2, 0x3C, 0x00, 0x00); apdu.cla = 0xB0; apdu.le = 64; apdu.resplen = 64; apdu.resp = response; r = sc_transmit_apdu(card, &apdu); if (r == SC_SUCCESS && response[0] == 0x01) { card->type = SC_CARD_TYPE_MUSCLE_V1; } else { card->type = SC_CARD_TYPE_MUSCLE_GENERIC; } return 1; } return 0; } /* Since Musclecard has a different ACL system then PKCS15 * objects need to have their READ/UPDATE/DELETE permissions mapped for files * and directory ACLS need to be set * For keys.. they have different ACLS, but are accessed in different locations, so it shouldn't be an issue here */ static unsigned short muscle_parse_singleAcl(const sc_acl_entry_t* acl) { unsigned short acl_entry = 0; while(acl) { int key = acl->key_ref; int method = acl->method; switch(method) { case SC_AC_NEVER: return 0xFFFF; /* Ignore... other items overwrite these */ case SC_AC_NONE: case SC_AC_UNKNOWN: break; case SC_AC_CHV: acl_entry |= (1 << key); /* Assuming key 0 == SO */ break; case SC_AC_AUT: case SC_AC_TERM: case SC_AC_PRO: default: /* Ignored */ break; } acl = acl->next; } return acl_entry; } static void muscle_parse_acls(const sc_file_t* file, unsigned short* read_perm, unsigned short* write_perm, unsigned short* delete_perm) { assert(read_perm && write_perm && delete_perm); *read_perm = muscle_parse_singleAcl(sc_file_get_acl_entry(file, SC_AC_OP_READ)); *write_perm = muscle_parse_singleAcl(sc_file_get_acl_entry(file, SC_AC_OP_UPDATE)); *delete_perm = muscle_parse_singleAcl(sc_file_get_acl_entry(file, SC_AC_OP_DELETE)); } static int muscle_create_directory(sc_card_t *card, sc_file_t *file) { mscfs_t *fs = MUSCLE_FS(card); msc_id objectId; u8* oid = objectId.id; unsigned id = file->id; unsigned short read_perm = 0, write_perm = 0, delete_perm = 0; int objectSize; int r; if(id == 0) /* No null name files */ return SC_ERROR_INVALID_ARGUMENTS; /* No nesting directories */ if(fs->currentPath[0] != 0x3F || fs->currentPath[1] != 0x00) return SC_ERROR_NOT_SUPPORTED; oid[0] = ((id & 0xFF00) >> 8) & 0xFF; oid[1] = id & 0xFF; oid[2] = oid[3] = 0; objectSize = file->size; muscle_parse_acls(file, &read_perm, &write_perm, &delete_perm); r = msc_create_object(card, objectId, objectSize, read_perm, write_perm, delete_perm); mscfs_clear_cache(fs); if(r >= 0) return 0; return r; } static int muscle_create_file(sc_card_t *card, sc_file_t *file) { mscfs_t *fs = MUSCLE_FS(card); int objectSize = file->size; unsigned short read_perm = 0, write_perm = 0, delete_perm = 0; msc_id objectId; int r; if(file->type == SC_FILE_TYPE_DF) return muscle_create_directory(card, file); if(file->type != SC_FILE_TYPE_WORKING_EF) return SC_ERROR_NOT_SUPPORTED; if(file->id == 0) /* No null name files */ return SC_ERROR_INVALID_ARGUMENTS; muscle_parse_acls(file, &read_perm, &write_perm, &delete_perm); mscfs_lookup_local(fs, file->id, &objectId); r = msc_create_object(card, objectId, objectSize, read_perm, write_perm, delete_perm); mscfs_clear_cache(fs); if(r >= 0) return 0; return r; } static int muscle_read_binary(sc_card_t *card, unsigned int idx, u8* buf, size_t count, unsigned long flags) { mscfs_t *fs = MUSCLE_FS(card); int r; msc_id objectId; u8* oid = objectId.id; mscfs_file_t *file; r = mscfs_check_selection(fs, -1); if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); file = &fs->cache.array[fs->currentFileIndex]; objectId = file->objectId; /* memcpy(objectId.id, file->objectId.id, 4); */ if(!file->ef) { oid[0] = oid[2]; oid[1] = oid[3]; oid[2] = oid[3] = 0; } r = msc_read_object(card, objectId, idx, buf, count); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } static int muscle_update_binary(sc_card_t *card, unsigned int idx, const u8* buf, size_t count, unsigned long flags) { mscfs_t *fs = MUSCLE_FS(card); int r; mscfs_file_t *file; msc_id objectId; u8* oid = objectId.id; r = mscfs_check_selection(fs, -1); if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); file = &fs->cache.array[fs->currentFileIndex]; objectId = file->objectId; /* memcpy(objectId.id, file->objectId.id, 4); */ if(!file->ef) { oid[0] = oid[2]; oid[1] = oid[3]; oid[2] = oid[3] = 0; } if(file->size < idx + count) { int newFileSize = idx + count; u8* buffer = malloc(newFileSize); if(buffer == NULL) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY); r = msc_read_object(card, objectId, 0, buffer, file->size); /* TODO: RETRIEVE ACLS */ if(r < 0) goto update_bin_free_buffer; r = msc_delete_object(card, objectId, 0); if(r < 0) goto update_bin_free_buffer; r = msc_create_object(card, objectId, newFileSize, 0,0,0); if(r < 0) goto update_bin_free_buffer; memcpy(buffer + idx, buf, count); r = msc_update_object(card, objectId, 0, buffer, newFileSize); if(r < 0) goto update_bin_free_buffer; file->size = newFileSize; update_bin_free_buffer: free(buffer); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } else { r = msc_update_object(card, objectId, idx, buf, count); } /* mscfs_clear_cache(fs); */ return r; } /* TODO: Evaluate correctness */ static int muscle_delete_mscfs_file(sc_card_t *card, mscfs_file_t *file_data) { mscfs_t *fs = MUSCLE_FS(card); msc_id id = file_data->objectId; u8* oid = id.id; int r; if(!file_data->ef) { int x; mscfs_file_t *childFile; /* Delete children */ mscfs_check_cache(fs); sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "DELETING Children of: %02X%02X%02X%02X\n", oid[0],oid[1],oid[2],oid[3]); for(x = 0; x < fs->cache.size; x++) { msc_id objectId; childFile = &fs->cache.array[x]; objectId = childFile->objectId; if(0 == memcmp(oid + 2, objectId.id, 2)) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "DELETING: %02X%02X%02X%02X\n", objectId.id[0],objectId.id[1], objectId.id[2],objectId.id[3]); r = muscle_delete_mscfs_file(card, childFile); if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r); } } oid[0] = oid[2]; oid[1] = oid[3]; oid[2] = oid[3] = 0; /* ??? objectId = objectId >> 16; */ } if((0 == memcmp(oid, "\x3F\x00\x00\x00", 4)) || (0 == memcmp(oid, "\x3F\x00\x3F\x00", 4))) { } r = msc_delete_object(card, id, 1); /* Check if its the root... this file generally is virtual * So don't return an error if it fails */ if((0 == memcmp(oid, "\x3F\x00\x00\x00", 4)) || (0 == memcmp(oid, "\x3F\x00\x3F\x00", 4))) return 0; if(r < 0) { printf("ID: %02X%02X%02X%02X\n", oid[0],oid[1],oid[2],oid[3]); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r); } return 0; } static int muscle_delete_file(sc_card_t *card, const sc_path_t *path_in) { mscfs_t *fs = MUSCLE_FS(card); mscfs_file_t *file_data = NULL; int r = 0; r = mscfs_loadFileInfo(fs, path_in->value, path_in->len, &file_data, NULL); if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r); r = muscle_delete_mscfs_file(card, file_data); mscfs_clear_cache(fs); if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r); return 0; } static void muscle_load_single_acl(sc_file_t* file, int operation, unsigned short acl) { int key; /* Everybody by default.... */ sc_file_add_acl_entry(file, operation, SC_AC_NONE, 0); if(acl == 0xFFFF) { sc_file_add_acl_entry(file, operation, SC_AC_NEVER, 0); return; } for(key = 0; key < 16; key++) { if(acl >> key & 1) { sc_file_add_acl_entry(file, operation, SC_AC_CHV, key); } } } static void muscle_load_file_acls(sc_file_t* file, mscfs_file_t *file_data) { muscle_load_single_acl(file, SC_AC_OP_READ, file_data->read); muscle_load_single_acl(file, SC_AC_OP_WRITE, file_data->write); muscle_load_single_acl(file, SC_AC_OP_UPDATE, file_data->write); muscle_load_single_acl(file, SC_AC_OP_DELETE, file_data->delete); } static void muscle_load_dir_acls(sc_file_t* file, mscfs_file_t *file_data) { muscle_load_single_acl(file, SC_AC_OP_SELECT, 0); muscle_load_single_acl(file, SC_AC_OP_LIST_FILES, 0); muscle_load_single_acl(file, SC_AC_OP_LOCK, 0xFFFF); muscle_load_single_acl(file, SC_AC_OP_DELETE, file_data->delete); muscle_load_single_acl(file, SC_AC_OP_CREATE, file_data->write); } /* Required type = -1 for don't care, 1 for EF, 0 for DF */ static int select_item(sc_card_t *card, const sc_path_t *path_in, sc_file_t ** file_out, int requiredType) { mscfs_t *fs = MUSCLE_FS(card); mscfs_file_t *file_data = NULL; int pathlen = path_in->len; int r = 0; int objectIndex; u8* oid; mscfs_check_cache(fs); r = mscfs_loadFileInfo(fs, path_in->value, path_in->len, &file_data, &objectIndex); if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r); /* Check if its the right type */ if(requiredType >= 0 && requiredType != file_data->ef) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_ARGUMENTS); } oid = file_data->objectId.id; /* Is it a file or directory */ if(file_data->ef) { fs->currentPath[0] = oid[0]; fs->currentPath[1] = oid[1]; fs->currentFile[0] = oid[2]; fs->currentFile[1] = oid[3]; } else { fs->currentPath[0] = oid[pathlen - 2]; fs->currentPath[1] = oid[pathlen - 1]; fs->currentFile[0] = 0; fs->currentFile[1] = 0; } fs->currentFileIndex = objectIndex; if(file_out) { sc_file_t *file; file = sc_file_new(); file->path = *path_in; file->size = file_data->size; file->id = (oid[2] << 8) | oid[3]; if(!file_data->ef) { file->type = SC_FILE_TYPE_DF; } else { file->type = SC_FILE_TYPE_WORKING_EF; file->ef_structure = SC_FILE_EF_TRANSPARENT; } /* Setup ACLS */ if(file_data->ef) { muscle_load_file_acls(file, file_data); } else { muscle_load_dir_acls(file, file_data); /* Setup directory acls... */ } file->magic = SC_FILE_MAGIC; *file_out = file; } return 0; } static int muscle_select_file(sc_card_t *card, const sc_path_t *path_in, sc_file_t **file_out) { int r; assert(card != NULL && path_in != NULL); switch (path_in->type) { case SC_PATH_TYPE_FILE_ID: r = select_item(card, path_in, file_out, 1); break; case SC_PATH_TYPE_DF_NAME: r = select_item(card, path_in, file_out, 0); break; case SC_PATH_TYPE_PATH: r = select_item(card, path_in, file_out, -1); break; default: SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS); } if(r > 0) r = 0; SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r); } static int _listFile(mscfs_file_t *file, int reset, void *udata) { int next = reset ? 0x00 : 0x01; return msc_list_objects( (sc_card_t*)udata, next, file); } static int muscle_init(sc_card_t *card) { muscle_private_t *priv; card->name = "MuscleApplet"; card->drv_data = malloc(sizeof(muscle_private_t)); if(!card->drv_data) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY); } memset(card->drv_data, 0, sizeof(muscle_private_t)); priv = MUSCLE_DATA(card); priv->verifiedPins = 0; priv->fs = mscfs_new(); if(!priv->fs) { free(card->drv_data); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY); } priv->fs->udata = card; priv->fs->listFile = _listFile; card->cla = 0xB0; card->flags |= SC_CARD_FLAG_RNG; card->caps |= SC_CARD_CAP_RNG; /* Card type detection */ _sc_match_atr(card, muscle_atrs, &card->type); if(card->type == SC_CARD_TYPE_MUSCLE_ETOKEN_72K) { card->caps |= SC_CARD_CAP_APDU_EXT; } if(card->type == SC_CARD_TYPE_MUSCLE_JCOP241) { card->caps |= SC_CARD_CAP_APDU_EXT; } if (!(card->caps & SC_CARD_CAP_APDU_EXT)) { card->max_recv_size = 255; card->max_send_size = 255; } if(card->type == SC_CARD_TYPE_MUSCLE_JCOP242R2_NO_EXT_APDU) { /* Tyfone JCOP v242R2 card that doesn't support extended APDUs */ } /* FIXME: Card type detection */ if (1) { unsigned long flags; flags = SC_ALGORITHM_RSA_RAW; flags |= SC_ALGORITHM_RSA_HASH_NONE; flags |= SC_ALGORITHM_ONBOARD_KEY_GEN; _sc_card_add_rsa_alg(card, 1024, flags, 0); _sc_card_add_rsa_alg(card, 2048, flags, 0); } return SC_SUCCESS; } static int muscle_list_files(sc_card_t *card, u8 *buf, size_t bufLen) { muscle_private_t* priv = MUSCLE_DATA(card); mscfs_t *fs = priv->fs; int x; int count = 0; mscfs_check_cache(priv->fs); for(x = 0; x < fs->cache.size; x++) { u8* oid= fs->cache.array[x].objectId.id; sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "FILE: %02X%02X%02X%02X\n", oid[0],oid[1],oid[2],oid[3]); if(0 == memcmp(fs->currentPath, oid, 2)) { buf[0] = oid[2]; buf[1] = oid[3]; if(buf[0] == 0x00 && buf[1] == 0x00) continue; /* No directories/null names outside of root */ buf += 2; count+=2; } } return count; } static int muscle_pin_cmd(sc_card_t *card, struct sc_pin_cmd_data *cmd, int *tries_left) { muscle_private_t* priv = MUSCLE_DATA(card); const int bufferLength = MSC_MAX_PIN_COMMAND_LENGTH; u8 buffer[MSC_MAX_PIN_COMMAND_LENGTH]; switch(cmd->cmd) { case SC_PIN_CMD_VERIFY: switch(cmd->pin_type) { case SC_AC_CHV: { sc_apdu_t apdu; int r; msc_verify_pin_apdu(card, &apdu, buffer, bufferLength, cmd->pin_reference, cmd->pin1.data, cmd->pin1.len); cmd->apdu = &apdu; cmd->pin1.offset = 5; r = iso_ops->pin_cmd(card, cmd, tries_left); if(r >= 0) priv->verifiedPins |= (1 << cmd->pin_reference); return r; } case SC_AC_TERM: case SC_AC_PRO: case SC_AC_AUT: case SC_AC_NONE: default: sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported authentication method\n"); return SC_ERROR_NOT_SUPPORTED; } case SC_PIN_CMD_CHANGE: switch(cmd->pin_type) { case SC_AC_CHV: { sc_apdu_t apdu; msc_change_pin_apdu(card, &apdu, buffer, bufferLength, cmd->pin_reference, cmd->pin1.data, cmd->pin1.len, cmd->pin2.data, cmd->pin2.len); cmd->apdu = &apdu; return iso_ops->pin_cmd(card, cmd, tries_left); } case SC_AC_TERM: case SC_AC_PRO: case SC_AC_AUT: case SC_AC_NONE: default: sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported authentication method\n"); return SC_ERROR_NOT_SUPPORTED; } case SC_PIN_CMD_UNBLOCK: switch(cmd->pin_type) { case SC_AC_CHV: { sc_apdu_t apdu; msc_unblock_pin_apdu(card, &apdu, buffer, bufferLength, cmd->pin_reference, cmd->pin1.data, cmd->pin1.len); cmd->apdu = &apdu; return iso_ops->pin_cmd(card, cmd, tries_left); } case SC_AC_TERM: case SC_AC_PRO: case SC_AC_AUT: case SC_AC_NONE: default: sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported authentication method\n"); return SC_ERROR_NOT_SUPPORTED; } default: sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported command\n"); return SC_ERROR_NOT_SUPPORTED; } } static int muscle_card_extract_key(sc_card_t *card, sc_cardctl_muscle_key_info_t *info) { /* CURRENTLY DONT SUPPORT EXTRACTING PRIVATE KEYS... */ switch(info->keyType) { case 1: /* RSA */ return msc_extract_rsa_public_key(card, info->keyLocation, &info->modLength, &info->modValue, &info->expLength, &info->expValue); default: return SC_ERROR_NOT_SUPPORTED; } } static int muscle_card_import_key(sc_card_t *card, sc_cardctl_muscle_key_info_t *info) { /* CURRENTLY DONT SUPPORT EXTRACTING PRIVATE KEYS... */ switch(info->keyType) { case 0x02: /* RSA_PRIVATE */ case 0x03: /* RSA_PRIVATE_CRT */ return msc_import_key(card, info->keyLocation, info); default: return SC_ERROR_NOT_SUPPORTED; } } static int muscle_card_generate_key(sc_card_t *card, sc_cardctl_muscle_gen_key_info_t *info) { return msc_generate_keypair(card, info->privateKeyLocation, info->publicKeyLocation, info->keyType, info->keySize, 0); } static int muscle_card_verified_pins(sc_card_t *card, sc_cardctl_muscle_verified_pins_info_t *info) { muscle_private_t* priv = MUSCLE_DATA(card); info->verifiedPins = priv->verifiedPins; return 0; } static int muscle_card_ctl(sc_card_t *card, unsigned long request, void *data) { switch(request) { case SC_CARDCTL_MUSCLE_GENERATE_KEY: return muscle_card_generate_key(card, (sc_cardctl_muscle_gen_key_info_t*) data); case SC_CARDCTL_MUSCLE_EXTRACT_KEY: return muscle_card_extract_key(card, (sc_cardctl_muscle_key_info_t*) data); case SC_CARDCTL_MUSCLE_IMPORT_KEY: return muscle_card_import_key(card, (sc_cardctl_muscle_key_info_t*) data); case SC_CARDCTL_MUSCLE_VERIFIED_PINS: return muscle_card_verified_pins(card, (sc_cardctl_muscle_verified_pins_info_t*) data); default: return SC_ERROR_NOT_SUPPORTED; /* Unsupported.. whatever it is */ } } static int muscle_set_security_env(sc_card_t *card, const sc_security_env_t *env, int se_num) { muscle_private_t* priv = MUSCLE_DATA(card); if (env->operation != SC_SEC_OPERATION_SIGN && env->operation != SC_SEC_OPERATION_DECIPHER) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Invalid crypto operation supplied.\n"); return SC_ERROR_NOT_SUPPORTED; } if (env->algorithm != SC_ALGORITHM_RSA) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Invalid crypto algorithm supplied.\n"); return SC_ERROR_NOT_SUPPORTED; } /* ADJUST FOR PKCS1 padding support for decryption only */ if ((env->algorithm_flags & SC_ALGORITHM_RSA_PADS) || (env->algorithm_flags & SC_ALGORITHM_RSA_HASHES)) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Card supports only raw RSA.\n"); return SC_ERROR_NOT_SUPPORTED; } if (env->flags & SC_SEC_ENV_KEY_REF_PRESENT) { if (env->key_ref_len != 1 || (env->key_ref[0] > 0x0F)) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Invalid key reference supplied.\n"); return SC_ERROR_NOT_SUPPORTED; } priv->rsa_key_ref = env->key_ref[0]; } if (env->flags & SC_SEC_ENV_ALG_REF_PRESENT) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Algorithm reference not supported.\n"); return SC_ERROR_NOT_SUPPORTED; } /* if (env->flags & SC_SEC_ENV_FILE_REF_PRESENT) if (memcmp(env->file_ref.value, "\x00\x12", 2) != 0) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "File reference is not 0012.\n"); return SC_ERROR_NOT_SUPPORTED; } */ priv->env = *env; return 0; } static int muscle_restore_security_env(sc_card_t *card, int se_num) { muscle_private_t* priv = MUSCLE_DATA(card); memset(&priv->env, 0, sizeof(priv->env)); return 0; } static int muscle_decipher(sc_card_t * card, const u8 * crgram, size_t crgram_len, u8 * out, size_t out_len) { muscle_private_t* priv = MUSCLE_DATA(card); u8 key_id; int r; /* sanity check */ if (priv->env.operation != SC_SEC_OPERATION_DECIPHER) return SC_ERROR_INVALID_ARGUMENTS; key_id = priv->rsa_key_ref * 2; /* Private key */ if (out_len < crgram_len) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Output buffer too small"); return SC_ERROR_BUFFER_TOO_SMALL; } r = msc_compute_crypt(card, key_id, 0x00, /* RSA NO PADDING */ 0x04, /* decrypt */ crgram, out, crgram_len, out_len); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card signature failed"); return r; } static int muscle_compute_signature(sc_card_t *card, const u8 *data, size_t data_len, u8 * out, size_t outlen) { muscle_private_t* priv = MUSCLE_DATA(card); u8 key_id; int r; key_id = priv->rsa_key_ref * 2; /* Private key */ if (outlen < data_len) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Output buffer too small"); return SC_ERROR_BUFFER_TOO_SMALL; } r = msc_compute_crypt(card, key_id, 0x00, /* RSA NO PADDING */ 0x04, /* -- decrypt raw... will do what we need since signing isn't yet supported */ data, out, data_len, outlen); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card signature failed"); return r; } static int muscle_get_challenge(sc_card_t *card, u8 *rnd, size_t len) { if (len == 0) return SC_SUCCESS; else { SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, msc_get_challenge(card, len, 0, NULL, rnd), "GET CHALLENGE cmd failed"); return (int) len; } } static int muscle_check_sw(sc_card_t * card, unsigned int sw1, unsigned int sw2) { if(sw1 == 0x9C) { switch(sw2) { case 0x01: /* SW_NO_MEMORY_LEFT */ return SC_ERROR_NOT_ENOUGH_MEMORY; case 0x02: /* SW_AUTH_FAILED */ return SC_ERROR_PIN_CODE_INCORRECT; case 0x03: /* SW_OPERATION_NOT_ALLOWED */ return SC_ERROR_NOT_ALLOWED; case 0x05: /* SW_UNSUPPORTED_FEATURE */ return SC_ERROR_NO_CARD_SUPPORT; case 0x06: /* SW_UNAUTHORIZED */ return SC_ERROR_SECURITY_STATUS_NOT_SATISFIED; case 0x07: /* SW_OBJECT_NOT_FOUND */ return SC_ERROR_FILE_NOT_FOUND; case 0x08: /* SW_OBJECT_EXISTS */ return SC_ERROR_FILE_ALREADY_EXISTS; case 0x09: /* SW_INCORRECT_ALG */ return SC_ERROR_INCORRECT_PARAMETERS; case 0x0B: /* SW_SIGNATURE_INVALID */ return SC_ERROR_CARD_CMD_FAILED; case 0x0C: /* SW_IDENTITY_BLOCKED */ return SC_ERROR_AUTH_METHOD_BLOCKED; case 0x0F: /* SW_INVALID_PARAMETER */ case 0x10: /* SW_INCORRECT_P1 */ case 0x11: /* SW_INCORRECT_P2 */ return SC_ERROR_INCORRECT_PARAMETERS; } } return iso_ops->check_sw(card, sw1, sw2); } static int muscle_card_reader_lock_obtained(sc_card_t *card, int was_reset) { int r = SC_SUCCESS; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); if (was_reset > 0) { if (msc_select_applet(card, muscleAppletId, sizeof muscleAppletId) != 1) { r = SC_ERROR_INVALID_CARD; } } LOG_FUNC_RETURN(card->ctx, r); } static struct sc_card_driver * sc_get_driver(void) { struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); if (iso_ops == NULL) iso_ops = iso_drv->ops; muscle_ops = *iso_drv->ops; muscle_ops.check_sw = muscle_check_sw; muscle_ops.pin_cmd = muscle_pin_cmd; muscle_ops.match_card = muscle_match_card; muscle_ops.init = muscle_init; muscle_ops.finish = muscle_finish; muscle_ops.get_challenge = muscle_get_challenge; muscle_ops.set_security_env = muscle_set_security_env; muscle_ops.restore_security_env = muscle_restore_security_env; muscle_ops.compute_signature = muscle_compute_signature; muscle_ops.decipher = muscle_decipher; muscle_ops.card_ctl = muscle_card_ctl; muscle_ops.read_binary = muscle_read_binary; muscle_ops.update_binary = muscle_update_binary; muscle_ops.create_file = muscle_create_file; muscle_ops.select_file = muscle_select_file; muscle_ops.delete_file = muscle_delete_file; muscle_ops.list_files = muscle_list_files; muscle_ops.card_reader_lock_obtained = muscle_card_reader_lock_obtained; return &muscle_drv; } struct sc_card_driver * sc_get_muscle_driver(void) { return sc_get_driver(); }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_346_2
crossvul-cpp_data_good_730_0
// SPDX-License-Identifier: BSD-2-Clause /* * Copyright (c) 2014, STMicroelectronics International N.V. */ #include <assert.h> #include <compiler.h> #include <crypto/crypto.h> #include <kernel/tee_ta_manager.h> #include <mm/tee_mmu.h> #include <string_ext.h> #include <string.h> #include <sys/queue.h> #include <tee_api_types.h> #include <tee/tee_cryp_utl.h> #include <tee/tee_obj.h> #include <tee/tee_svc_cryp.h> #include <tee/tee_svc.h> #include <trace.h> #include <utee_defines.h> #include <util.h> #include <tee_api_defines_extensions.h> #if defined(CFG_CRYPTO_HKDF) #include <tee/tee_cryp_hkdf.h> #endif #if defined(CFG_CRYPTO_CONCAT_KDF) #include <tee/tee_cryp_concat_kdf.h> #endif #if defined(CFG_CRYPTO_PBKDF2) #include <tee/tee_cryp_pbkdf2.h> #endif typedef void (*tee_cryp_ctx_finalize_func_t) (void *ctx, uint32_t algo); struct tee_cryp_state { TAILQ_ENTRY(tee_cryp_state) link; uint32_t algo; uint32_t mode; vaddr_t key1; vaddr_t key2; void *ctx; tee_cryp_ctx_finalize_func_t ctx_finalize; }; struct tee_cryp_obj_secret { uint32_t key_size; uint32_t alloc_size; /* * Pseudo code visualize layout of structure * Next follows data, such as: * uint8_t data[alloc_size] * key_size must never exceed alloc_size */ }; #define TEE_TYPE_ATTR_OPTIONAL 0x0 #define TEE_TYPE_ATTR_REQUIRED 0x1 #define TEE_TYPE_ATTR_OPTIONAL_GROUP 0x2 #define TEE_TYPE_ATTR_SIZE_INDICATOR 0x4 #define TEE_TYPE_ATTR_GEN_KEY_OPT 0x8 #define TEE_TYPE_ATTR_GEN_KEY_REQ 0x10 /* Handle storing of generic secret keys of varying lengths */ #define ATTR_OPS_INDEX_SECRET 0 /* Convert to/from big-endian byte array and provider-specific bignum */ #define ATTR_OPS_INDEX_BIGNUM 1 /* Convert to/from value attribute depending on direction */ #define ATTR_OPS_INDEX_VALUE 2 struct tee_cryp_obj_type_attrs { uint32_t attr_id; uint16_t flags; uint16_t ops_index; uint16_t raw_offs; uint16_t raw_size; }; #define RAW_DATA(_x, _y) \ .raw_offs = offsetof(_x, _y), .raw_size = MEMBER_SIZE(_x, _y) static const struct tee_cryp_obj_type_attrs tee_cryp_obj_secret_value_attrs[] = { { .attr_id = TEE_ATTR_SECRET_VALUE, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_SECRET, .raw_offs = 0, .raw_size = 0 }, }; static const struct tee_cryp_obj_type_attrs tee_cryp_obj_rsa_pub_key_attrs[] = { { .attr_id = TEE_ATTR_RSA_MODULUS, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_public_key, n) }, { .attr_id = TEE_ATTR_RSA_PUBLIC_EXPONENT, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_public_key, e) }, }; static const struct tee_cryp_obj_type_attrs tee_cryp_obj_rsa_keypair_attrs[] = { { .attr_id = TEE_ATTR_RSA_MODULUS, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, n) }, { .attr_id = TEE_ATTR_RSA_PUBLIC_EXPONENT, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, e) }, { .attr_id = TEE_ATTR_RSA_PRIVATE_EXPONENT, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, d) }, { .attr_id = TEE_ATTR_RSA_PRIME1, .flags = TEE_TYPE_ATTR_OPTIONAL_GROUP, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, p) }, { .attr_id = TEE_ATTR_RSA_PRIME2, .flags = TEE_TYPE_ATTR_OPTIONAL_GROUP, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, q) }, { .attr_id = TEE_ATTR_RSA_EXPONENT1, .flags = TEE_TYPE_ATTR_OPTIONAL_GROUP, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, dp) }, { .attr_id = TEE_ATTR_RSA_EXPONENT2, .flags = TEE_TYPE_ATTR_OPTIONAL_GROUP, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, dq) }, { .attr_id = TEE_ATTR_RSA_COEFFICIENT, .flags = TEE_TYPE_ATTR_OPTIONAL_GROUP, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, qp) }, }; static const struct tee_cryp_obj_type_attrs tee_cryp_obj_dsa_pub_key_attrs[] = { { .attr_id = TEE_ATTR_DSA_PRIME, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_public_key, p) }, { .attr_id = TEE_ATTR_DSA_SUBPRIME, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_public_key, q) }, { .attr_id = TEE_ATTR_DSA_BASE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_public_key, g) }, { .attr_id = TEE_ATTR_DSA_PUBLIC_VALUE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_public_key, y) }, }; static const struct tee_cryp_obj_type_attrs tee_cryp_obj_dsa_keypair_attrs[] = { { .attr_id = TEE_ATTR_DSA_PRIME, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_GEN_KEY_REQ, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_keypair, p) }, { .attr_id = TEE_ATTR_DSA_SUBPRIME, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR | TEE_TYPE_ATTR_GEN_KEY_REQ, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_keypair, q) }, { .attr_id = TEE_ATTR_DSA_BASE, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_GEN_KEY_REQ, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_keypair, g) }, { .attr_id = TEE_ATTR_DSA_PRIVATE_VALUE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_keypair, x) }, { .attr_id = TEE_ATTR_DSA_PUBLIC_VALUE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_keypair, y) }, }; static const struct tee_cryp_obj_type_attrs tee_cryp_obj_dh_keypair_attrs[] = { { .attr_id = TEE_ATTR_DH_PRIME, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR | TEE_TYPE_ATTR_GEN_KEY_REQ, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dh_keypair, p) }, { .attr_id = TEE_ATTR_DH_BASE, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_GEN_KEY_REQ, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dh_keypair, g) }, { .attr_id = TEE_ATTR_DH_PUBLIC_VALUE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dh_keypair, y) }, { .attr_id = TEE_ATTR_DH_PRIVATE_VALUE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dh_keypair, x) }, { .attr_id = TEE_ATTR_DH_SUBPRIME, .flags = TEE_TYPE_ATTR_OPTIONAL_GROUP | TEE_TYPE_ATTR_GEN_KEY_OPT, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dh_keypair, q) }, { .attr_id = TEE_ATTR_DH_X_BITS, .flags = TEE_TYPE_ATTR_GEN_KEY_OPT, .ops_index = ATTR_OPS_INDEX_VALUE, RAW_DATA(struct dh_keypair, xbits) }, }; #if defined(CFG_CRYPTO_HKDF) static const struct tee_cryp_obj_type_attrs tee_cryp_obj_hkdf_ikm_attrs[] = { { .attr_id = TEE_ATTR_HKDF_IKM, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_SECRET, .raw_offs = 0, .raw_size = 0 }, }; #endif #if defined(CFG_CRYPTO_CONCAT_KDF) static const struct tee_cryp_obj_type_attrs tee_cryp_obj_concat_kdf_z_attrs[] = { { .attr_id = TEE_ATTR_CONCAT_KDF_Z, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_SECRET, .raw_offs = 0, .raw_size = 0 }, }; #endif #if defined(CFG_CRYPTO_PBKDF2) static const struct tee_cryp_obj_type_attrs tee_cryp_obj_pbkdf2_passwd_attrs[] = { { .attr_id = TEE_ATTR_PBKDF2_PASSWORD, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_SECRET, .raw_offs = 0, .raw_size = 0 }, }; #endif static const struct tee_cryp_obj_type_attrs tee_cryp_obj_ecc_pub_key_attrs[] = { { .attr_id = TEE_ATTR_ECC_PUBLIC_VALUE_X, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct ecc_public_key, x) }, { .attr_id = TEE_ATTR_ECC_PUBLIC_VALUE_Y, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct ecc_public_key, y) }, { .attr_id = TEE_ATTR_ECC_CURVE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_VALUE, RAW_DATA(struct ecc_public_key, curve) }, }; static const struct tee_cryp_obj_type_attrs tee_cryp_obj_ecc_keypair_attrs[] = { { .attr_id = TEE_ATTR_ECC_PRIVATE_VALUE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct ecc_keypair, d) }, { .attr_id = TEE_ATTR_ECC_PUBLIC_VALUE_X, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct ecc_keypair, x) }, { .attr_id = TEE_ATTR_ECC_PUBLIC_VALUE_Y, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct ecc_keypair, y) }, { .attr_id = TEE_ATTR_ECC_CURVE, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_VALUE, RAW_DATA(struct ecc_keypair, curve) }, }; struct tee_cryp_obj_type_props { TEE_ObjectType obj_type; uint16_t min_size; /* may not be smaller than this */ uint16_t max_size; /* may not be larger than this */ uint16_t alloc_size; /* this many bytes are allocated to hold data */ uint8_t quanta; /* may only be an multiple of this */ uint8_t num_type_attrs; const struct tee_cryp_obj_type_attrs *type_attrs; }; #define PROP(obj_type, quanta, min_size, max_size, alloc_size, type_attrs) \ { (obj_type), (min_size), (max_size), (alloc_size), (quanta), \ ARRAY_SIZE(type_attrs), (type_attrs) } static const struct tee_cryp_obj_type_props tee_cryp_obj_props[] = { PROP(TEE_TYPE_AES, 64, 128, 256, /* valid sizes 128, 192, 256 */ 256 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_DES, 56, 56, 56, /* * Valid size 56 without parity, note that we still allocate * for 64 bits since the key is supplied with parity. */ 64 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_DES3, 56, 112, 168, /* * Valid sizes 112, 168 without parity, note that we still * allocate for with space for the parity since the key is * supplied with parity. */ 192 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_HMAC_MD5, 8, 64, 512, 512 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_HMAC_SHA1, 8, 80, 512, 512 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_HMAC_SHA224, 8, 112, 512, 512 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_HMAC_SHA256, 8, 192, 1024, 1024 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_HMAC_SHA384, 8, 256, 1024, 1024 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_HMAC_SHA512, 8, 256, 1024, 1024 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_GENERIC_SECRET, 8, 0, 4096, 4096 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), #if defined(CFG_CRYPTO_HKDF) PROP(TEE_TYPE_HKDF_IKM, 8, 0, 4096, 4096 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_hkdf_ikm_attrs), #endif #if defined(CFG_CRYPTO_CONCAT_KDF) PROP(TEE_TYPE_CONCAT_KDF_Z, 8, 0, 4096, 4096 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_concat_kdf_z_attrs), #endif #if defined(CFG_CRYPTO_PBKDF2) PROP(TEE_TYPE_PBKDF2_PASSWORD, 8, 0, 4096, 4096 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_pbkdf2_passwd_attrs), #endif PROP(TEE_TYPE_RSA_PUBLIC_KEY, 1, 256, CFG_CORE_BIGNUM_MAX_BITS, sizeof(struct rsa_public_key), tee_cryp_obj_rsa_pub_key_attrs), PROP(TEE_TYPE_RSA_KEYPAIR, 1, 256, CFG_CORE_BIGNUM_MAX_BITS, sizeof(struct rsa_keypair), tee_cryp_obj_rsa_keypair_attrs), PROP(TEE_TYPE_DSA_PUBLIC_KEY, 64, 512, 3072, sizeof(struct dsa_public_key), tee_cryp_obj_dsa_pub_key_attrs), PROP(TEE_TYPE_DSA_KEYPAIR, 64, 512, 3072, sizeof(struct dsa_keypair), tee_cryp_obj_dsa_keypair_attrs), PROP(TEE_TYPE_DH_KEYPAIR, 1, 256, 2048, sizeof(struct dh_keypair), tee_cryp_obj_dh_keypair_attrs), PROP(TEE_TYPE_ECDSA_PUBLIC_KEY, 1, 192, 521, sizeof(struct ecc_public_key), tee_cryp_obj_ecc_pub_key_attrs), PROP(TEE_TYPE_ECDSA_KEYPAIR, 1, 192, 521, sizeof(struct ecc_keypair), tee_cryp_obj_ecc_keypair_attrs), PROP(TEE_TYPE_ECDH_PUBLIC_KEY, 1, 192, 521, sizeof(struct ecc_public_key), tee_cryp_obj_ecc_pub_key_attrs), PROP(TEE_TYPE_ECDH_KEYPAIR, 1, 192, 521, sizeof(struct ecc_keypair), tee_cryp_obj_ecc_keypair_attrs), }; struct attr_ops { TEE_Result (*from_user)(void *attr, const void *buffer, size_t size); TEE_Result (*to_user)(void *attr, struct tee_ta_session *sess, void *buffer, uint64_t *size); TEE_Result (*to_binary)(void *attr, void *data, size_t data_len, size_t *offs); bool (*from_binary)(void *attr, const void *data, size_t data_len, size_t *offs); TEE_Result (*from_obj)(void *attr, void *src_attr); void (*free)(void *attr); void (*clear)(void *attr); }; static TEE_Result op_u32_to_binary_helper(uint32_t v, uint8_t *data, size_t data_len, size_t *offs) { uint32_t field; size_t next_offs; if (ADD_OVERFLOW(*offs, sizeof(field), &next_offs)) return TEE_ERROR_OVERFLOW; if (data && next_offs <= data_len) { field = TEE_U32_TO_BIG_ENDIAN(v); memcpy(data + *offs, &field, sizeof(field)); } (*offs) = next_offs; return TEE_SUCCESS; } static bool op_u32_from_binary_helper(uint32_t *v, const uint8_t *data, size_t data_len, size_t *offs) { uint32_t field; if (!data || (*offs + sizeof(field)) > data_len) return false; memcpy(&field, data + *offs, sizeof(field)); *v = TEE_U32_FROM_BIG_ENDIAN(field); (*offs) += sizeof(field); return true; } static TEE_Result op_attr_secret_value_from_user(void *attr, const void *buffer, size_t size) { struct tee_cryp_obj_secret *key = attr; /* Data size has to fit in allocated buffer */ if (size > key->alloc_size) return TEE_ERROR_SECURITY; memcpy(key + 1, buffer, size); key->key_size = size; return TEE_SUCCESS; } static TEE_Result op_attr_secret_value_to_user(void *attr, struct tee_ta_session *sess __unused, void *buffer, uint64_t *size) { TEE_Result res; struct tee_cryp_obj_secret *key = attr; uint64_t s; uint64_t key_size; res = tee_svc_copy_from_user(&s, size, sizeof(s)); if (res != TEE_SUCCESS) return res; key_size = key->key_size; res = tee_svc_copy_to_user(size, &key_size, sizeof(key_size)); if (res != TEE_SUCCESS) return res; if (s < key->key_size || !buffer) return TEE_ERROR_SHORT_BUFFER; return tee_svc_copy_to_user(buffer, key + 1, key->key_size); } static TEE_Result op_attr_secret_value_to_binary(void *attr, void *data, size_t data_len, size_t *offs) { TEE_Result res; struct tee_cryp_obj_secret *key = attr; size_t next_offs; res = op_u32_to_binary_helper(key->key_size, data, data_len, offs); if (res != TEE_SUCCESS) return res; if (ADD_OVERFLOW(*offs, key->key_size, &next_offs)) return TEE_ERROR_OVERFLOW; if (data && next_offs <= data_len) memcpy((uint8_t *)data + *offs, key + 1, key->key_size); (*offs) = next_offs; return TEE_SUCCESS; } static bool op_attr_secret_value_from_binary(void *attr, const void *data, size_t data_len, size_t *offs) { struct tee_cryp_obj_secret *key = attr; uint32_t s; if (!op_u32_from_binary_helper(&s, data, data_len, offs)) return false; if ((*offs + s) > data_len) return false; /* Data size has to fit in allocated buffer */ if (s > key->alloc_size) return false; key->key_size = s; memcpy(key + 1, (const uint8_t *)data + *offs, s); (*offs) += s; return true; } static TEE_Result op_attr_secret_value_from_obj(void *attr, void *src_attr) { struct tee_cryp_obj_secret *key = attr; struct tee_cryp_obj_secret *src_key = src_attr; if (src_key->key_size > key->alloc_size) return TEE_ERROR_BAD_STATE; memcpy(key + 1, src_key + 1, src_key->key_size); key->key_size = src_key->key_size; return TEE_SUCCESS; } static void op_attr_secret_value_clear(void *attr) { struct tee_cryp_obj_secret *key = attr; key->key_size = 0; memset(key + 1, 0, key->alloc_size); } static TEE_Result op_attr_bignum_from_user(void *attr, const void *buffer, size_t size) { struct bignum **bn = attr; return crypto_bignum_bin2bn(buffer, size, *bn); } static TEE_Result op_attr_bignum_to_user(void *attr, struct tee_ta_session *sess, void *buffer, uint64_t *size) { TEE_Result res; struct bignum **bn = attr; uint64_t req_size; uint64_t s; res = tee_svc_copy_from_user(&s, size, sizeof(s)); if (res != TEE_SUCCESS) return res; req_size = crypto_bignum_num_bytes(*bn); res = tee_svc_copy_to_user(size, &req_size, sizeof(req_size)); if (res != TEE_SUCCESS) return res; if (!req_size) return TEE_SUCCESS; if (s < req_size || !buffer) return TEE_ERROR_SHORT_BUFFER; /* Check we can access data using supplied user mode pointer */ res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)buffer, req_size); if (res != TEE_SUCCESS) return res; /* * Write the bignum (wich raw data points to) into an array of * bytes (stored in buffer) */ crypto_bignum_bn2bin(*bn, buffer); return TEE_SUCCESS; } static TEE_Result op_attr_bignum_to_binary(void *attr, void *data, size_t data_len, size_t *offs) { TEE_Result res; struct bignum **bn = attr; uint32_t n = crypto_bignum_num_bytes(*bn); size_t next_offs; res = op_u32_to_binary_helper(n, data, data_len, offs); if (res != TEE_SUCCESS) return res; if (ADD_OVERFLOW(*offs, n, &next_offs)) return TEE_ERROR_OVERFLOW; if (data && next_offs <= data_len) crypto_bignum_bn2bin(*bn, (uint8_t *)data + *offs); (*offs) = next_offs; return TEE_SUCCESS; } static bool op_attr_bignum_from_binary(void *attr, const void *data, size_t data_len, size_t *offs) { struct bignum **bn = attr; uint32_t n; if (!op_u32_from_binary_helper(&n, data, data_len, offs)) return false; if ((*offs + n) > data_len) return false; if (crypto_bignum_bin2bn((const uint8_t *)data + *offs, n, *bn)) return false; (*offs) += n; return true; } static TEE_Result op_attr_bignum_from_obj(void *attr, void *src_attr) { struct bignum **bn = attr; struct bignum **src_bn = src_attr; crypto_bignum_copy(*bn, *src_bn); return TEE_SUCCESS; } static void op_attr_bignum_clear(void *attr) { struct bignum **bn = attr; crypto_bignum_clear(*bn); } static void op_attr_bignum_free(void *attr) { struct bignum **bn = attr; crypto_bignum_free(*bn); *bn = NULL; } static TEE_Result op_attr_value_from_user(void *attr, const void *buffer, size_t size) { uint32_t *v = attr; if (size != sizeof(uint32_t) * 2) return TEE_ERROR_GENERIC; /* "can't happen */ /* Note that only the first value is copied */ memcpy(v, buffer, sizeof(uint32_t)); return TEE_SUCCESS; } static TEE_Result op_attr_value_to_user(void *attr, struct tee_ta_session *sess __unused, void *buffer, uint64_t *size) { TEE_Result res; uint32_t *v = attr; uint64_t s; uint32_t value[2] = { *v }; uint64_t req_size = sizeof(value); res = tee_svc_copy_from_user(&s, size, sizeof(s)); if (res != TEE_SUCCESS) return res; if (s < req_size || !buffer) return TEE_ERROR_SHORT_BUFFER; return tee_svc_copy_to_user(buffer, value, req_size); } static TEE_Result op_attr_value_to_binary(void *attr, void *data, size_t data_len, size_t *offs) { uint32_t *v = attr; return op_u32_to_binary_helper(*v, data, data_len, offs); } static bool op_attr_value_from_binary(void *attr, const void *data, size_t data_len, size_t *offs) { uint32_t *v = attr; return op_u32_from_binary_helper(v, data, data_len, offs); } static TEE_Result op_attr_value_from_obj(void *attr, void *src_attr) { uint32_t *v = attr; uint32_t *src_v = src_attr; *v = *src_v; return TEE_SUCCESS; } static void op_attr_value_clear(void *attr) { uint32_t *v = attr; *v = 0; } static const struct attr_ops attr_ops[] = { [ATTR_OPS_INDEX_SECRET] = { .from_user = op_attr_secret_value_from_user, .to_user = op_attr_secret_value_to_user, .to_binary = op_attr_secret_value_to_binary, .from_binary = op_attr_secret_value_from_binary, .from_obj = op_attr_secret_value_from_obj, .free = op_attr_secret_value_clear, /* not a typo */ .clear = op_attr_secret_value_clear, }, [ATTR_OPS_INDEX_BIGNUM] = { .from_user = op_attr_bignum_from_user, .to_user = op_attr_bignum_to_user, .to_binary = op_attr_bignum_to_binary, .from_binary = op_attr_bignum_from_binary, .from_obj = op_attr_bignum_from_obj, .free = op_attr_bignum_free, .clear = op_attr_bignum_clear, }, [ATTR_OPS_INDEX_VALUE] = { .from_user = op_attr_value_from_user, .to_user = op_attr_value_to_user, .to_binary = op_attr_value_to_binary, .from_binary = op_attr_value_from_binary, .from_obj = op_attr_value_from_obj, .free = op_attr_value_clear, /* not a typo */ .clear = op_attr_value_clear, }, }; TEE_Result syscall_cryp_obj_get_info(unsigned long obj, TEE_ObjectInfo *info) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) goto exit; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) goto exit; res = tee_svc_copy_to_user(info, &o->info, sizeof(o->info)); exit: return res; } TEE_Result syscall_cryp_obj_restrict_usage(unsigned long obj, unsigned long usage) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) goto exit; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) goto exit; o->info.objectUsage &= usage; exit: return res; } static int tee_svc_cryp_obj_find_type_attr_idx( uint32_t attr_id, const struct tee_cryp_obj_type_props *type_props) { size_t n; for (n = 0; n < type_props->num_type_attrs; n++) { if (attr_id == type_props->type_attrs[n].attr_id) return n; } return -1; } static const struct tee_cryp_obj_type_props *tee_svc_find_type_props( TEE_ObjectType obj_type) { size_t n; for (n = 0; n < ARRAY_SIZE(tee_cryp_obj_props); n++) { if (tee_cryp_obj_props[n].obj_type == obj_type) return tee_cryp_obj_props + n; } return NULL; } /* Set an attribute on an object */ static void set_attribute(struct tee_obj *o, const struct tee_cryp_obj_type_props *props, uint32_t attr) { int idx = tee_svc_cryp_obj_find_type_attr_idx(attr, props); if (idx < 0) return; o->have_attrs |= BIT(idx); } /* Get an attribute on an object */ static uint32_t get_attribute(const struct tee_obj *o, const struct tee_cryp_obj_type_props *props, uint32_t attr) { int idx = tee_svc_cryp_obj_find_type_attr_idx(attr, props); if (idx < 0) return 0; return o->have_attrs & BIT(idx); } TEE_Result syscall_cryp_obj_get_attr(unsigned long obj, unsigned long attr_id, void *buffer, uint64_t *size) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; const struct tee_cryp_obj_type_props *type_props; int idx; const struct attr_ops *ops; void *attr; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) return TEE_ERROR_ITEM_NOT_FOUND; /* Check that the object is initialized */ if (!(o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED)) return TEE_ERROR_BAD_PARAMETERS; /* Check that getting the attribute is allowed */ if (!(attr_id & TEE_ATTR_BIT_PROTECTED) && !(o->info.objectUsage & TEE_USAGE_EXTRACTABLE)) return TEE_ERROR_BAD_PARAMETERS; type_props = tee_svc_find_type_props(o->info.objectType); if (!type_props) { /* Unknown object type, "can't happen" */ return TEE_ERROR_BAD_STATE; } idx = tee_svc_cryp_obj_find_type_attr_idx(attr_id, type_props); if ((idx < 0) || ((o->have_attrs & (1 << idx)) == 0)) return TEE_ERROR_ITEM_NOT_FOUND; ops = attr_ops + type_props->type_attrs[idx].ops_index; attr = (uint8_t *)o->attr + type_props->type_attrs[idx].raw_offs; return ops->to_user(attr, sess, buffer, size); } void tee_obj_attr_free(struct tee_obj *o) { const struct tee_cryp_obj_type_props *tp; size_t n; if (!o->attr) return; tp = tee_svc_find_type_props(o->info.objectType); if (!tp) return; for (n = 0; n < tp->num_type_attrs; n++) { const struct tee_cryp_obj_type_attrs *ta = tp->type_attrs + n; attr_ops[ta->ops_index].free((uint8_t *)o->attr + ta->raw_offs); } } void tee_obj_attr_clear(struct tee_obj *o) { const struct tee_cryp_obj_type_props *tp; size_t n; if (!o->attr) return; tp = tee_svc_find_type_props(o->info.objectType); if (!tp) return; for (n = 0; n < tp->num_type_attrs; n++) { const struct tee_cryp_obj_type_attrs *ta = tp->type_attrs + n; attr_ops[ta->ops_index].clear((uint8_t *)o->attr + ta->raw_offs); } } TEE_Result tee_obj_attr_to_binary(struct tee_obj *o, void *data, size_t *data_len) { const struct tee_cryp_obj_type_props *tp; size_t n; size_t offs = 0; size_t len = data ? *data_len : 0; TEE_Result res; if (o->info.objectType == TEE_TYPE_DATA) { *data_len = 0; return TEE_SUCCESS; /* pure data object */ } if (!o->attr) return TEE_ERROR_BAD_STATE; tp = tee_svc_find_type_props(o->info.objectType); if (!tp) return TEE_ERROR_BAD_STATE; for (n = 0; n < tp->num_type_attrs; n++) { const struct tee_cryp_obj_type_attrs *ta = tp->type_attrs + n; void *attr = (uint8_t *)o->attr + ta->raw_offs; res = attr_ops[ta->ops_index].to_binary(attr, data, len, &offs); if (res != TEE_SUCCESS) return res; } *data_len = offs; if (data && offs > len) return TEE_ERROR_SHORT_BUFFER; return TEE_SUCCESS; } TEE_Result tee_obj_attr_from_binary(struct tee_obj *o, const void *data, size_t data_len) { const struct tee_cryp_obj_type_props *tp; size_t n; size_t offs = 0; if (o->info.objectType == TEE_TYPE_DATA) return TEE_SUCCESS; /* pure data object */ if (!o->attr) return TEE_ERROR_BAD_STATE; tp = tee_svc_find_type_props(o->info.objectType); if (!tp) return TEE_ERROR_BAD_STATE; for (n = 0; n < tp->num_type_attrs; n++) { const struct tee_cryp_obj_type_attrs *ta = tp->type_attrs + n; void *attr = (uint8_t *)o->attr + ta->raw_offs; if (!attr_ops[ta->ops_index].from_binary(attr, data, data_len, &offs)) return TEE_ERROR_CORRUPT_OBJECT; } return TEE_SUCCESS; } TEE_Result tee_obj_attr_copy_from(struct tee_obj *o, const struct tee_obj *src) { TEE_Result res; const struct tee_cryp_obj_type_props *tp; const struct tee_cryp_obj_type_attrs *ta; size_t n; uint32_t have_attrs = 0; void *attr; void *src_attr; if (o->info.objectType == TEE_TYPE_DATA) return TEE_SUCCESS; /* pure data object */ if (!o->attr) return TEE_ERROR_BAD_STATE; tp = tee_svc_find_type_props(o->info.objectType); if (!tp) return TEE_ERROR_BAD_STATE; if (o->info.objectType == src->info.objectType) { have_attrs = src->have_attrs; for (n = 0; n < tp->num_type_attrs; n++) { ta = tp->type_attrs + n; attr = (uint8_t *)o->attr + ta->raw_offs; src_attr = (uint8_t *)src->attr + ta->raw_offs; res = attr_ops[ta->ops_index].from_obj(attr, src_attr); if (res != TEE_SUCCESS) return res; } } else { const struct tee_cryp_obj_type_props *tp_src; int idx; if (o->info.objectType == TEE_TYPE_RSA_PUBLIC_KEY) { if (src->info.objectType != TEE_TYPE_RSA_KEYPAIR) return TEE_ERROR_BAD_PARAMETERS; } else if (o->info.objectType == TEE_TYPE_DSA_PUBLIC_KEY) { if (src->info.objectType != TEE_TYPE_DSA_KEYPAIR) return TEE_ERROR_BAD_PARAMETERS; } else if (o->info.objectType == TEE_TYPE_ECDSA_PUBLIC_KEY) { if (src->info.objectType != TEE_TYPE_ECDSA_KEYPAIR) return TEE_ERROR_BAD_PARAMETERS; } else if (o->info.objectType == TEE_TYPE_ECDH_PUBLIC_KEY) { if (src->info.objectType != TEE_TYPE_ECDH_KEYPAIR) return TEE_ERROR_BAD_PARAMETERS; } else { return TEE_ERROR_BAD_PARAMETERS; } tp_src = tee_svc_find_type_props(src->info.objectType); if (!tp_src) return TEE_ERROR_BAD_STATE; have_attrs = BIT32(tp->num_type_attrs) - 1; for (n = 0; n < tp->num_type_attrs; n++) { ta = tp->type_attrs + n; idx = tee_svc_cryp_obj_find_type_attr_idx(ta->attr_id, tp_src); if (idx < 0) return TEE_ERROR_BAD_STATE; attr = (uint8_t *)o->attr + ta->raw_offs; src_attr = (uint8_t *)src->attr + tp_src->type_attrs[idx].raw_offs; res = attr_ops[ta->ops_index].from_obj(attr, src_attr); if (res != TEE_SUCCESS) return res; } } o->have_attrs = have_attrs; return TEE_SUCCESS; } TEE_Result tee_obj_set_type(struct tee_obj *o, uint32_t obj_type, size_t max_key_size) { TEE_Result res = TEE_SUCCESS; const struct tee_cryp_obj_type_props *type_props; /* Can only set type for newly allocated objs */ if (o->attr) return TEE_ERROR_BAD_STATE; /* * Verify that maxKeySize is supported and find out how * much should be allocated. */ if (obj_type == TEE_TYPE_DATA) { if (max_key_size) return TEE_ERROR_NOT_SUPPORTED; } else { /* Find description of object */ type_props = tee_svc_find_type_props(obj_type); if (!type_props) return TEE_ERROR_NOT_SUPPORTED; /* Check that maxKeySize follows restrictions */ if (max_key_size % type_props->quanta != 0) return TEE_ERROR_NOT_SUPPORTED; if (max_key_size < type_props->min_size) return TEE_ERROR_NOT_SUPPORTED; if (max_key_size > type_props->max_size) return TEE_ERROR_NOT_SUPPORTED; o->attr = calloc(1, type_props->alloc_size); if (!o->attr) return TEE_ERROR_OUT_OF_MEMORY; } /* If we have a key structure, pre-allocate the bignums inside */ switch (obj_type) { case TEE_TYPE_RSA_PUBLIC_KEY: res = crypto_acipher_alloc_rsa_public_key(o->attr, max_key_size); break; case TEE_TYPE_RSA_KEYPAIR: res = crypto_acipher_alloc_rsa_keypair(o->attr, max_key_size); break; case TEE_TYPE_DSA_PUBLIC_KEY: res = crypto_acipher_alloc_dsa_public_key(o->attr, max_key_size); break; case TEE_TYPE_DSA_KEYPAIR: res = crypto_acipher_alloc_dsa_keypair(o->attr, max_key_size); break; case TEE_TYPE_DH_KEYPAIR: res = crypto_acipher_alloc_dh_keypair(o->attr, max_key_size); break; case TEE_TYPE_ECDSA_PUBLIC_KEY: case TEE_TYPE_ECDH_PUBLIC_KEY: res = crypto_acipher_alloc_ecc_public_key(o->attr, max_key_size); break; case TEE_TYPE_ECDSA_KEYPAIR: case TEE_TYPE_ECDH_KEYPAIR: res = crypto_acipher_alloc_ecc_keypair(o->attr, max_key_size); break; default: if (obj_type != TEE_TYPE_DATA) { struct tee_cryp_obj_secret *key = o->attr; key->alloc_size = type_props->alloc_size - sizeof(*key); } break; } if (res != TEE_SUCCESS) return res; o->info.objectType = obj_type; o->info.maxKeySize = max_key_size; o->info.objectUsage = TEE_USAGE_DEFAULT; return TEE_SUCCESS; } TEE_Result syscall_cryp_obj_alloc(unsigned long obj_type, unsigned long max_key_size, uint32_t *obj) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; if (obj_type == TEE_TYPE_DATA) return TEE_ERROR_NOT_SUPPORTED; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; o = tee_obj_alloc(); if (!o) return TEE_ERROR_OUT_OF_MEMORY; res = tee_obj_set_type(o, obj_type, max_key_size); if (res != TEE_SUCCESS) { tee_obj_free(o); return res; } tee_obj_add(to_user_ta_ctx(sess->ctx), o); res = tee_svc_copy_kaddr_to_uref(obj, o); if (res != TEE_SUCCESS) tee_obj_close(to_user_ta_ctx(sess->ctx), o); return res; } TEE_Result syscall_cryp_obj_close(unsigned long obj) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) return res; /* * If it's busy it's used by an operation, a client should never have * this handle. */ if (o->busy) return TEE_ERROR_ITEM_NOT_FOUND; tee_obj_close(to_user_ta_ctx(sess->ctx), o); return TEE_SUCCESS; } TEE_Result syscall_cryp_obj_reset(unsigned long obj) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) return res; if ((o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) == 0) { tee_obj_attr_clear(o); o->info.keySize = 0; o->info.objectUsage = TEE_USAGE_DEFAULT; } else { return TEE_ERROR_BAD_PARAMETERS; } /* the object is no more initialized */ o->info.handleFlags &= ~TEE_HANDLE_FLAG_INITIALIZED; return TEE_SUCCESS; } static TEE_Result copy_in_attrs(struct user_ta_ctx *utc, const struct utee_attribute *usr_attrs, uint32_t attr_count, TEE_Attribute *attrs) { TEE_Result res; uint32_t n; res = tee_mmu_check_access_rights(utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)usr_attrs, attr_count * sizeof(struct utee_attribute)); if (res != TEE_SUCCESS) return res; for (n = 0; n < attr_count; n++) { attrs[n].attributeID = usr_attrs[n].attribute_id; if (attrs[n].attributeID & TEE_ATTR_BIT_VALUE) { attrs[n].content.value.a = usr_attrs[n].a; attrs[n].content.value.b = usr_attrs[n].b; } else { uintptr_t buf = usr_attrs[n].a; size_t len = usr_attrs[n].b; res = tee_mmu_check_access_rights(utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, buf, len); if (res != TEE_SUCCESS) return res; attrs[n].content.ref.buffer = (void *)buf; attrs[n].content.ref.length = len; } } return TEE_SUCCESS; } enum attr_usage { ATTR_USAGE_POPULATE, ATTR_USAGE_GENERATE_KEY }; static TEE_Result tee_svc_cryp_check_attr(enum attr_usage usage, const struct tee_cryp_obj_type_props *type_props, const TEE_Attribute *attrs, uint32_t attr_count) { uint32_t required_flag; uint32_t opt_flag; bool all_opt_needed; uint32_t req_attrs = 0; uint32_t opt_grp_attrs = 0; uint32_t attrs_found = 0; size_t n; uint32_t bit; uint32_t flags; int idx; if (usage == ATTR_USAGE_POPULATE) { required_flag = TEE_TYPE_ATTR_REQUIRED; opt_flag = TEE_TYPE_ATTR_OPTIONAL_GROUP; all_opt_needed = true; } else { required_flag = TEE_TYPE_ATTR_GEN_KEY_REQ; opt_flag = TEE_TYPE_ATTR_GEN_KEY_OPT; all_opt_needed = false; } /* * First find out which attributes are required and which belong to * the optional group */ for (n = 0; n < type_props->num_type_attrs; n++) { bit = 1 << n; flags = type_props->type_attrs[n].flags; if (flags & required_flag) req_attrs |= bit; else if (flags & opt_flag) opt_grp_attrs |= bit; } /* * Verify that all required attributes are in place and * that the same attribute isn't repeated. */ for (n = 0; n < attr_count; n++) { idx = tee_svc_cryp_obj_find_type_attr_idx( attrs[n].attributeID, type_props); /* attribute not defined in current object type */ if (idx < 0) return TEE_ERROR_ITEM_NOT_FOUND; bit = 1 << idx; /* attribute not repeated */ if ((attrs_found & bit) != 0) return TEE_ERROR_ITEM_NOT_FOUND; attrs_found |= bit; } /* Required attribute missing */ if ((attrs_found & req_attrs) != req_attrs) return TEE_ERROR_ITEM_NOT_FOUND; /* * If the flag says that "if one of the optional attributes are included * all of them has to be included" this must be checked. */ if (all_opt_needed && (attrs_found & opt_grp_attrs) != 0 && (attrs_found & opt_grp_attrs) != opt_grp_attrs) return TEE_ERROR_ITEM_NOT_FOUND; return TEE_SUCCESS; } static TEE_Result get_ec_key_size(uint32_t curve, size_t *key_size) { switch (curve) { case TEE_ECC_CURVE_NIST_P192: *key_size = 192; break; case TEE_ECC_CURVE_NIST_P224: *key_size = 224; break; case TEE_ECC_CURVE_NIST_P256: *key_size = 256; break; case TEE_ECC_CURVE_NIST_P384: *key_size = 384; break; case TEE_ECC_CURVE_NIST_P521: *key_size = 521; break; default: return TEE_ERROR_NOT_SUPPORTED; } return TEE_SUCCESS; } static TEE_Result tee_svc_cryp_obj_populate_type( struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props, const TEE_Attribute *attrs, uint32_t attr_count) { TEE_Result res; uint32_t have_attrs = 0; size_t obj_size = 0; size_t n; int idx; const struct attr_ops *ops; void *attr; for (n = 0; n < attr_count; n++) { idx = tee_svc_cryp_obj_find_type_attr_idx( attrs[n].attributeID, type_props); /* attribute not defined in current object type */ if (idx < 0) return TEE_ERROR_ITEM_NOT_FOUND; have_attrs |= BIT32(idx); ops = attr_ops + type_props->type_attrs[idx].ops_index; attr = (uint8_t *)o->attr + type_props->type_attrs[idx].raw_offs; if (attrs[n].attributeID & TEE_ATTR_BIT_VALUE) res = ops->from_user(attr, &attrs[n].content.value, sizeof(attrs[n].content.value)); else res = ops->from_user(attr, attrs[n].content.ref.buffer, attrs[n].content.ref.length); if (res != TEE_SUCCESS) return res; /* * First attr_idx signifies the attribute that gives the size * of the object */ if (type_props->type_attrs[idx].flags & TEE_TYPE_ATTR_SIZE_INDICATOR) { /* * For ECDSA/ECDH we need to translate curve into * object size */ if (attrs[n].attributeID == TEE_ATTR_ECC_CURVE) { res = get_ec_key_size(attrs[n].content.value.a, &obj_size); if (res != TEE_SUCCESS) return res; } else { obj_size += (attrs[n].content.ref.length * 8); } } } /* * We have to do it like this because the parity bits aren't counted * when telling the size of the key in bits. */ if (o->info.objectType == TEE_TYPE_DES || o->info.objectType == TEE_TYPE_DES3) obj_size -= obj_size / 8; /* Exclude parity in size of key */ o->have_attrs = have_attrs; o->info.keySize = obj_size; return TEE_SUCCESS; } TEE_Result syscall_cryp_obj_populate(unsigned long obj, struct utee_attribute *usr_attrs, unsigned long attr_count) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; const struct tee_cryp_obj_type_props *type_props; TEE_Attribute *attrs = NULL; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) return res; /* Must be a transient object */ if ((o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) != 0) return TEE_ERROR_BAD_PARAMETERS; /* Must not be initialized already */ if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) != 0) return TEE_ERROR_BAD_PARAMETERS; type_props = tee_svc_find_type_props(o->info.objectType); if (!type_props) return TEE_ERROR_NOT_IMPLEMENTED; size_t alloc_size = 0; if (MUL_OVERFLOW(sizeof(TEE_Attribute), attr_count, &alloc_size)) return TEE_ERROR_OVERFLOW; attrs = malloc(alloc_size); if (!attrs) return TEE_ERROR_OUT_OF_MEMORY; res = copy_in_attrs(to_user_ta_ctx(sess->ctx), usr_attrs, attr_count, attrs); if (res != TEE_SUCCESS) goto out; res = tee_svc_cryp_check_attr(ATTR_USAGE_POPULATE, type_props, attrs, attr_count); if (res != TEE_SUCCESS) goto out; res = tee_svc_cryp_obj_populate_type(o, type_props, attrs, attr_count); if (res == TEE_SUCCESS) o->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; out: free(attrs); return res; } TEE_Result syscall_cryp_obj_copy(unsigned long dst, unsigned long src) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *dst_o; struct tee_obj *src_o; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(dst), &dst_o); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(src), &src_o); if (res != TEE_SUCCESS) return res; if ((src_o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) return TEE_ERROR_BAD_PARAMETERS; if ((dst_o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) != 0) return TEE_ERROR_BAD_PARAMETERS; if ((dst_o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) != 0) return TEE_ERROR_BAD_PARAMETERS; res = tee_obj_attr_copy_from(dst_o, src_o); if (res != TEE_SUCCESS) return res; dst_o->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; dst_o->info.keySize = src_o->info.keySize; dst_o->info.objectUsage = src_o->info.objectUsage; return TEE_SUCCESS; } static TEE_Result tee_svc_obj_generate_key_rsa( struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props, uint32_t key_size, const TEE_Attribute *params, uint32_t param_count) { TEE_Result res; struct rsa_keypair *key = o->attr; uint32_t e = TEE_U32_TO_BIG_ENDIAN(65537); /* Copy the present attributes into the obj before starting */ res = tee_svc_cryp_obj_populate_type(o, type_props, params, param_count); if (res != TEE_SUCCESS) return res; if (!get_attribute(o, type_props, TEE_ATTR_RSA_PUBLIC_EXPONENT)) crypto_bignum_bin2bn((const uint8_t *)&e, sizeof(e), key->e); res = crypto_acipher_gen_rsa_key(key, key_size); if (res != TEE_SUCCESS) return res; /* Set bits for all known attributes for this object type */ o->have_attrs = (1 << type_props->num_type_attrs) - 1; return TEE_SUCCESS; } static TEE_Result tee_svc_obj_generate_key_dsa( struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props, uint32_t key_size) { TEE_Result res; res = crypto_acipher_gen_dsa_key(o->attr, key_size); if (res != TEE_SUCCESS) return res; /* Set bits for all known attributes for this object type */ o->have_attrs = (1 << type_props->num_type_attrs) - 1; return TEE_SUCCESS; } static TEE_Result tee_svc_obj_generate_key_dh( struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props, uint32_t key_size __unused, const TEE_Attribute *params, uint32_t param_count) { TEE_Result res; struct dh_keypair *tee_dh_key; struct bignum *dh_q = NULL; uint32_t dh_xbits = 0; /* Copy the present attributes into the obj before starting */ res = tee_svc_cryp_obj_populate_type(o, type_props, params, param_count); if (res != TEE_SUCCESS) return res; tee_dh_key = (struct dh_keypair *)o->attr; if (get_attribute(o, type_props, TEE_ATTR_DH_SUBPRIME)) dh_q = tee_dh_key->q; if (get_attribute(o, type_props, TEE_ATTR_DH_X_BITS)) dh_xbits = tee_dh_key->xbits; res = crypto_acipher_gen_dh_key(tee_dh_key, dh_q, dh_xbits); if (res != TEE_SUCCESS) return res; /* Set bits for the generated public and private key */ set_attribute(o, type_props, TEE_ATTR_DH_PUBLIC_VALUE); set_attribute(o, type_props, TEE_ATTR_DH_PRIVATE_VALUE); set_attribute(o, type_props, TEE_ATTR_DH_X_BITS); return TEE_SUCCESS; } static TEE_Result tee_svc_obj_generate_key_ecc( struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props, uint32_t key_size __unused, const TEE_Attribute *params, uint32_t param_count) { TEE_Result res; struct ecc_keypair *tee_ecc_key; /* Copy the present attributes into the obj before starting */ res = tee_svc_cryp_obj_populate_type(o, type_props, params, param_count); if (res != TEE_SUCCESS) return res; tee_ecc_key = (struct ecc_keypair *)o->attr; res = crypto_acipher_gen_ecc_key(tee_ecc_key); if (res != TEE_SUCCESS) return res; /* Set bits for the generated public and private key */ set_attribute(o, type_props, TEE_ATTR_ECC_PRIVATE_VALUE); set_attribute(o, type_props, TEE_ATTR_ECC_PUBLIC_VALUE_X); set_attribute(o, type_props, TEE_ATTR_ECC_PUBLIC_VALUE_Y); set_attribute(o, type_props, TEE_ATTR_ECC_CURVE); return TEE_SUCCESS; } TEE_Result syscall_obj_generate_key(unsigned long obj, unsigned long key_size, const struct utee_attribute *usr_params, unsigned long param_count) { TEE_Result res; struct tee_ta_session *sess; const struct tee_cryp_obj_type_props *type_props; struct tee_obj *o; struct tee_cryp_obj_secret *key; size_t byte_size; TEE_Attribute *params = NULL; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) return res; /* Must be a transient object */ if ((o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) != 0) return TEE_ERROR_BAD_STATE; /* Must not be initialized already */ if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) != 0) return TEE_ERROR_BAD_STATE; /* Find description of object */ type_props = tee_svc_find_type_props(o->info.objectType); if (!type_props) return TEE_ERROR_NOT_SUPPORTED; /* Check that maxKeySize follows restrictions */ if (key_size % type_props->quanta != 0) return TEE_ERROR_NOT_SUPPORTED; if (key_size < type_props->min_size) return TEE_ERROR_NOT_SUPPORTED; if (key_size > type_props->max_size) return TEE_ERROR_NOT_SUPPORTED; params = malloc(sizeof(TEE_Attribute) * param_count); if (!params) return TEE_ERROR_OUT_OF_MEMORY; res = copy_in_attrs(to_user_ta_ctx(sess->ctx), usr_params, param_count, params); if (res != TEE_SUCCESS) goto out; res = tee_svc_cryp_check_attr(ATTR_USAGE_GENERATE_KEY, type_props, params, param_count); if (res != TEE_SUCCESS) goto out; switch (o->info.objectType) { case TEE_TYPE_AES: case TEE_TYPE_DES: case TEE_TYPE_DES3: case TEE_TYPE_HMAC_MD5: case TEE_TYPE_HMAC_SHA1: case TEE_TYPE_HMAC_SHA224: case TEE_TYPE_HMAC_SHA256: case TEE_TYPE_HMAC_SHA384: case TEE_TYPE_HMAC_SHA512: case TEE_TYPE_GENERIC_SECRET: byte_size = key_size / 8; /* * We have to do it like this because the parity bits aren't * counted when telling the size of the key in bits. */ if (o->info.objectType == TEE_TYPE_DES || o->info.objectType == TEE_TYPE_DES3) { byte_size = (key_size + key_size / 7) / 8; } key = (struct tee_cryp_obj_secret *)o->attr; if (byte_size > key->alloc_size) { res = TEE_ERROR_EXCESS_DATA; goto out; } res = crypto_rng_read((void *)(key + 1), byte_size); if (res != TEE_SUCCESS) goto out; key->key_size = byte_size; /* Set bits for all known attributes for this object type */ o->have_attrs = (1 << type_props->num_type_attrs) - 1; break; case TEE_TYPE_RSA_KEYPAIR: res = tee_svc_obj_generate_key_rsa(o, type_props, key_size, params, param_count); if (res != TEE_SUCCESS) goto out; break; case TEE_TYPE_DSA_KEYPAIR: res = tee_svc_obj_generate_key_dsa(o, type_props, key_size); if (res != TEE_SUCCESS) goto out; break; case TEE_TYPE_DH_KEYPAIR: res = tee_svc_obj_generate_key_dh(o, type_props, key_size, params, param_count); if (res != TEE_SUCCESS) goto out; break; case TEE_TYPE_ECDSA_KEYPAIR: case TEE_TYPE_ECDH_KEYPAIR: res = tee_svc_obj_generate_key_ecc(o, type_props, key_size, params, param_count); if (res != TEE_SUCCESS) goto out; break; default: res = TEE_ERROR_BAD_FORMAT; } out: free(params); if (res == TEE_SUCCESS) { o->info.keySize = key_size; o->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; } return res; } static TEE_Result tee_svc_cryp_get_state(struct tee_ta_session *sess, uint32_t state_id, struct tee_cryp_state **state) { struct tee_cryp_state *s; struct user_ta_ctx *utc = to_user_ta_ctx(sess->ctx); TAILQ_FOREACH(s, &utc->cryp_states, link) { if (state_id == (vaddr_t)s) { *state = s; return TEE_SUCCESS; } } return TEE_ERROR_BAD_PARAMETERS; } static void cryp_state_free(struct user_ta_ctx *utc, struct tee_cryp_state *cs) { struct tee_obj *o; if (tee_obj_get(utc, cs->key1, &o) == TEE_SUCCESS) tee_obj_close(utc, o); if (tee_obj_get(utc, cs->key2, &o) == TEE_SUCCESS) tee_obj_close(utc, o); TAILQ_REMOVE(&utc->cryp_states, cs, link); if (cs->ctx_finalize != NULL) cs->ctx_finalize(cs->ctx, cs->algo); switch (TEE_ALG_GET_CLASS(cs->algo)) { case TEE_OPERATION_CIPHER: crypto_cipher_free_ctx(cs->ctx, cs->algo); break; case TEE_OPERATION_AE: crypto_authenc_free_ctx(cs->ctx, cs->algo); break; case TEE_OPERATION_DIGEST: crypto_hash_free_ctx(cs->ctx, cs->algo); break; case TEE_OPERATION_MAC: crypto_mac_free_ctx(cs->ctx, cs->algo); break; default: assert(!cs->ctx); } free(cs); } static TEE_Result tee_svc_cryp_check_key_type(const struct tee_obj *o, uint32_t algo, TEE_OperationMode mode) { uint32_t req_key_type; uint32_t req_key_type2 = 0; switch (TEE_ALG_GET_MAIN_ALG(algo)) { case TEE_MAIN_ALGO_MD5: req_key_type = TEE_TYPE_HMAC_MD5; break; case TEE_MAIN_ALGO_SHA1: req_key_type = TEE_TYPE_HMAC_SHA1; break; case TEE_MAIN_ALGO_SHA224: req_key_type = TEE_TYPE_HMAC_SHA224; break; case TEE_MAIN_ALGO_SHA256: req_key_type = TEE_TYPE_HMAC_SHA256; break; case TEE_MAIN_ALGO_SHA384: req_key_type = TEE_TYPE_HMAC_SHA384; break; case TEE_MAIN_ALGO_SHA512: req_key_type = TEE_TYPE_HMAC_SHA512; break; case TEE_MAIN_ALGO_AES: req_key_type = TEE_TYPE_AES; break; case TEE_MAIN_ALGO_DES: req_key_type = TEE_TYPE_DES; break; case TEE_MAIN_ALGO_DES3: req_key_type = TEE_TYPE_DES3; break; case TEE_MAIN_ALGO_RSA: req_key_type = TEE_TYPE_RSA_KEYPAIR; if (mode == TEE_MODE_ENCRYPT || mode == TEE_MODE_VERIFY) req_key_type2 = TEE_TYPE_RSA_PUBLIC_KEY; break; case TEE_MAIN_ALGO_DSA: req_key_type = TEE_TYPE_DSA_KEYPAIR; if (mode == TEE_MODE_ENCRYPT || mode == TEE_MODE_VERIFY) req_key_type2 = TEE_TYPE_DSA_PUBLIC_KEY; break; case TEE_MAIN_ALGO_DH: req_key_type = TEE_TYPE_DH_KEYPAIR; break; case TEE_MAIN_ALGO_ECDSA: req_key_type = TEE_TYPE_ECDSA_KEYPAIR; if (mode == TEE_MODE_VERIFY) req_key_type2 = TEE_TYPE_ECDSA_PUBLIC_KEY; break; case TEE_MAIN_ALGO_ECDH: req_key_type = TEE_TYPE_ECDH_KEYPAIR; break; #if defined(CFG_CRYPTO_HKDF) case TEE_MAIN_ALGO_HKDF: req_key_type = TEE_TYPE_HKDF_IKM; break; #endif #if defined(CFG_CRYPTO_CONCAT_KDF) case TEE_MAIN_ALGO_CONCAT_KDF: req_key_type = TEE_TYPE_CONCAT_KDF_Z; break; #endif #if defined(CFG_CRYPTO_PBKDF2) case TEE_MAIN_ALGO_PBKDF2: req_key_type = TEE_TYPE_PBKDF2_PASSWORD; break; #endif default: return TEE_ERROR_BAD_PARAMETERS; } if (req_key_type != o->info.objectType && req_key_type2 != o->info.objectType) return TEE_ERROR_BAD_PARAMETERS; return TEE_SUCCESS; } TEE_Result syscall_cryp_state_alloc(unsigned long algo, unsigned long mode, unsigned long key1, unsigned long key2, uint32_t *state) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; struct tee_obj *o1 = NULL; struct tee_obj *o2 = NULL; struct user_ta_ctx *utc; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; utc = to_user_ta_ctx(sess->ctx); if (key1 != 0) { res = tee_obj_get(utc, tee_svc_uref_to_vaddr(key1), &o1); if (res != TEE_SUCCESS) return res; if (o1->busy) return TEE_ERROR_BAD_PARAMETERS; res = tee_svc_cryp_check_key_type(o1, algo, mode); if (res != TEE_SUCCESS) return res; } if (key2 != 0) { res = tee_obj_get(utc, tee_svc_uref_to_vaddr(key2), &o2); if (res != TEE_SUCCESS) return res; if (o2->busy) return TEE_ERROR_BAD_PARAMETERS; res = tee_svc_cryp_check_key_type(o2, algo, mode); if (res != TEE_SUCCESS) return res; } cs = calloc(1, sizeof(struct tee_cryp_state)); if (!cs) return TEE_ERROR_OUT_OF_MEMORY; TAILQ_INSERT_TAIL(&utc->cryp_states, cs, link); cs->algo = algo; cs->mode = mode; switch (TEE_ALG_GET_CLASS(algo)) { case TEE_OPERATION_EXTENSION: #ifdef CFG_CRYPTO_RSASSA_NA1 if (algo == TEE_ALG_RSASSA_PKCS1_V1_5) goto rsassa_na1; #endif res = TEE_ERROR_NOT_SUPPORTED; break; case TEE_OPERATION_CIPHER: if ((algo == TEE_ALG_AES_XTS && (key1 == 0 || key2 == 0)) || (algo != TEE_ALG_AES_XTS && (key1 == 0 || key2 != 0))) { res = TEE_ERROR_BAD_PARAMETERS; } else { res = crypto_cipher_alloc_ctx(&cs->ctx, algo); if (res != TEE_SUCCESS) break; } break; case TEE_OPERATION_AE: if (key1 == 0 || key2 != 0) { res = TEE_ERROR_BAD_PARAMETERS; } else { res = crypto_authenc_alloc_ctx(&cs->ctx, algo); if (res != TEE_SUCCESS) break; } break; case TEE_OPERATION_MAC: if (key1 == 0 || key2 != 0) { res = TEE_ERROR_BAD_PARAMETERS; } else { res = crypto_mac_alloc_ctx(&cs->ctx, algo); if (res != TEE_SUCCESS) break; } break; case TEE_OPERATION_DIGEST: if (key1 != 0 || key2 != 0) { res = TEE_ERROR_BAD_PARAMETERS; } else { res = crypto_hash_alloc_ctx(&cs->ctx, algo); if (res != TEE_SUCCESS) break; } break; case TEE_OPERATION_ASYMMETRIC_CIPHER: case TEE_OPERATION_ASYMMETRIC_SIGNATURE: rsassa_na1: __maybe_unused if (key1 == 0 || key2 != 0) res = TEE_ERROR_BAD_PARAMETERS; break; case TEE_OPERATION_KEY_DERIVATION: if (key1 == 0 || key2 != 0) res = TEE_ERROR_BAD_PARAMETERS; break; default: res = TEE_ERROR_NOT_SUPPORTED; break; } if (res != TEE_SUCCESS) goto out; res = tee_svc_copy_kaddr_to_uref(state, cs); if (res != TEE_SUCCESS) goto out; /* Register keys */ if (o1 != NULL) { o1->busy = true; cs->key1 = (vaddr_t)o1; } if (o2 != NULL) { o2->busy = true; cs->key2 = (vaddr_t)o2; } out: if (res != TEE_SUCCESS) cryp_state_free(utc, cs); return res; } TEE_Result syscall_cryp_state_copy(unsigned long dst, unsigned long src) { TEE_Result res; struct tee_cryp_state *cs_dst; struct tee_cryp_state *cs_src; struct tee_ta_session *sess; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(dst), &cs_dst); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(src), &cs_src); if (res != TEE_SUCCESS) return res; if (cs_dst->algo != cs_src->algo || cs_dst->mode != cs_src->mode) return TEE_ERROR_BAD_PARAMETERS; switch (TEE_ALG_GET_CLASS(cs_src->algo)) { case TEE_OPERATION_CIPHER: crypto_cipher_copy_state(cs_dst->ctx, cs_src->ctx, cs_src->algo); break; case TEE_OPERATION_AE: crypto_authenc_copy_state(cs_dst->ctx, cs_src->ctx, cs_src->algo); break; case TEE_OPERATION_DIGEST: crypto_hash_copy_state(cs_dst->ctx, cs_src->ctx, cs_src->algo); break; case TEE_OPERATION_MAC: crypto_mac_copy_state(cs_dst->ctx, cs_src->ctx, cs_src->algo); break; default: return TEE_ERROR_BAD_STATE; } return TEE_SUCCESS; } void tee_svc_cryp_free_states(struct user_ta_ctx *utc) { struct tee_cryp_state_head *states = &utc->cryp_states; while (!TAILQ_EMPTY(states)) cryp_state_free(utc, TAILQ_FIRST(states)); } TEE_Result syscall_cryp_state_free(unsigned long state) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; cryp_state_free(to_user_ta_ctx(sess->ctx), cs); return TEE_SUCCESS; } TEE_Result syscall_hash_init(unsigned long state, const void *iv __maybe_unused, size_t iv_len __maybe_unused) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; switch (TEE_ALG_GET_CLASS(cs->algo)) { case TEE_OPERATION_DIGEST: res = crypto_hash_init(cs->ctx, cs->algo); if (res != TEE_SUCCESS) return res; break; case TEE_OPERATION_MAC: { struct tee_obj *o; struct tee_cryp_obj_secret *key; res = tee_obj_get(to_user_ta_ctx(sess->ctx), cs->key1, &o); if (res != TEE_SUCCESS) return res; if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) return TEE_ERROR_BAD_PARAMETERS; key = (struct tee_cryp_obj_secret *)o->attr; res = crypto_mac_init(cs->ctx, cs->algo, (void *)(key + 1), key->key_size); if (res != TEE_SUCCESS) return res; break; } default: return TEE_ERROR_BAD_PARAMETERS; } return TEE_SUCCESS; } TEE_Result syscall_hash_update(unsigned long state, const void *chunk, size_t chunk_size) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; /* No data, but size provided isn't valid parameters. */ if (!chunk && chunk_size) return TEE_ERROR_BAD_PARAMETERS; /* Zero length hash is valid, but nothing we need to do. */ if (!chunk_size) return TEE_SUCCESS; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)chunk, chunk_size); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; switch (TEE_ALG_GET_CLASS(cs->algo)) { case TEE_OPERATION_DIGEST: res = crypto_hash_update(cs->ctx, cs->algo, chunk, chunk_size); if (res != TEE_SUCCESS) return res; break; case TEE_OPERATION_MAC: res = crypto_mac_update(cs->ctx, cs->algo, chunk, chunk_size); if (res != TEE_SUCCESS) return res; break; default: return TEE_ERROR_BAD_PARAMETERS; } return TEE_SUCCESS; } TEE_Result syscall_hash_final(unsigned long state, const void *chunk, size_t chunk_size, void *hash, uint64_t *hash_len) { TEE_Result res, res2; size_t hash_size; uint64_t hlen; struct tee_cryp_state *cs; struct tee_ta_session *sess; /* No data, but size provided isn't valid parameters. */ if (!chunk && chunk_size) return TEE_ERROR_BAD_PARAMETERS; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)chunk, chunk_size); if (res != TEE_SUCCESS) return res; res = tee_svc_copy_from_user(&hlen, hash_len, sizeof(hlen)); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)hash, hlen); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; switch (TEE_ALG_GET_CLASS(cs->algo)) { case TEE_OPERATION_DIGEST: res = tee_hash_get_digest_size(cs->algo, &hash_size); if (res != TEE_SUCCESS) return res; if (*hash_len < hash_size) { res = TEE_ERROR_SHORT_BUFFER; goto out; } if (chunk_size) { res = crypto_hash_update(cs->ctx, cs->algo, chunk, chunk_size); if (res != TEE_SUCCESS) return res; } res = crypto_hash_final(cs->ctx, cs->algo, hash, hash_size); if (res != TEE_SUCCESS) return res; break; case TEE_OPERATION_MAC: res = tee_mac_get_digest_size(cs->algo, &hash_size); if (res != TEE_SUCCESS) return res; if (*hash_len < hash_size) { res = TEE_ERROR_SHORT_BUFFER; goto out; } if (chunk_size) { res = crypto_mac_update(cs->ctx, cs->algo, chunk, chunk_size); if (res != TEE_SUCCESS) return res; } res = crypto_mac_final(cs->ctx, cs->algo, hash, hash_size); if (res != TEE_SUCCESS) return res; break; default: return TEE_ERROR_BAD_PARAMETERS; } out: hlen = hash_size; res2 = tee_svc_copy_to_user(hash_len, &hlen, sizeof(*hash_len)); if (res2 != TEE_SUCCESS) return res2; return res; } TEE_Result syscall_cipher_init(unsigned long state, const void *iv, size_t iv_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; struct tee_obj *o; struct tee_cryp_obj_secret *key1; struct user_ta_ctx *utc; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; utc = to_user_ta_ctx(sess->ctx); res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t) iv, iv_len); if (res != TEE_SUCCESS) return res; res = tee_obj_get(utc, cs->key1, &o); if (res != TEE_SUCCESS) return res; if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) return TEE_ERROR_BAD_PARAMETERS; key1 = o->attr; if (tee_obj_get(utc, cs->key2, &o) == TEE_SUCCESS) { struct tee_cryp_obj_secret *key2 = o->attr; if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) return TEE_ERROR_BAD_PARAMETERS; res = crypto_cipher_init(cs->ctx, cs->algo, cs->mode, (uint8_t *)(key1 + 1), key1->key_size, (uint8_t *)(key2 + 1), key2->key_size, iv, iv_len); } else { res = crypto_cipher_init(cs->ctx, cs->algo, cs->mode, (uint8_t *)(key1 + 1), key1->key_size, NULL, 0, iv, iv_len); } if (res != TEE_SUCCESS) return res; cs->ctx_finalize = crypto_cipher_final; return TEE_SUCCESS; } static TEE_Result tee_svc_cipher_update_helper(unsigned long state, bool last_block, const void *src, size_t src_len, void *dst, uint64_t *dst_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; uint64_t dlen; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)src, src_len); if (res != TEE_SUCCESS) return res; if (!dst_len) { dlen = 0; } else { res = tee_svc_copy_from_user(&dlen, dst_len, sizeof(dlen)); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)dst, dlen); if (res != TEE_SUCCESS) return res; } if (dlen < src_len) { res = TEE_ERROR_SHORT_BUFFER; goto out; } if (src_len > 0) { /* Permit src_len == 0 to finalize the operation */ res = tee_do_cipher_update(cs->ctx, cs->algo, cs->mode, last_block, src, src_len, dst); } if (last_block && cs->ctx_finalize != NULL) { cs->ctx_finalize(cs->ctx, cs->algo); cs->ctx_finalize = NULL; } out: if ((res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) && dst_len != NULL) { TEE_Result res2; dlen = src_len; res2 = tee_svc_copy_to_user(dst_len, &dlen, sizeof(*dst_len)); if (res2 != TEE_SUCCESS) res = res2; } return res; } TEE_Result syscall_cipher_update(unsigned long state, const void *src, size_t src_len, void *dst, uint64_t *dst_len) { return tee_svc_cipher_update_helper(state, false /* last_block */, src, src_len, dst, dst_len); } TEE_Result syscall_cipher_final(unsigned long state, const void *src, size_t src_len, void *dst, uint64_t *dst_len) { return tee_svc_cipher_update_helper(state, true /* last_block */, src, src_len, dst, dst_len); } #if defined(CFG_CRYPTO_HKDF) static TEE_Result get_hkdf_params(const TEE_Attribute *params, uint32_t param_count, void **salt, size_t *salt_len, void **info, size_t *info_len, size_t *okm_len) { size_t n; enum { SALT = 0x1, LENGTH = 0x2, INFO = 0x4 }; uint8_t found = 0; *salt = *info = NULL; *salt_len = *info_len = *okm_len = 0; for (n = 0; n < param_count; n++) { switch (params[n].attributeID) { case TEE_ATTR_HKDF_SALT: if (!(found & SALT)) { *salt = params[n].content.ref.buffer; *salt_len = params[n].content.ref.length; found |= SALT; } break; case TEE_ATTR_HKDF_OKM_LENGTH: if (!(found & LENGTH)) { *okm_len = params[n].content.value.a; found |= LENGTH; } break; case TEE_ATTR_HKDF_INFO: if (!(found & INFO)) { *info = params[n].content.ref.buffer; *info_len = params[n].content.ref.length; found |= INFO; } break; default: /* Unexpected attribute */ return TEE_ERROR_BAD_PARAMETERS; } } if (!(found & LENGTH)) return TEE_ERROR_BAD_PARAMETERS; return TEE_SUCCESS; } #endif #if defined(CFG_CRYPTO_CONCAT_KDF) static TEE_Result get_concat_kdf_params(const TEE_Attribute *params, uint32_t param_count, void **other_info, size_t *other_info_len, size_t *derived_key_len) { size_t n; enum { LENGTH = 0x1, INFO = 0x2 }; uint8_t found = 0; *other_info = NULL; *other_info_len = *derived_key_len = 0; for (n = 0; n < param_count; n++) { switch (params[n].attributeID) { case TEE_ATTR_CONCAT_KDF_OTHER_INFO: if (!(found & INFO)) { *other_info = params[n].content.ref.buffer; *other_info_len = params[n].content.ref.length; found |= INFO; } break; case TEE_ATTR_CONCAT_KDF_DKM_LENGTH: if (!(found & LENGTH)) { *derived_key_len = params[n].content.value.a; found |= LENGTH; } break; default: /* Unexpected attribute */ return TEE_ERROR_BAD_PARAMETERS; } } if (!(found & LENGTH)) return TEE_ERROR_BAD_PARAMETERS; return TEE_SUCCESS; } #endif #if defined(CFG_CRYPTO_PBKDF2) static TEE_Result get_pbkdf2_params(const TEE_Attribute *params, uint32_t param_count, void **salt, size_t *salt_len, size_t *derived_key_len, size_t *iteration_count) { size_t n; enum { SALT = 0x1, LENGTH = 0x2, COUNT = 0x4 }; uint8_t found = 0; *salt = NULL; *salt_len = *derived_key_len = *iteration_count = 0; for (n = 0; n < param_count; n++) { switch (params[n].attributeID) { case TEE_ATTR_PBKDF2_SALT: if (!(found & SALT)) { *salt = params[n].content.ref.buffer; *salt_len = params[n].content.ref.length; found |= SALT; } break; case TEE_ATTR_PBKDF2_DKM_LENGTH: if (!(found & LENGTH)) { *derived_key_len = params[n].content.value.a; found |= LENGTH; } break; case TEE_ATTR_PBKDF2_ITERATION_COUNT: if (!(found & COUNT)) { *iteration_count = params[n].content.value.a; found |= COUNT; } break; default: /* Unexpected attribute */ return TEE_ERROR_BAD_PARAMETERS; } } if ((found & (LENGTH|COUNT)) != (LENGTH|COUNT)) return TEE_ERROR_BAD_PARAMETERS; return TEE_SUCCESS; } #endif TEE_Result syscall_cryp_derive_key(unsigned long state, const struct utee_attribute *usr_params, unsigned long param_count, unsigned long derived_key) { TEE_Result res = TEE_ERROR_NOT_SUPPORTED; struct tee_ta_session *sess; struct tee_obj *ko; struct tee_obj *so; struct tee_cryp_state *cs; struct tee_cryp_obj_secret *sk; const struct tee_cryp_obj_type_props *type_props; TEE_Attribute *params = NULL; struct user_ta_ctx *utc; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; utc = to_user_ta_ctx(sess->ctx); res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; params = malloc(sizeof(TEE_Attribute) * param_count); if (!params) return TEE_ERROR_OUT_OF_MEMORY; res = copy_in_attrs(utc, usr_params, param_count, params); if (res != TEE_SUCCESS) goto out; /* Get key set in operation */ res = tee_obj_get(utc, cs->key1, &ko); if (res != TEE_SUCCESS) goto out; res = tee_obj_get(utc, tee_svc_uref_to_vaddr(derived_key), &so); if (res != TEE_SUCCESS) goto out; /* Find information needed about the object to initialize */ sk = so->attr; /* Find description of object */ type_props = tee_svc_find_type_props(so->info.objectType); if (!type_props) { res = TEE_ERROR_NOT_SUPPORTED; goto out; } if (cs->algo == TEE_ALG_DH_DERIVE_SHARED_SECRET) { size_t alloc_size; struct bignum *pub; struct bignum *ss; if (param_count != 1 || params[0].attributeID != TEE_ATTR_DH_PUBLIC_VALUE) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } alloc_size = params[0].content.ref.length * 8; pub = crypto_bignum_allocate(alloc_size); ss = crypto_bignum_allocate(alloc_size); if (pub && ss) { crypto_bignum_bin2bn(params[0].content.ref.buffer, params[0].content.ref.length, pub); res = crypto_acipher_dh_shared_secret(ko->attr, pub, ss); if (res == TEE_SUCCESS) { sk->key_size = crypto_bignum_num_bytes(ss); crypto_bignum_bn2bin(ss, (uint8_t *)(sk + 1)); so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE); } } else { res = TEE_ERROR_OUT_OF_MEMORY; } crypto_bignum_free(pub); crypto_bignum_free(ss); } else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_ECDH) { size_t alloc_size; struct ecc_public_key key_public; uint8_t *pt_secret; unsigned long pt_secret_len; if (param_count != 2 || params[0].attributeID != TEE_ATTR_ECC_PUBLIC_VALUE_X || params[1].attributeID != TEE_ATTR_ECC_PUBLIC_VALUE_Y) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } switch (cs->algo) { case TEE_ALG_ECDH_P192: alloc_size = 192; break; case TEE_ALG_ECDH_P224: alloc_size = 224; break; case TEE_ALG_ECDH_P256: alloc_size = 256; break; case TEE_ALG_ECDH_P384: alloc_size = 384; break; case TEE_ALG_ECDH_P521: alloc_size = 521; break; default: res = TEE_ERROR_NOT_IMPLEMENTED; goto out; } /* Create the public key */ res = crypto_acipher_alloc_ecc_public_key(&key_public, alloc_size); if (res != TEE_SUCCESS) goto out; key_public.curve = ((struct ecc_keypair *)ko->attr)->curve; crypto_bignum_bin2bn(params[0].content.ref.buffer, params[0].content.ref.length, key_public.x); crypto_bignum_bin2bn(params[1].content.ref.buffer, params[1].content.ref.length, key_public.y); pt_secret = (uint8_t *)(sk + 1); pt_secret_len = sk->alloc_size; res = crypto_acipher_ecc_shared_secret(ko->attr, &key_public, pt_secret, &pt_secret_len); if (res == TEE_SUCCESS) { sk->key_size = pt_secret_len; so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE); } /* free the public key */ crypto_acipher_free_ecc_public_key(&key_public); } #if defined(CFG_CRYPTO_HKDF) else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_HKDF) { void *salt, *info; size_t salt_len, info_len, okm_len; uint32_t hash_id = TEE_ALG_GET_DIGEST_HASH(cs->algo); struct tee_cryp_obj_secret *ik = ko->attr; const uint8_t *ikm = (const uint8_t *)(ik + 1); res = get_hkdf_params(params, param_count, &salt, &salt_len, &info, &info_len, &okm_len); if (res != TEE_SUCCESS) goto out; /* Requested size must fit into the output object's buffer */ if (okm_len > ik->alloc_size) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } res = tee_cryp_hkdf(hash_id, ikm, ik->key_size, salt, salt_len, info, info_len, (uint8_t *)(sk + 1), okm_len); if (res == TEE_SUCCESS) { sk->key_size = okm_len; so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE); } } #endif #if defined(CFG_CRYPTO_CONCAT_KDF) else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_CONCAT_KDF) { void *info; size_t info_len, derived_key_len; uint32_t hash_id = TEE_ALG_GET_DIGEST_HASH(cs->algo); struct tee_cryp_obj_secret *ss = ko->attr; const uint8_t *shared_secret = (const uint8_t *)(ss + 1); res = get_concat_kdf_params(params, param_count, &info, &info_len, &derived_key_len); if (res != TEE_SUCCESS) goto out; /* Requested size must fit into the output object's buffer */ if (derived_key_len > ss->alloc_size) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } res = tee_cryp_concat_kdf(hash_id, shared_secret, ss->key_size, info, info_len, (uint8_t *)(sk + 1), derived_key_len); if (res == TEE_SUCCESS) { sk->key_size = derived_key_len; so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE); } } #endif #if defined(CFG_CRYPTO_PBKDF2) else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_PBKDF2) { void *salt; size_t salt_len, iteration_count, derived_key_len; uint32_t hash_id = TEE_ALG_GET_DIGEST_HASH(cs->algo); struct tee_cryp_obj_secret *ss = ko->attr; const uint8_t *password = (const uint8_t *)(ss + 1); res = get_pbkdf2_params(params, param_count, &salt, &salt_len, &derived_key_len, &iteration_count); if (res != TEE_SUCCESS) goto out; /* Requested size must fit into the output object's buffer */ if (derived_key_len > ss->alloc_size) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } res = tee_cryp_pbkdf2(hash_id, password, ss->key_size, salt, salt_len, iteration_count, (uint8_t *)(sk + 1), derived_key_len); if (res == TEE_SUCCESS) { sk->key_size = derived_key_len; so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE); } } #endif else res = TEE_ERROR_NOT_SUPPORTED; out: free(params); return res; } TEE_Result syscall_cryp_random_number_generate(void *buf, size_t blen) { TEE_Result res; struct tee_ta_session *sess; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)buf, blen); if (res != TEE_SUCCESS) return res; res = crypto_rng_read(buf, blen); if (res != TEE_SUCCESS) return res; return res; } TEE_Result syscall_authenc_init(unsigned long state, const void *nonce, size_t nonce_len, size_t tag_len, size_t aad_len, size_t payload_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; struct tee_obj *o; struct tee_cryp_obj_secret *key; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), cs->key1, &o); if (res != TEE_SUCCESS) return res; if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) return TEE_ERROR_BAD_PARAMETERS; key = o->attr; res = crypto_authenc_init(cs->ctx, cs->algo, cs->mode, (uint8_t *)(key + 1), key->key_size, nonce, nonce_len, tag_len, aad_len, payload_len); if (res != TEE_SUCCESS) return res; cs->ctx_finalize = (tee_cryp_ctx_finalize_func_t)crypto_authenc_final; return TEE_SUCCESS; } TEE_Result syscall_authenc_update_aad(unsigned long state, const void *aad_data, size_t aad_data_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t) aad_data, aad_data_len); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; res = crypto_authenc_update_aad(cs->ctx, cs->algo, cs->mode, aad_data, aad_data_len); if (res != TEE_SUCCESS) return res; return TEE_SUCCESS; } TEE_Result syscall_authenc_update_payload(unsigned long state, const void *src_data, size_t src_len, void *dst_data, uint64_t *dst_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; uint64_t dlen; size_t tmp_dlen; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t) src_data, src_len); if (res != TEE_SUCCESS) return res; res = tee_svc_copy_from_user(&dlen, dst_len, sizeof(dlen)); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)dst_data, dlen); if (res != TEE_SUCCESS) return res; if (dlen < src_len) { res = TEE_ERROR_SHORT_BUFFER; goto out; } tmp_dlen = dlen; res = crypto_authenc_update_payload(cs->ctx, cs->algo, cs->mode, src_data, src_len, dst_data, &tmp_dlen); dlen = tmp_dlen; out: if (res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) { TEE_Result res2 = tee_svc_copy_to_user(dst_len, &dlen, sizeof(*dst_len)); if (res2 != TEE_SUCCESS) res = res2; } return res; } TEE_Result syscall_authenc_enc_final(unsigned long state, const void *src_data, size_t src_len, void *dst_data, uint64_t *dst_len, void *tag, uint64_t *tag_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; uint64_t dlen; uint64_t tlen = 0; size_t tmp_dlen; size_t tmp_tlen; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; if (cs->mode != TEE_MODE_ENCRYPT) return TEE_ERROR_BAD_PARAMETERS; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)src_data, src_len); if (res != TEE_SUCCESS) return res; if (!dst_len) { dlen = 0; } else { res = tee_svc_copy_from_user(&dlen, dst_len, sizeof(dlen)); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)dst_data, dlen); if (res != TEE_SUCCESS) return res; } if (dlen < src_len) { res = TEE_ERROR_SHORT_BUFFER; goto out; } res = tee_svc_copy_from_user(&tlen, tag_len, sizeof(tlen)); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)tag, tlen); if (res != TEE_SUCCESS) return res; tmp_dlen = dlen; tmp_tlen = tlen; res = crypto_authenc_enc_final(cs->ctx, cs->algo, src_data, src_len, dst_data, &tmp_dlen, tag, &tmp_tlen); dlen = tmp_dlen; tlen = tmp_tlen; out: if (res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) { TEE_Result res2; if (dst_len != NULL) { res2 = tee_svc_copy_to_user(dst_len, &dlen, sizeof(*dst_len)); if (res2 != TEE_SUCCESS) return res2; } res2 = tee_svc_copy_to_user(tag_len, &tlen, sizeof(*tag_len)); if (res2 != TEE_SUCCESS) return res2; } return res; } TEE_Result syscall_authenc_dec_final(unsigned long state, const void *src_data, size_t src_len, void *dst_data, uint64_t *dst_len, const void *tag, size_t tag_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; uint64_t dlen; size_t tmp_dlen; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; if (cs->mode != TEE_MODE_DECRYPT) return TEE_ERROR_BAD_PARAMETERS; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)src_data, src_len); if (res != TEE_SUCCESS) return res; if (!dst_len) { dlen = 0; } else { res = tee_svc_copy_from_user(&dlen, dst_len, sizeof(dlen)); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)dst_data, dlen); if (res != TEE_SUCCESS) return res; } if (dlen < src_len) { res = TEE_ERROR_SHORT_BUFFER; goto out; } res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)tag, tag_len); if (res != TEE_SUCCESS) return res; tmp_dlen = dlen; res = crypto_authenc_dec_final(cs->ctx, cs->algo, src_data, src_len, dst_data, &tmp_dlen, tag, tag_len); dlen = tmp_dlen; out: if ((res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) && dst_len != NULL) { TEE_Result res2; res2 = tee_svc_copy_to_user(dst_len, &dlen, sizeof(*dst_len)); if (res2 != TEE_SUCCESS) return res2; } return res; } static int pkcs1_get_salt_len(const TEE_Attribute *params, uint32_t num_params, size_t default_len) { size_t n; assert(default_len < INT_MAX); for (n = 0; n < num_params; n++) { if (params[n].attributeID == TEE_ATTR_RSA_PSS_SALT_LENGTH) { if (params[n].content.value.a < INT_MAX) return params[n].content.value.a; break; } } /* * If salt length isn't provided use the default value which is * the length of the digest. */ return default_len; } TEE_Result syscall_asymm_operate(unsigned long state, const struct utee_attribute *usr_params, size_t num_params, const void *src_data, size_t src_len, void *dst_data, uint64_t *dst_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; uint64_t dlen64; size_t dlen; struct tee_obj *o; void *label = NULL; size_t label_len = 0; size_t n; int salt_len; TEE_Attribute *params = NULL; struct user_ta_ctx *utc; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; utc = to_user_ta_ctx(sess->ctx); res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights( utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t) src_data, src_len); if (res != TEE_SUCCESS) return res; res = tee_svc_copy_from_user(&dlen64, dst_len, sizeof(dlen64)); if (res != TEE_SUCCESS) return res; dlen = dlen64; res = tee_mmu_check_access_rights( utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t) dst_data, dlen); if (res != TEE_SUCCESS) return res; params = malloc(sizeof(TEE_Attribute) * num_params); if (!params) return TEE_ERROR_OUT_OF_MEMORY; res = copy_in_attrs(utc, usr_params, num_params, params); if (res != TEE_SUCCESS) goto out; res = tee_obj_get(utc, cs->key1, &o); if (res != TEE_SUCCESS) goto out; if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) { res = TEE_ERROR_GENERIC; goto out; } switch (cs->algo) { case TEE_ALG_RSA_NOPAD: if (cs->mode == TEE_MODE_ENCRYPT) { res = crypto_acipher_rsanopad_encrypt(o->attr, src_data, src_len, dst_data, &dlen); } else if (cs->mode == TEE_MODE_DECRYPT) { res = crypto_acipher_rsanopad_decrypt(o->attr, src_data, src_len, dst_data, &dlen); } else { /* * We will panic because "the mode is not compatible * with the function" */ res = TEE_ERROR_GENERIC; } break; case TEE_ALG_RSAES_PKCS1_V1_5: case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA1: case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA224: case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA256: case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA384: case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA512: for (n = 0; n < num_params; n++) { if (params[n].attributeID == TEE_ATTR_RSA_OAEP_LABEL) { label = params[n].content.ref.buffer; label_len = params[n].content.ref.length; break; } } if (cs->mode == TEE_MODE_ENCRYPT) { res = crypto_acipher_rsaes_encrypt(cs->algo, o->attr, label, label_len, src_data, src_len, dst_data, &dlen); } else if (cs->mode == TEE_MODE_DECRYPT) { res = crypto_acipher_rsaes_decrypt( cs->algo, o->attr, label, label_len, src_data, src_len, dst_data, &dlen); } else { res = TEE_ERROR_BAD_PARAMETERS; } break; #if defined(CFG_CRYPTO_RSASSA_NA1) case TEE_ALG_RSASSA_PKCS1_V1_5: #endif case TEE_ALG_RSASSA_PKCS1_V1_5_MD5: case TEE_ALG_RSASSA_PKCS1_V1_5_SHA1: case TEE_ALG_RSASSA_PKCS1_V1_5_SHA224: case TEE_ALG_RSASSA_PKCS1_V1_5_SHA256: case TEE_ALG_RSASSA_PKCS1_V1_5_SHA384: case TEE_ALG_RSASSA_PKCS1_V1_5_SHA512: case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA1: case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA224: case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA256: case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA384: case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA512: if (cs->mode != TEE_MODE_SIGN) { res = TEE_ERROR_BAD_PARAMETERS; break; } salt_len = pkcs1_get_salt_len(params, num_params, src_len); res = crypto_acipher_rsassa_sign(cs->algo, o->attr, salt_len, src_data, src_len, dst_data, &dlen); break; case TEE_ALG_DSA_SHA1: case TEE_ALG_DSA_SHA224: case TEE_ALG_DSA_SHA256: res = crypto_acipher_dsa_sign(cs->algo, o->attr, src_data, src_len, dst_data, &dlen); break; case TEE_ALG_ECDSA_P192: case TEE_ALG_ECDSA_P224: case TEE_ALG_ECDSA_P256: case TEE_ALG_ECDSA_P384: case TEE_ALG_ECDSA_P521: res = crypto_acipher_ecc_sign(cs->algo, o->attr, src_data, src_len, dst_data, &dlen); break; default: res = TEE_ERROR_BAD_PARAMETERS; break; } out: free(params); if (res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) { TEE_Result res2; dlen64 = dlen; res2 = tee_svc_copy_to_user(dst_len, &dlen64, sizeof(*dst_len)); if (res2 != TEE_SUCCESS) return res2; } return res; } TEE_Result syscall_asymm_verify(unsigned long state, const struct utee_attribute *usr_params, size_t num_params, const void *data, size_t data_len, const void *sig, size_t sig_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; struct tee_obj *o; size_t hash_size; int salt_len = 0; TEE_Attribute *params = NULL; uint32_t hash_algo; struct user_ta_ctx *utc; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; utc = to_user_ta_ctx(sess->ctx); res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; if (cs->mode != TEE_MODE_VERIFY) return TEE_ERROR_BAD_PARAMETERS; res = tee_mmu_check_access_rights(utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)data, data_len); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)sig, sig_len); if (res != TEE_SUCCESS) return res; params = malloc(sizeof(TEE_Attribute) * num_params); if (!params) return TEE_ERROR_OUT_OF_MEMORY; res = copy_in_attrs(utc, usr_params, num_params, params); if (res != TEE_SUCCESS) goto out; res = tee_obj_get(utc, cs->key1, &o); if (res != TEE_SUCCESS) goto out; if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } switch (TEE_ALG_GET_MAIN_ALG(cs->algo)) { case TEE_MAIN_ALGO_RSA: if (cs->algo != TEE_ALG_RSASSA_PKCS1_V1_5) { hash_algo = TEE_DIGEST_HASH_TO_ALGO(cs->algo); res = tee_hash_get_digest_size(hash_algo, &hash_size); if (res != TEE_SUCCESS) break; if (data_len != hash_size) { res = TEE_ERROR_BAD_PARAMETERS; break; } salt_len = pkcs1_get_salt_len(params, num_params, hash_size); } res = crypto_acipher_rsassa_verify(cs->algo, o->attr, salt_len, data, data_len, sig, sig_len); break; case TEE_MAIN_ALGO_DSA: hash_algo = TEE_DIGEST_HASH_TO_ALGO(cs->algo); res = tee_hash_get_digest_size(hash_algo, &hash_size); if (res != TEE_SUCCESS) break; /* * Depending on the DSA algorithm (NIST), the digital signature * output size may be truncated to the size of a key pair * (Q prime size). Q prime size must be less or equal than the * hash output length of the hash algorithm involved. */ if (data_len > hash_size) { res = TEE_ERROR_BAD_PARAMETERS; break; } res = crypto_acipher_dsa_verify(cs->algo, o->attr, data, data_len, sig, sig_len); break; case TEE_MAIN_ALGO_ECDSA: res = crypto_acipher_ecc_verify(cs->algo, o->attr, data, data_len, sig, sig_len); break; default: res = TEE_ERROR_NOT_SUPPORTED; } out: free(params); return res; }
./CrossVul/dataset_final_sorted/CWE-119/c/good_730_0
crossvul-cpp_data_bad_5661_0
/* * net/key/af_key.c An implementation of PF_KEYv2 sockets. * * 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. * * Authors: Maxim Giryaev <gem@asplinux.ru> * David S. Miller <davem@redhat.com> * Alexey Kuznetsov <kuznet@ms2.inr.ac.ru> * Kunihiro Ishiguro <kunihiro@ipinfusion.com> * Kazunori MIYAZAWA / USAGI Project <miyazawa@linux-ipv6.org> * Derek Atkins <derek@ihtfp.com> */ #include <linux/capability.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/socket.h> #include <linux/pfkeyv2.h> #include <linux/ipsec.h> #include <linux/skbuff.h> #include <linux/rtnetlink.h> #include <linux/in.h> #include <linux/in6.h> #include <linux/proc_fs.h> #include <linux/init.h> #include <linux/slab.h> #include <net/net_namespace.h> #include <net/netns/generic.h> #include <net/xfrm.h> #include <net/sock.h> #define _X2KEY(x) ((x) == XFRM_INF ? 0 : (x)) #define _KEY2X(x) ((x) == 0 ? XFRM_INF : (x)) static int pfkey_net_id __read_mostly; struct netns_pfkey { /* List of all pfkey sockets. */ struct hlist_head table; atomic_t socks_nr; }; static DEFINE_MUTEX(pfkey_mutex); #define DUMMY_MARK 0 static struct xfrm_mark dummy_mark = {0, 0}; struct pfkey_sock { /* struct sock must be the first member of struct pfkey_sock */ struct sock sk; int registered; int promisc; struct { uint8_t msg_version; uint32_t msg_portid; int (*dump)(struct pfkey_sock *sk); void (*done)(struct pfkey_sock *sk); union { struct xfrm_policy_walk policy; struct xfrm_state_walk state; } u; struct sk_buff *skb; } dump; }; static inline struct pfkey_sock *pfkey_sk(struct sock *sk) { return (struct pfkey_sock *)sk; } static int pfkey_can_dump(const struct sock *sk) { if (3 * atomic_read(&sk->sk_rmem_alloc) <= 2 * sk->sk_rcvbuf) return 1; return 0; } static void pfkey_terminate_dump(struct pfkey_sock *pfk) { if (pfk->dump.dump) { if (pfk->dump.skb) { kfree_skb(pfk->dump.skb); pfk->dump.skb = NULL; } pfk->dump.done(pfk); pfk->dump.dump = NULL; pfk->dump.done = NULL; } } static void pfkey_sock_destruct(struct sock *sk) { struct net *net = sock_net(sk); struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id); pfkey_terminate_dump(pfkey_sk(sk)); skb_queue_purge(&sk->sk_receive_queue); if (!sock_flag(sk, SOCK_DEAD)) { pr_err("Attempt to release alive pfkey socket: %p\n", sk); return; } WARN_ON(atomic_read(&sk->sk_rmem_alloc)); WARN_ON(atomic_read(&sk->sk_wmem_alloc)); atomic_dec(&net_pfkey->socks_nr); } static const struct proto_ops pfkey_ops; static void pfkey_insert(struct sock *sk) { struct net *net = sock_net(sk); struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id); mutex_lock(&pfkey_mutex); sk_add_node_rcu(sk, &net_pfkey->table); mutex_unlock(&pfkey_mutex); } static void pfkey_remove(struct sock *sk) { mutex_lock(&pfkey_mutex); sk_del_node_init_rcu(sk); mutex_unlock(&pfkey_mutex); } static struct proto key_proto = { .name = "KEY", .owner = THIS_MODULE, .obj_size = sizeof(struct pfkey_sock), }; static int pfkey_create(struct net *net, struct socket *sock, int protocol, int kern) { struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id); struct sock *sk; int err; if (!ns_capable(net->user_ns, CAP_NET_ADMIN)) return -EPERM; if (sock->type != SOCK_RAW) return -ESOCKTNOSUPPORT; if (protocol != PF_KEY_V2) return -EPROTONOSUPPORT; err = -ENOMEM; sk = sk_alloc(net, PF_KEY, GFP_KERNEL, &key_proto); if (sk == NULL) goto out; sock->ops = &pfkey_ops; sock_init_data(sock, sk); sk->sk_family = PF_KEY; sk->sk_destruct = pfkey_sock_destruct; atomic_inc(&net_pfkey->socks_nr); pfkey_insert(sk); return 0; out: return err; } static int pfkey_release(struct socket *sock) { struct sock *sk = sock->sk; if (!sk) return 0; pfkey_remove(sk); sock_orphan(sk); sock->sk = NULL; skb_queue_purge(&sk->sk_write_queue); synchronize_rcu(); sock_put(sk); return 0; } static int pfkey_broadcast_one(struct sk_buff *skb, struct sk_buff **skb2, gfp_t allocation, struct sock *sk) { int err = -ENOBUFS; sock_hold(sk); if (*skb2 == NULL) { if (atomic_read(&skb->users) != 1) { *skb2 = skb_clone(skb, allocation); } else { *skb2 = skb; atomic_inc(&skb->users); } } if (*skb2 != NULL) { if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf) { skb_set_owner_r(*skb2, sk); skb_queue_tail(&sk->sk_receive_queue, *skb2); sk->sk_data_ready(sk, (*skb2)->len); *skb2 = NULL; err = 0; } } sock_put(sk); return err; } /* Send SKB to all pfkey sockets matching selected criteria. */ #define BROADCAST_ALL 0 #define BROADCAST_ONE 1 #define BROADCAST_REGISTERED 2 #define BROADCAST_PROMISC_ONLY 4 static int pfkey_broadcast(struct sk_buff *skb, gfp_t allocation, int broadcast_flags, struct sock *one_sk, struct net *net) { struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id); struct sock *sk; struct sk_buff *skb2 = NULL; int err = -ESRCH; /* XXX Do we need something like netlink_overrun? I think * XXX PF_KEY socket apps will not mind current behavior. */ if (!skb) return -ENOMEM; rcu_read_lock(); sk_for_each_rcu(sk, &net_pfkey->table) { struct pfkey_sock *pfk = pfkey_sk(sk); int err2; /* Yes, it means that if you are meant to receive this * pfkey message you receive it twice as promiscuous * socket. */ if (pfk->promisc) pfkey_broadcast_one(skb, &skb2, allocation, sk); /* the exact target will be processed later */ if (sk == one_sk) continue; if (broadcast_flags != BROADCAST_ALL) { if (broadcast_flags & BROADCAST_PROMISC_ONLY) continue; if ((broadcast_flags & BROADCAST_REGISTERED) && !pfk->registered) continue; if (broadcast_flags & BROADCAST_ONE) continue; } err2 = pfkey_broadcast_one(skb, &skb2, allocation, sk); /* Error is cleare after succecful sending to at least one * registered KM */ if ((broadcast_flags & BROADCAST_REGISTERED) && err) err = err2; } rcu_read_unlock(); if (one_sk != NULL) err = pfkey_broadcast_one(skb, &skb2, allocation, one_sk); kfree_skb(skb2); kfree_skb(skb); return err; } static int pfkey_do_dump(struct pfkey_sock *pfk) { struct sadb_msg *hdr; int rc; rc = pfk->dump.dump(pfk); if (rc == -ENOBUFS) return 0; if (pfk->dump.skb) { if (!pfkey_can_dump(&pfk->sk)) return 0; hdr = (struct sadb_msg *) pfk->dump.skb->data; hdr->sadb_msg_seq = 0; hdr->sadb_msg_errno = rc; pfkey_broadcast(pfk->dump.skb, GFP_ATOMIC, BROADCAST_ONE, &pfk->sk, sock_net(&pfk->sk)); pfk->dump.skb = NULL; } pfkey_terminate_dump(pfk); return rc; } static inline void pfkey_hdr_dup(struct sadb_msg *new, const struct sadb_msg *orig) { *new = *orig; } static int pfkey_error(const struct sadb_msg *orig, int err, struct sock *sk) { struct sk_buff *skb = alloc_skb(sizeof(struct sadb_msg) + 16, GFP_KERNEL); struct sadb_msg *hdr; if (!skb) return -ENOBUFS; /* Woe be to the platform trying to support PFKEY yet * having normal errnos outside the 1-255 range, inclusive. */ err = -err; if (err == ERESTARTSYS || err == ERESTARTNOHAND || err == ERESTARTNOINTR) err = EINTR; if (err >= 512) err = EINVAL; BUG_ON(err <= 0 || err >= 256); hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg)); pfkey_hdr_dup(hdr, orig); hdr->sadb_msg_errno = (uint8_t) err; hdr->sadb_msg_len = (sizeof(struct sadb_msg) / sizeof(uint64_t)); pfkey_broadcast(skb, GFP_KERNEL, BROADCAST_ONE, sk, sock_net(sk)); return 0; } static u8 sadb_ext_min_len[] = { [SADB_EXT_RESERVED] = (u8) 0, [SADB_EXT_SA] = (u8) sizeof(struct sadb_sa), [SADB_EXT_LIFETIME_CURRENT] = (u8) sizeof(struct sadb_lifetime), [SADB_EXT_LIFETIME_HARD] = (u8) sizeof(struct sadb_lifetime), [SADB_EXT_LIFETIME_SOFT] = (u8) sizeof(struct sadb_lifetime), [SADB_EXT_ADDRESS_SRC] = (u8) sizeof(struct sadb_address), [SADB_EXT_ADDRESS_DST] = (u8) sizeof(struct sadb_address), [SADB_EXT_ADDRESS_PROXY] = (u8) sizeof(struct sadb_address), [SADB_EXT_KEY_AUTH] = (u8) sizeof(struct sadb_key), [SADB_EXT_KEY_ENCRYPT] = (u8) sizeof(struct sadb_key), [SADB_EXT_IDENTITY_SRC] = (u8) sizeof(struct sadb_ident), [SADB_EXT_IDENTITY_DST] = (u8) sizeof(struct sadb_ident), [SADB_EXT_SENSITIVITY] = (u8) sizeof(struct sadb_sens), [SADB_EXT_PROPOSAL] = (u8) sizeof(struct sadb_prop), [SADB_EXT_SUPPORTED_AUTH] = (u8) sizeof(struct sadb_supported), [SADB_EXT_SUPPORTED_ENCRYPT] = (u8) sizeof(struct sadb_supported), [SADB_EXT_SPIRANGE] = (u8) sizeof(struct sadb_spirange), [SADB_X_EXT_KMPRIVATE] = (u8) sizeof(struct sadb_x_kmprivate), [SADB_X_EXT_POLICY] = (u8) sizeof(struct sadb_x_policy), [SADB_X_EXT_SA2] = (u8) sizeof(struct sadb_x_sa2), [SADB_X_EXT_NAT_T_TYPE] = (u8) sizeof(struct sadb_x_nat_t_type), [SADB_X_EXT_NAT_T_SPORT] = (u8) sizeof(struct sadb_x_nat_t_port), [SADB_X_EXT_NAT_T_DPORT] = (u8) sizeof(struct sadb_x_nat_t_port), [SADB_X_EXT_NAT_T_OA] = (u8) sizeof(struct sadb_address), [SADB_X_EXT_SEC_CTX] = (u8) sizeof(struct sadb_x_sec_ctx), [SADB_X_EXT_KMADDRESS] = (u8) sizeof(struct sadb_x_kmaddress), }; /* Verify sadb_address_{len,prefixlen} against sa_family. */ static int verify_address_len(const void *p) { const struct sadb_address *sp = p; const struct sockaddr *addr = (const struct sockaddr *)(sp + 1); const struct sockaddr_in *sin; #if IS_ENABLED(CONFIG_IPV6) const struct sockaddr_in6 *sin6; #endif int len; switch (addr->sa_family) { case AF_INET: len = DIV_ROUND_UP(sizeof(*sp) + sizeof(*sin), sizeof(uint64_t)); if (sp->sadb_address_len != len || sp->sadb_address_prefixlen > 32) return -EINVAL; break; #if IS_ENABLED(CONFIG_IPV6) case AF_INET6: len = DIV_ROUND_UP(sizeof(*sp) + sizeof(*sin6), sizeof(uint64_t)); if (sp->sadb_address_len != len || sp->sadb_address_prefixlen > 128) return -EINVAL; break; #endif default: /* It is user using kernel to keep track of security * associations for another protocol, such as * OSPF/RSVP/RIPV2/MIP. It is user's job to verify * lengths. * * XXX Actually, association/policy database is not yet * XXX able to cope with arbitrary sockaddr families. * XXX When it can, remove this -EINVAL. -DaveM */ return -EINVAL; break; } return 0; } static inline int pfkey_sec_ctx_len(const struct sadb_x_sec_ctx *sec_ctx) { return DIV_ROUND_UP(sizeof(struct sadb_x_sec_ctx) + sec_ctx->sadb_x_ctx_len, sizeof(uint64_t)); } static inline int verify_sec_ctx_len(const void *p) { const struct sadb_x_sec_ctx *sec_ctx = p; int len = sec_ctx->sadb_x_ctx_len; if (len > PAGE_SIZE) return -EINVAL; len = pfkey_sec_ctx_len(sec_ctx); if (sec_ctx->sadb_x_sec_len != len) return -EINVAL; return 0; } static inline struct xfrm_user_sec_ctx *pfkey_sadb2xfrm_user_sec_ctx(const struct sadb_x_sec_ctx *sec_ctx) { struct xfrm_user_sec_ctx *uctx = NULL; int ctx_size = sec_ctx->sadb_x_ctx_len; uctx = kmalloc((sizeof(*uctx)+ctx_size), GFP_KERNEL); if (!uctx) return NULL; uctx->len = pfkey_sec_ctx_len(sec_ctx); uctx->exttype = sec_ctx->sadb_x_sec_exttype; uctx->ctx_doi = sec_ctx->sadb_x_ctx_doi; uctx->ctx_alg = sec_ctx->sadb_x_ctx_alg; uctx->ctx_len = sec_ctx->sadb_x_ctx_len; memcpy(uctx + 1, sec_ctx + 1, uctx->ctx_len); return uctx; } static int present_and_same_family(const struct sadb_address *src, const struct sadb_address *dst) { const struct sockaddr *s_addr, *d_addr; if (!src || !dst) return 0; s_addr = (const struct sockaddr *)(src + 1); d_addr = (const struct sockaddr *)(dst + 1); if (s_addr->sa_family != d_addr->sa_family) return 0; if (s_addr->sa_family != AF_INET #if IS_ENABLED(CONFIG_IPV6) && s_addr->sa_family != AF_INET6 #endif ) return 0; return 1; } static int parse_exthdrs(struct sk_buff *skb, const struct sadb_msg *hdr, void **ext_hdrs) { const char *p = (char *) hdr; int len = skb->len; len -= sizeof(*hdr); p += sizeof(*hdr); while (len > 0) { const struct sadb_ext *ehdr = (const struct sadb_ext *) p; uint16_t ext_type; int ext_len; ext_len = ehdr->sadb_ext_len; ext_len *= sizeof(uint64_t); ext_type = ehdr->sadb_ext_type; if (ext_len < sizeof(uint64_t) || ext_len > len || ext_type == SADB_EXT_RESERVED) return -EINVAL; if (ext_type <= SADB_EXT_MAX) { int min = (int) sadb_ext_min_len[ext_type]; if (ext_len < min) return -EINVAL; if (ext_hdrs[ext_type-1] != NULL) return -EINVAL; if (ext_type == SADB_EXT_ADDRESS_SRC || ext_type == SADB_EXT_ADDRESS_DST || ext_type == SADB_EXT_ADDRESS_PROXY || ext_type == SADB_X_EXT_NAT_T_OA) { if (verify_address_len(p)) return -EINVAL; } if (ext_type == SADB_X_EXT_SEC_CTX) { if (verify_sec_ctx_len(p)) return -EINVAL; } ext_hdrs[ext_type-1] = (void *) p; } p += ext_len; len -= ext_len; } return 0; } static uint16_t pfkey_satype2proto(uint8_t satype) { switch (satype) { case SADB_SATYPE_UNSPEC: return IPSEC_PROTO_ANY; case SADB_SATYPE_AH: return IPPROTO_AH; case SADB_SATYPE_ESP: return IPPROTO_ESP; case SADB_X_SATYPE_IPCOMP: return IPPROTO_COMP; break; default: return 0; } /* NOTREACHED */ } static uint8_t pfkey_proto2satype(uint16_t proto) { switch (proto) { case IPPROTO_AH: return SADB_SATYPE_AH; case IPPROTO_ESP: return SADB_SATYPE_ESP; case IPPROTO_COMP: return SADB_X_SATYPE_IPCOMP; break; default: return 0; } /* NOTREACHED */ } /* BTW, this scheme means that there is no way with PFKEY2 sockets to * say specifically 'just raw sockets' as we encode them as 255. */ static uint8_t pfkey_proto_to_xfrm(uint8_t proto) { return proto == IPSEC_PROTO_ANY ? 0 : proto; } static uint8_t pfkey_proto_from_xfrm(uint8_t proto) { return proto ? proto : IPSEC_PROTO_ANY; } static inline int pfkey_sockaddr_len(sa_family_t family) { switch (family) { case AF_INET: return sizeof(struct sockaddr_in); #if IS_ENABLED(CONFIG_IPV6) case AF_INET6: return sizeof(struct sockaddr_in6); #endif } return 0; } static int pfkey_sockaddr_extract(const struct sockaddr *sa, xfrm_address_t *xaddr) { switch (sa->sa_family) { case AF_INET: xaddr->a4 = ((struct sockaddr_in *)sa)->sin_addr.s_addr; return AF_INET; #if IS_ENABLED(CONFIG_IPV6) case AF_INET6: memcpy(xaddr->a6, &((struct sockaddr_in6 *)sa)->sin6_addr, sizeof(struct in6_addr)); return AF_INET6; #endif } return 0; } static int pfkey_sadb_addr2xfrm_addr(const struct sadb_address *addr, xfrm_address_t *xaddr) { return pfkey_sockaddr_extract((struct sockaddr *)(addr + 1), xaddr); } static struct xfrm_state *pfkey_xfrm_state_lookup(struct net *net, const struct sadb_msg *hdr, void * const *ext_hdrs) { const struct sadb_sa *sa; const struct sadb_address *addr; uint16_t proto; unsigned short family; xfrm_address_t *xaddr; sa = ext_hdrs[SADB_EXT_SA - 1]; if (sa == NULL) return NULL; proto = pfkey_satype2proto(hdr->sadb_msg_satype); if (proto == 0) return NULL; /* sadb_address_len should be checked by caller */ addr = ext_hdrs[SADB_EXT_ADDRESS_DST - 1]; if (addr == NULL) return NULL; family = ((const struct sockaddr *)(addr + 1))->sa_family; switch (family) { case AF_INET: xaddr = (xfrm_address_t *)&((const struct sockaddr_in *)(addr + 1))->sin_addr; break; #if IS_ENABLED(CONFIG_IPV6) case AF_INET6: xaddr = (xfrm_address_t *)&((const struct sockaddr_in6 *)(addr + 1))->sin6_addr; break; #endif default: xaddr = NULL; } if (!xaddr) return NULL; return xfrm_state_lookup(net, DUMMY_MARK, xaddr, sa->sadb_sa_spi, proto, family); } #define PFKEY_ALIGN8(a) (1 + (((a) - 1) | (8 - 1))) static int pfkey_sockaddr_size(sa_family_t family) { return PFKEY_ALIGN8(pfkey_sockaddr_len(family)); } static inline int pfkey_mode_from_xfrm(int mode) { switch(mode) { case XFRM_MODE_TRANSPORT: return IPSEC_MODE_TRANSPORT; case XFRM_MODE_TUNNEL: return IPSEC_MODE_TUNNEL; case XFRM_MODE_BEET: return IPSEC_MODE_BEET; default: return -1; } } static inline int pfkey_mode_to_xfrm(int mode) { switch(mode) { case IPSEC_MODE_ANY: /*XXX*/ case IPSEC_MODE_TRANSPORT: return XFRM_MODE_TRANSPORT; case IPSEC_MODE_TUNNEL: return XFRM_MODE_TUNNEL; case IPSEC_MODE_BEET: return XFRM_MODE_BEET; default: return -1; } } static unsigned int pfkey_sockaddr_fill(const xfrm_address_t *xaddr, __be16 port, struct sockaddr *sa, unsigned short family) { switch (family) { case AF_INET: { struct sockaddr_in *sin = (struct sockaddr_in *)sa; sin->sin_family = AF_INET; sin->sin_port = port; sin->sin_addr.s_addr = xaddr->a4; memset(sin->sin_zero, 0, sizeof(sin->sin_zero)); return 32; } #if IS_ENABLED(CONFIG_IPV6) case AF_INET6: { struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sa; sin6->sin6_family = AF_INET6; sin6->sin6_port = port; sin6->sin6_flowinfo = 0; sin6->sin6_addr = *(struct in6_addr *)xaddr->a6; sin6->sin6_scope_id = 0; return 128; } #endif } return 0; } static struct sk_buff *__pfkey_xfrm_state2msg(const struct xfrm_state *x, int add_keys, int hsc) { struct sk_buff *skb; struct sadb_msg *hdr; struct sadb_sa *sa; struct sadb_lifetime *lifetime; struct sadb_address *addr; struct sadb_key *key; struct sadb_x_sa2 *sa2; struct sadb_x_sec_ctx *sec_ctx; struct xfrm_sec_ctx *xfrm_ctx; int ctx_size = 0; int size; int auth_key_size = 0; int encrypt_key_size = 0; int sockaddr_size; struct xfrm_encap_tmpl *natt = NULL; int mode; /* address family check */ sockaddr_size = pfkey_sockaddr_size(x->props.family); if (!sockaddr_size) return ERR_PTR(-EINVAL); /* base, SA, (lifetime (HSC),) address(SD), (address(P),) key(AE), (identity(SD),) (sensitivity)> */ size = sizeof(struct sadb_msg) +sizeof(struct sadb_sa) + sizeof(struct sadb_lifetime) + ((hsc & 1) ? sizeof(struct sadb_lifetime) : 0) + ((hsc & 2) ? sizeof(struct sadb_lifetime) : 0) + sizeof(struct sadb_address)*2 + sockaddr_size*2 + sizeof(struct sadb_x_sa2); if ((xfrm_ctx = x->security)) { ctx_size = PFKEY_ALIGN8(xfrm_ctx->ctx_len); size += sizeof(struct sadb_x_sec_ctx) + ctx_size; } /* identity & sensitivity */ if (!xfrm_addr_equal(&x->sel.saddr, &x->props.saddr, x->props.family)) size += sizeof(struct sadb_address) + sockaddr_size; if (add_keys) { if (x->aalg && x->aalg->alg_key_len) { auth_key_size = PFKEY_ALIGN8((x->aalg->alg_key_len + 7) / 8); size += sizeof(struct sadb_key) + auth_key_size; } if (x->ealg && x->ealg->alg_key_len) { encrypt_key_size = PFKEY_ALIGN8((x->ealg->alg_key_len+7) / 8); size += sizeof(struct sadb_key) + encrypt_key_size; } } if (x->encap) natt = x->encap; if (natt && natt->encap_type) { size += sizeof(struct sadb_x_nat_t_type); size += sizeof(struct sadb_x_nat_t_port); size += sizeof(struct sadb_x_nat_t_port); } skb = alloc_skb(size + 16, GFP_ATOMIC); if (skb == NULL) return ERR_PTR(-ENOBUFS); /* call should fill header later */ hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg)); memset(hdr, 0, size); /* XXX do we need this ? */ hdr->sadb_msg_len = size / sizeof(uint64_t); /* sa */ sa = (struct sadb_sa *) skb_put(skb, sizeof(struct sadb_sa)); sa->sadb_sa_len = sizeof(struct sadb_sa)/sizeof(uint64_t); sa->sadb_sa_exttype = SADB_EXT_SA; sa->sadb_sa_spi = x->id.spi; sa->sadb_sa_replay = x->props.replay_window; switch (x->km.state) { case XFRM_STATE_VALID: sa->sadb_sa_state = x->km.dying ? SADB_SASTATE_DYING : SADB_SASTATE_MATURE; break; case XFRM_STATE_ACQ: sa->sadb_sa_state = SADB_SASTATE_LARVAL; break; default: sa->sadb_sa_state = SADB_SASTATE_DEAD; break; } sa->sadb_sa_auth = 0; if (x->aalg) { struct xfrm_algo_desc *a = xfrm_aalg_get_byname(x->aalg->alg_name, 0); sa->sadb_sa_auth = (a && a->pfkey_supported) ? a->desc.sadb_alg_id : 0; } sa->sadb_sa_encrypt = 0; BUG_ON(x->ealg && x->calg); if (x->ealg) { struct xfrm_algo_desc *a = xfrm_ealg_get_byname(x->ealg->alg_name, 0); sa->sadb_sa_encrypt = (a && a->pfkey_supported) ? a->desc.sadb_alg_id : 0; } /* KAME compatible: sadb_sa_encrypt is overloaded with calg id */ if (x->calg) { struct xfrm_algo_desc *a = xfrm_calg_get_byname(x->calg->alg_name, 0); sa->sadb_sa_encrypt = (a && a->pfkey_supported) ? a->desc.sadb_alg_id : 0; } sa->sadb_sa_flags = 0; if (x->props.flags & XFRM_STATE_NOECN) sa->sadb_sa_flags |= SADB_SAFLAGS_NOECN; if (x->props.flags & XFRM_STATE_DECAP_DSCP) sa->sadb_sa_flags |= SADB_SAFLAGS_DECAP_DSCP; if (x->props.flags & XFRM_STATE_NOPMTUDISC) sa->sadb_sa_flags |= SADB_SAFLAGS_NOPMTUDISC; /* hard time */ if (hsc & 2) { lifetime = (struct sadb_lifetime *) skb_put(skb, sizeof(struct sadb_lifetime)); lifetime->sadb_lifetime_len = sizeof(struct sadb_lifetime)/sizeof(uint64_t); lifetime->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD; lifetime->sadb_lifetime_allocations = _X2KEY(x->lft.hard_packet_limit); lifetime->sadb_lifetime_bytes = _X2KEY(x->lft.hard_byte_limit); lifetime->sadb_lifetime_addtime = x->lft.hard_add_expires_seconds; lifetime->sadb_lifetime_usetime = x->lft.hard_use_expires_seconds; } /* soft time */ if (hsc & 1) { lifetime = (struct sadb_lifetime *) skb_put(skb, sizeof(struct sadb_lifetime)); lifetime->sadb_lifetime_len = sizeof(struct sadb_lifetime)/sizeof(uint64_t); lifetime->sadb_lifetime_exttype = SADB_EXT_LIFETIME_SOFT; lifetime->sadb_lifetime_allocations = _X2KEY(x->lft.soft_packet_limit); lifetime->sadb_lifetime_bytes = _X2KEY(x->lft.soft_byte_limit); lifetime->sadb_lifetime_addtime = x->lft.soft_add_expires_seconds; lifetime->sadb_lifetime_usetime = x->lft.soft_use_expires_seconds; } /* current time */ lifetime = (struct sadb_lifetime *) skb_put(skb, sizeof(struct sadb_lifetime)); lifetime->sadb_lifetime_len = sizeof(struct sadb_lifetime)/sizeof(uint64_t); lifetime->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT; lifetime->sadb_lifetime_allocations = x->curlft.packets; lifetime->sadb_lifetime_bytes = x->curlft.bytes; lifetime->sadb_lifetime_addtime = x->curlft.add_time; lifetime->sadb_lifetime_usetime = x->curlft.use_time; /* src address */ addr = (struct sadb_address*) skb_put(skb, sizeof(struct sadb_address)+sockaddr_size); addr->sadb_address_len = (sizeof(struct sadb_address)+sockaddr_size)/ sizeof(uint64_t); addr->sadb_address_exttype = SADB_EXT_ADDRESS_SRC; /* "if the ports are non-zero, then the sadb_address_proto field, normally zero, MUST be filled in with the transport protocol's number." - RFC2367 */ addr->sadb_address_proto = 0; addr->sadb_address_reserved = 0; addr->sadb_address_prefixlen = pfkey_sockaddr_fill(&x->props.saddr, 0, (struct sockaddr *) (addr + 1), x->props.family); if (!addr->sadb_address_prefixlen) BUG(); /* dst address */ addr = (struct sadb_address*) skb_put(skb, sizeof(struct sadb_address)+sockaddr_size); addr->sadb_address_len = (sizeof(struct sadb_address)+sockaddr_size)/ sizeof(uint64_t); addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST; addr->sadb_address_proto = 0; addr->sadb_address_reserved = 0; addr->sadb_address_prefixlen = pfkey_sockaddr_fill(&x->id.daddr, 0, (struct sockaddr *) (addr + 1), x->props.family); if (!addr->sadb_address_prefixlen) BUG(); if (!xfrm_addr_equal(&x->sel.saddr, &x->props.saddr, x->props.family)) { addr = (struct sadb_address*) skb_put(skb, sizeof(struct sadb_address)+sockaddr_size); addr->sadb_address_len = (sizeof(struct sadb_address)+sockaddr_size)/ sizeof(uint64_t); addr->sadb_address_exttype = SADB_EXT_ADDRESS_PROXY; addr->sadb_address_proto = pfkey_proto_from_xfrm(x->sel.proto); addr->sadb_address_prefixlen = x->sel.prefixlen_s; addr->sadb_address_reserved = 0; pfkey_sockaddr_fill(&x->sel.saddr, x->sel.sport, (struct sockaddr *) (addr + 1), x->props.family); } /* auth key */ if (add_keys && auth_key_size) { key = (struct sadb_key *) skb_put(skb, sizeof(struct sadb_key)+auth_key_size); key->sadb_key_len = (sizeof(struct sadb_key) + auth_key_size) / sizeof(uint64_t); key->sadb_key_exttype = SADB_EXT_KEY_AUTH; key->sadb_key_bits = x->aalg->alg_key_len; key->sadb_key_reserved = 0; memcpy(key + 1, x->aalg->alg_key, (x->aalg->alg_key_len+7)/8); } /* encrypt key */ if (add_keys && encrypt_key_size) { key = (struct sadb_key *) skb_put(skb, sizeof(struct sadb_key)+encrypt_key_size); key->sadb_key_len = (sizeof(struct sadb_key) + encrypt_key_size) / sizeof(uint64_t); key->sadb_key_exttype = SADB_EXT_KEY_ENCRYPT; key->sadb_key_bits = x->ealg->alg_key_len; key->sadb_key_reserved = 0; memcpy(key + 1, x->ealg->alg_key, (x->ealg->alg_key_len+7)/8); } /* sa */ sa2 = (struct sadb_x_sa2 *) skb_put(skb, sizeof(struct sadb_x_sa2)); sa2->sadb_x_sa2_len = sizeof(struct sadb_x_sa2)/sizeof(uint64_t); sa2->sadb_x_sa2_exttype = SADB_X_EXT_SA2; if ((mode = pfkey_mode_from_xfrm(x->props.mode)) < 0) { kfree_skb(skb); return ERR_PTR(-EINVAL); } sa2->sadb_x_sa2_mode = mode; sa2->sadb_x_sa2_reserved1 = 0; sa2->sadb_x_sa2_reserved2 = 0; sa2->sadb_x_sa2_sequence = 0; sa2->sadb_x_sa2_reqid = x->props.reqid; if (natt && natt->encap_type) { struct sadb_x_nat_t_type *n_type; struct sadb_x_nat_t_port *n_port; /* type */ n_type = (struct sadb_x_nat_t_type*) skb_put(skb, sizeof(*n_type)); n_type->sadb_x_nat_t_type_len = sizeof(*n_type)/sizeof(uint64_t); n_type->sadb_x_nat_t_type_exttype = SADB_X_EXT_NAT_T_TYPE; n_type->sadb_x_nat_t_type_type = natt->encap_type; n_type->sadb_x_nat_t_type_reserved[0] = 0; n_type->sadb_x_nat_t_type_reserved[1] = 0; n_type->sadb_x_nat_t_type_reserved[2] = 0; /* source port */ n_port = (struct sadb_x_nat_t_port*) skb_put(skb, sizeof (*n_port)); n_port->sadb_x_nat_t_port_len = sizeof(*n_port)/sizeof(uint64_t); n_port->sadb_x_nat_t_port_exttype = SADB_X_EXT_NAT_T_SPORT; n_port->sadb_x_nat_t_port_port = natt->encap_sport; n_port->sadb_x_nat_t_port_reserved = 0; /* dest port */ n_port = (struct sadb_x_nat_t_port*) skb_put(skb, sizeof (*n_port)); n_port->sadb_x_nat_t_port_len = sizeof(*n_port)/sizeof(uint64_t); n_port->sadb_x_nat_t_port_exttype = SADB_X_EXT_NAT_T_DPORT; n_port->sadb_x_nat_t_port_port = natt->encap_dport; n_port->sadb_x_nat_t_port_reserved = 0; } /* security context */ if (xfrm_ctx) { sec_ctx = (struct sadb_x_sec_ctx *) skb_put(skb, sizeof(struct sadb_x_sec_ctx) + ctx_size); sec_ctx->sadb_x_sec_len = (sizeof(struct sadb_x_sec_ctx) + ctx_size) / sizeof(uint64_t); sec_ctx->sadb_x_sec_exttype = SADB_X_EXT_SEC_CTX; sec_ctx->sadb_x_ctx_doi = xfrm_ctx->ctx_doi; sec_ctx->sadb_x_ctx_alg = xfrm_ctx->ctx_alg; sec_ctx->sadb_x_ctx_len = xfrm_ctx->ctx_len; memcpy(sec_ctx + 1, xfrm_ctx->ctx_str, xfrm_ctx->ctx_len); } return skb; } static inline struct sk_buff *pfkey_xfrm_state2msg(const struct xfrm_state *x) { struct sk_buff *skb; skb = __pfkey_xfrm_state2msg(x, 1, 3); return skb; } static inline struct sk_buff *pfkey_xfrm_state2msg_expire(const struct xfrm_state *x, int hsc) { return __pfkey_xfrm_state2msg(x, 0, hsc); } static struct xfrm_state * pfkey_msg2xfrm_state(struct net *net, const struct sadb_msg *hdr, void * const *ext_hdrs) { struct xfrm_state *x; const struct sadb_lifetime *lifetime; const struct sadb_sa *sa; const struct sadb_key *key; const struct sadb_x_sec_ctx *sec_ctx; uint16_t proto; int err; sa = ext_hdrs[SADB_EXT_SA - 1]; if (!sa || !present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1], ext_hdrs[SADB_EXT_ADDRESS_DST-1])) return ERR_PTR(-EINVAL); if (hdr->sadb_msg_satype == SADB_SATYPE_ESP && !ext_hdrs[SADB_EXT_KEY_ENCRYPT-1]) return ERR_PTR(-EINVAL); if (hdr->sadb_msg_satype == SADB_SATYPE_AH && !ext_hdrs[SADB_EXT_KEY_AUTH-1]) return ERR_PTR(-EINVAL); if (!!ext_hdrs[SADB_EXT_LIFETIME_HARD-1] != !!ext_hdrs[SADB_EXT_LIFETIME_SOFT-1]) return ERR_PTR(-EINVAL); proto = pfkey_satype2proto(hdr->sadb_msg_satype); if (proto == 0) return ERR_PTR(-EINVAL); /* default error is no buffer space */ err = -ENOBUFS; /* RFC2367: Only SADB_SASTATE_MATURE SAs may be submitted in an SADB_ADD message. SADB_SASTATE_LARVAL SAs are created by SADB_GETSPI and it is not sensible to add a new SA in the DYING or SADB_SASTATE_DEAD state. Therefore, the sadb_sa_state field of all submitted SAs MUST be SADB_SASTATE_MATURE and the kernel MUST return an error if this is not true. However, KAME setkey always uses SADB_SASTATE_LARVAL. Hence, we have to _ignore_ sadb_sa_state, which is also reasonable. */ if (sa->sadb_sa_auth > SADB_AALG_MAX || (hdr->sadb_msg_satype == SADB_X_SATYPE_IPCOMP && sa->sadb_sa_encrypt > SADB_X_CALG_MAX) || sa->sadb_sa_encrypt > SADB_EALG_MAX) return ERR_PTR(-EINVAL); key = ext_hdrs[SADB_EXT_KEY_AUTH - 1]; if (key != NULL && sa->sadb_sa_auth != SADB_X_AALG_NULL && ((key->sadb_key_bits+7) / 8 == 0 || (key->sadb_key_bits+7) / 8 > key->sadb_key_len * sizeof(uint64_t))) return ERR_PTR(-EINVAL); key = ext_hdrs[SADB_EXT_KEY_ENCRYPT-1]; if (key != NULL && sa->sadb_sa_encrypt != SADB_EALG_NULL && ((key->sadb_key_bits+7) / 8 == 0 || (key->sadb_key_bits+7) / 8 > key->sadb_key_len * sizeof(uint64_t))) return ERR_PTR(-EINVAL); x = xfrm_state_alloc(net); if (x == NULL) return ERR_PTR(-ENOBUFS); x->id.proto = proto; x->id.spi = sa->sadb_sa_spi; x->props.replay_window = sa->sadb_sa_replay; if (sa->sadb_sa_flags & SADB_SAFLAGS_NOECN) x->props.flags |= XFRM_STATE_NOECN; if (sa->sadb_sa_flags & SADB_SAFLAGS_DECAP_DSCP) x->props.flags |= XFRM_STATE_DECAP_DSCP; if (sa->sadb_sa_flags & SADB_SAFLAGS_NOPMTUDISC) x->props.flags |= XFRM_STATE_NOPMTUDISC; lifetime = ext_hdrs[SADB_EXT_LIFETIME_HARD - 1]; if (lifetime != NULL) { x->lft.hard_packet_limit = _KEY2X(lifetime->sadb_lifetime_allocations); x->lft.hard_byte_limit = _KEY2X(lifetime->sadb_lifetime_bytes); x->lft.hard_add_expires_seconds = lifetime->sadb_lifetime_addtime; x->lft.hard_use_expires_seconds = lifetime->sadb_lifetime_usetime; } lifetime = ext_hdrs[SADB_EXT_LIFETIME_SOFT - 1]; if (lifetime != NULL) { x->lft.soft_packet_limit = _KEY2X(lifetime->sadb_lifetime_allocations); x->lft.soft_byte_limit = _KEY2X(lifetime->sadb_lifetime_bytes); x->lft.soft_add_expires_seconds = lifetime->sadb_lifetime_addtime; x->lft.soft_use_expires_seconds = lifetime->sadb_lifetime_usetime; } sec_ctx = ext_hdrs[SADB_X_EXT_SEC_CTX - 1]; if (sec_ctx != NULL) { struct xfrm_user_sec_ctx *uctx = pfkey_sadb2xfrm_user_sec_ctx(sec_ctx); if (!uctx) goto out; err = security_xfrm_state_alloc(x, uctx); kfree(uctx); if (err) goto out; } key = ext_hdrs[SADB_EXT_KEY_AUTH - 1]; if (sa->sadb_sa_auth) { int keysize = 0; struct xfrm_algo_desc *a = xfrm_aalg_get_byid(sa->sadb_sa_auth); if (!a || !a->pfkey_supported) { err = -ENOSYS; goto out; } if (key) keysize = (key->sadb_key_bits + 7) / 8; x->aalg = kmalloc(sizeof(*x->aalg) + keysize, GFP_KERNEL); if (!x->aalg) goto out; strcpy(x->aalg->alg_name, a->name); x->aalg->alg_key_len = 0; if (key) { x->aalg->alg_key_len = key->sadb_key_bits; memcpy(x->aalg->alg_key, key+1, keysize); } x->aalg->alg_trunc_len = a->uinfo.auth.icv_truncbits; x->props.aalgo = sa->sadb_sa_auth; /* x->algo.flags = sa->sadb_sa_flags; */ } if (sa->sadb_sa_encrypt) { if (hdr->sadb_msg_satype == SADB_X_SATYPE_IPCOMP) { struct xfrm_algo_desc *a = xfrm_calg_get_byid(sa->sadb_sa_encrypt); if (!a || !a->pfkey_supported) { err = -ENOSYS; goto out; } x->calg = kmalloc(sizeof(*x->calg), GFP_KERNEL); if (!x->calg) goto out; strcpy(x->calg->alg_name, a->name); x->props.calgo = sa->sadb_sa_encrypt; } else { int keysize = 0; struct xfrm_algo_desc *a = xfrm_ealg_get_byid(sa->sadb_sa_encrypt); if (!a || !a->pfkey_supported) { err = -ENOSYS; goto out; } key = (struct sadb_key*) ext_hdrs[SADB_EXT_KEY_ENCRYPT-1]; if (key) keysize = (key->sadb_key_bits + 7) / 8; x->ealg = kmalloc(sizeof(*x->ealg) + keysize, GFP_KERNEL); if (!x->ealg) goto out; strcpy(x->ealg->alg_name, a->name); x->ealg->alg_key_len = 0; if (key) { x->ealg->alg_key_len = key->sadb_key_bits; memcpy(x->ealg->alg_key, key+1, keysize); } x->props.ealgo = sa->sadb_sa_encrypt; } } /* x->algo.flags = sa->sadb_sa_flags; */ x->props.family = pfkey_sadb_addr2xfrm_addr((struct sadb_address *) ext_hdrs[SADB_EXT_ADDRESS_SRC-1], &x->props.saddr); if (!x->props.family) { err = -EAFNOSUPPORT; goto out; } pfkey_sadb_addr2xfrm_addr((struct sadb_address *) ext_hdrs[SADB_EXT_ADDRESS_DST-1], &x->id.daddr); if (ext_hdrs[SADB_X_EXT_SA2-1]) { const struct sadb_x_sa2 *sa2 = ext_hdrs[SADB_X_EXT_SA2-1]; int mode = pfkey_mode_to_xfrm(sa2->sadb_x_sa2_mode); if (mode < 0) { err = -EINVAL; goto out; } x->props.mode = mode; x->props.reqid = sa2->sadb_x_sa2_reqid; } if (ext_hdrs[SADB_EXT_ADDRESS_PROXY-1]) { const struct sadb_address *addr = ext_hdrs[SADB_EXT_ADDRESS_PROXY-1]; /* Nobody uses this, but we try. */ x->sel.family = pfkey_sadb_addr2xfrm_addr(addr, &x->sel.saddr); x->sel.prefixlen_s = addr->sadb_address_prefixlen; } if (!x->sel.family) x->sel.family = x->props.family; if (ext_hdrs[SADB_X_EXT_NAT_T_TYPE-1]) { const struct sadb_x_nat_t_type* n_type; struct xfrm_encap_tmpl *natt; x->encap = kmalloc(sizeof(*x->encap), GFP_KERNEL); if (!x->encap) goto out; natt = x->encap; n_type = ext_hdrs[SADB_X_EXT_NAT_T_TYPE-1]; natt->encap_type = n_type->sadb_x_nat_t_type_type; if (ext_hdrs[SADB_X_EXT_NAT_T_SPORT-1]) { const struct sadb_x_nat_t_port *n_port = ext_hdrs[SADB_X_EXT_NAT_T_SPORT-1]; natt->encap_sport = n_port->sadb_x_nat_t_port_port; } if (ext_hdrs[SADB_X_EXT_NAT_T_DPORT-1]) { const struct sadb_x_nat_t_port *n_port = ext_hdrs[SADB_X_EXT_NAT_T_DPORT-1]; natt->encap_dport = n_port->sadb_x_nat_t_port_port; } memset(&natt->encap_oa, 0, sizeof(natt->encap_oa)); } err = xfrm_init_state(x); if (err) goto out; x->km.seq = hdr->sadb_msg_seq; return x; out: x->km.state = XFRM_STATE_DEAD; xfrm_state_put(x); return ERR_PTR(err); } static int pfkey_reserved(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { return -EOPNOTSUPP; } static int pfkey_getspi(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { struct net *net = sock_net(sk); struct sk_buff *resp_skb; struct sadb_x_sa2 *sa2; struct sadb_address *saddr, *daddr; struct sadb_msg *out_hdr; struct sadb_spirange *range; struct xfrm_state *x = NULL; int mode; int err; u32 min_spi, max_spi; u32 reqid; u8 proto; unsigned short family; xfrm_address_t *xsaddr = NULL, *xdaddr = NULL; if (!present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1], ext_hdrs[SADB_EXT_ADDRESS_DST-1])) return -EINVAL; proto = pfkey_satype2proto(hdr->sadb_msg_satype); if (proto == 0) return -EINVAL; if ((sa2 = ext_hdrs[SADB_X_EXT_SA2-1]) != NULL) { mode = pfkey_mode_to_xfrm(sa2->sadb_x_sa2_mode); if (mode < 0) return -EINVAL; reqid = sa2->sadb_x_sa2_reqid; } else { mode = 0; reqid = 0; } saddr = ext_hdrs[SADB_EXT_ADDRESS_SRC-1]; daddr = ext_hdrs[SADB_EXT_ADDRESS_DST-1]; family = ((struct sockaddr *)(saddr + 1))->sa_family; switch (family) { case AF_INET: xdaddr = (xfrm_address_t *)&((struct sockaddr_in *)(daddr + 1))->sin_addr.s_addr; xsaddr = (xfrm_address_t *)&((struct sockaddr_in *)(saddr + 1))->sin_addr.s_addr; break; #if IS_ENABLED(CONFIG_IPV6) case AF_INET6: xdaddr = (xfrm_address_t *)&((struct sockaddr_in6 *)(daddr + 1))->sin6_addr; xsaddr = (xfrm_address_t *)&((struct sockaddr_in6 *)(saddr + 1))->sin6_addr; break; #endif } if (hdr->sadb_msg_seq) { x = xfrm_find_acq_byseq(net, DUMMY_MARK, hdr->sadb_msg_seq); if (x && !xfrm_addr_equal(&x->id.daddr, xdaddr, family)) { xfrm_state_put(x); x = NULL; } } if (!x) x = xfrm_find_acq(net, &dummy_mark, mode, reqid, proto, xdaddr, xsaddr, 1, family); if (x == NULL) return -ENOENT; min_spi = 0x100; max_spi = 0x0fffffff; range = ext_hdrs[SADB_EXT_SPIRANGE-1]; if (range) { min_spi = range->sadb_spirange_min; max_spi = range->sadb_spirange_max; } err = xfrm_alloc_spi(x, min_spi, max_spi); resp_skb = err ? ERR_PTR(err) : pfkey_xfrm_state2msg(x); if (IS_ERR(resp_skb)) { xfrm_state_put(x); return PTR_ERR(resp_skb); } out_hdr = (struct sadb_msg *) resp_skb->data; out_hdr->sadb_msg_version = hdr->sadb_msg_version; out_hdr->sadb_msg_type = SADB_GETSPI; out_hdr->sadb_msg_satype = pfkey_proto2satype(proto); out_hdr->sadb_msg_errno = 0; out_hdr->sadb_msg_reserved = 0; out_hdr->sadb_msg_seq = hdr->sadb_msg_seq; out_hdr->sadb_msg_pid = hdr->sadb_msg_pid; xfrm_state_put(x); pfkey_broadcast(resp_skb, GFP_KERNEL, BROADCAST_ONE, sk, net); return 0; } static int pfkey_acquire(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { struct net *net = sock_net(sk); struct xfrm_state *x; if (hdr->sadb_msg_len != sizeof(struct sadb_msg)/8) return -EOPNOTSUPP; if (hdr->sadb_msg_seq == 0 || hdr->sadb_msg_errno == 0) return 0; x = xfrm_find_acq_byseq(net, DUMMY_MARK, hdr->sadb_msg_seq); if (x == NULL) return 0; spin_lock_bh(&x->lock); if (x->km.state == XFRM_STATE_ACQ) { x->km.state = XFRM_STATE_ERROR; wake_up(&net->xfrm.km_waitq); } spin_unlock_bh(&x->lock); xfrm_state_put(x); return 0; } static inline int event2poltype(int event) { switch (event) { case XFRM_MSG_DELPOLICY: return SADB_X_SPDDELETE; case XFRM_MSG_NEWPOLICY: return SADB_X_SPDADD; case XFRM_MSG_UPDPOLICY: return SADB_X_SPDUPDATE; case XFRM_MSG_POLEXPIRE: // return SADB_X_SPDEXPIRE; default: pr_err("pfkey: Unknown policy event %d\n", event); break; } return 0; } static inline int event2keytype(int event) { switch (event) { case XFRM_MSG_DELSA: return SADB_DELETE; case XFRM_MSG_NEWSA: return SADB_ADD; case XFRM_MSG_UPDSA: return SADB_UPDATE; case XFRM_MSG_EXPIRE: return SADB_EXPIRE; default: pr_err("pfkey: Unknown SA event %d\n", event); break; } return 0; } /* ADD/UPD/DEL */ static int key_notify_sa(struct xfrm_state *x, const struct km_event *c) { struct sk_buff *skb; struct sadb_msg *hdr; skb = pfkey_xfrm_state2msg(x); if (IS_ERR(skb)) return PTR_ERR(skb); hdr = (struct sadb_msg *) skb->data; hdr->sadb_msg_version = PF_KEY_V2; hdr->sadb_msg_type = event2keytype(c->event); hdr->sadb_msg_satype = pfkey_proto2satype(x->id.proto); hdr->sadb_msg_errno = 0; hdr->sadb_msg_reserved = 0; hdr->sadb_msg_seq = c->seq; hdr->sadb_msg_pid = c->portid; pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_ALL, NULL, xs_net(x)); return 0; } static int pfkey_add(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { struct net *net = sock_net(sk); struct xfrm_state *x; int err; struct km_event c; x = pfkey_msg2xfrm_state(net, hdr, ext_hdrs); if (IS_ERR(x)) return PTR_ERR(x); xfrm_state_hold(x); if (hdr->sadb_msg_type == SADB_ADD) err = xfrm_state_add(x); else err = xfrm_state_update(x); xfrm_audit_state_add(x, err ? 0 : 1, audit_get_loginuid(current), audit_get_sessionid(current), 0); if (err < 0) { x->km.state = XFRM_STATE_DEAD; __xfrm_state_put(x); goto out; } if (hdr->sadb_msg_type == SADB_ADD) c.event = XFRM_MSG_NEWSA; else c.event = XFRM_MSG_UPDSA; c.seq = hdr->sadb_msg_seq; c.portid = hdr->sadb_msg_pid; km_state_notify(x, &c); out: xfrm_state_put(x); return err; } static int pfkey_delete(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { struct net *net = sock_net(sk); struct xfrm_state *x; struct km_event c; int err; if (!ext_hdrs[SADB_EXT_SA-1] || !present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1], ext_hdrs[SADB_EXT_ADDRESS_DST-1])) return -EINVAL; x = pfkey_xfrm_state_lookup(net, hdr, ext_hdrs); if (x == NULL) return -ESRCH; if ((err = security_xfrm_state_delete(x))) goto out; if (xfrm_state_kern(x)) { err = -EPERM; goto out; } err = xfrm_state_delete(x); if (err < 0) goto out; c.seq = hdr->sadb_msg_seq; c.portid = hdr->sadb_msg_pid; c.event = XFRM_MSG_DELSA; km_state_notify(x, &c); out: xfrm_audit_state_delete(x, err ? 0 : 1, audit_get_loginuid(current), audit_get_sessionid(current), 0); xfrm_state_put(x); return err; } static int pfkey_get(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { struct net *net = sock_net(sk); __u8 proto; struct sk_buff *out_skb; struct sadb_msg *out_hdr; struct xfrm_state *x; if (!ext_hdrs[SADB_EXT_SA-1] || !present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1], ext_hdrs[SADB_EXT_ADDRESS_DST-1])) return -EINVAL; x = pfkey_xfrm_state_lookup(net, hdr, ext_hdrs); if (x == NULL) return -ESRCH; out_skb = pfkey_xfrm_state2msg(x); proto = x->id.proto; xfrm_state_put(x); if (IS_ERR(out_skb)) return PTR_ERR(out_skb); out_hdr = (struct sadb_msg *) out_skb->data; out_hdr->sadb_msg_version = hdr->sadb_msg_version; out_hdr->sadb_msg_type = SADB_GET; out_hdr->sadb_msg_satype = pfkey_proto2satype(proto); out_hdr->sadb_msg_errno = 0; out_hdr->sadb_msg_reserved = 0; out_hdr->sadb_msg_seq = hdr->sadb_msg_seq; out_hdr->sadb_msg_pid = hdr->sadb_msg_pid; pfkey_broadcast(out_skb, GFP_ATOMIC, BROADCAST_ONE, sk, sock_net(sk)); return 0; } static struct sk_buff *compose_sadb_supported(const struct sadb_msg *orig, gfp_t allocation) { struct sk_buff *skb; struct sadb_msg *hdr; int len, auth_len, enc_len, i; auth_len = xfrm_count_pfkey_auth_supported(); if (auth_len) { auth_len *= sizeof(struct sadb_alg); auth_len += sizeof(struct sadb_supported); } enc_len = xfrm_count_pfkey_enc_supported(); if (enc_len) { enc_len *= sizeof(struct sadb_alg); enc_len += sizeof(struct sadb_supported); } len = enc_len + auth_len + sizeof(struct sadb_msg); skb = alloc_skb(len + 16, allocation); if (!skb) goto out_put_algs; hdr = (struct sadb_msg *) skb_put(skb, sizeof(*hdr)); pfkey_hdr_dup(hdr, orig); hdr->sadb_msg_errno = 0; hdr->sadb_msg_len = len / sizeof(uint64_t); if (auth_len) { struct sadb_supported *sp; struct sadb_alg *ap; sp = (struct sadb_supported *) skb_put(skb, auth_len); ap = (struct sadb_alg *) (sp + 1); sp->sadb_supported_len = auth_len / sizeof(uint64_t); sp->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH; for (i = 0; ; i++) { struct xfrm_algo_desc *aalg = xfrm_aalg_get_byidx(i); if (!aalg) break; if (!aalg->pfkey_supported) continue; if (aalg->available) *ap++ = aalg->desc; } } if (enc_len) { struct sadb_supported *sp; struct sadb_alg *ap; sp = (struct sadb_supported *) skb_put(skb, enc_len); ap = (struct sadb_alg *) (sp + 1); sp->sadb_supported_len = enc_len / sizeof(uint64_t); sp->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT; for (i = 0; ; i++) { struct xfrm_algo_desc *ealg = xfrm_ealg_get_byidx(i); if (!ealg) break; if (!ealg->pfkey_supported) continue; if (ealg->available) *ap++ = ealg->desc; } } out_put_algs: return skb; } static int pfkey_register(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { struct pfkey_sock *pfk = pfkey_sk(sk); struct sk_buff *supp_skb; if (hdr->sadb_msg_satype > SADB_SATYPE_MAX) return -EINVAL; if (hdr->sadb_msg_satype != SADB_SATYPE_UNSPEC) { if (pfk->registered&(1<<hdr->sadb_msg_satype)) return -EEXIST; pfk->registered |= (1<<hdr->sadb_msg_satype); } xfrm_probe_algs(); supp_skb = compose_sadb_supported(hdr, GFP_KERNEL); if (!supp_skb) { if (hdr->sadb_msg_satype != SADB_SATYPE_UNSPEC) pfk->registered &= ~(1<<hdr->sadb_msg_satype); return -ENOBUFS; } pfkey_broadcast(supp_skb, GFP_KERNEL, BROADCAST_REGISTERED, sk, sock_net(sk)); return 0; } static int unicast_flush_resp(struct sock *sk, const struct sadb_msg *ihdr) { struct sk_buff *skb; struct sadb_msg *hdr; skb = alloc_skb(sizeof(struct sadb_msg) + 16, GFP_ATOMIC); if (!skb) return -ENOBUFS; hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg)); memcpy(hdr, ihdr, sizeof(struct sadb_msg)); hdr->sadb_msg_errno = (uint8_t) 0; hdr->sadb_msg_len = (sizeof(struct sadb_msg) / sizeof(uint64_t)); return pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_ONE, sk, sock_net(sk)); } static int key_notify_sa_flush(const struct km_event *c) { struct sk_buff *skb; struct sadb_msg *hdr; skb = alloc_skb(sizeof(struct sadb_msg) + 16, GFP_ATOMIC); if (!skb) return -ENOBUFS; hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg)); hdr->sadb_msg_satype = pfkey_proto2satype(c->data.proto); hdr->sadb_msg_type = SADB_FLUSH; hdr->sadb_msg_seq = c->seq; hdr->sadb_msg_pid = c->portid; hdr->sadb_msg_version = PF_KEY_V2; hdr->sadb_msg_errno = (uint8_t) 0; hdr->sadb_msg_len = (sizeof(struct sadb_msg) / sizeof(uint64_t)); pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_ALL, NULL, c->net); return 0; } static int pfkey_flush(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { struct net *net = sock_net(sk); unsigned int proto; struct km_event c; struct xfrm_audit audit_info; int err, err2; proto = pfkey_satype2proto(hdr->sadb_msg_satype); if (proto == 0) return -EINVAL; audit_info.loginuid = audit_get_loginuid(current); audit_info.sessionid = audit_get_sessionid(current); audit_info.secid = 0; err = xfrm_state_flush(net, proto, &audit_info); err2 = unicast_flush_resp(sk, hdr); if (err || err2) { if (err == -ESRCH) /* empty table - go quietly */ err = 0; return err ? err : err2; } c.data.proto = proto; c.seq = hdr->sadb_msg_seq; c.portid = hdr->sadb_msg_pid; c.event = XFRM_MSG_FLUSHSA; c.net = net; km_state_notify(NULL, &c); return 0; } static int dump_sa(struct xfrm_state *x, int count, void *ptr) { struct pfkey_sock *pfk = ptr; struct sk_buff *out_skb; struct sadb_msg *out_hdr; if (!pfkey_can_dump(&pfk->sk)) return -ENOBUFS; out_skb = pfkey_xfrm_state2msg(x); if (IS_ERR(out_skb)) return PTR_ERR(out_skb); out_hdr = (struct sadb_msg *) out_skb->data; out_hdr->sadb_msg_version = pfk->dump.msg_version; out_hdr->sadb_msg_type = SADB_DUMP; out_hdr->sadb_msg_satype = pfkey_proto2satype(x->id.proto); out_hdr->sadb_msg_errno = 0; out_hdr->sadb_msg_reserved = 0; out_hdr->sadb_msg_seq = count + 1; out_hdr->sadb_msg_pid = pfk->dump.msg_portid; if (pfk->dump.skb) pfkey_broadcast(pfk->dump.skb, GFP_ATOMIC, BROADCAST_ONE, &pfk->sk, sock_net(&pfk->sk)); pfk->dump.skb = out_skb; return 0; } static int pfkey_dump_sa(struct pfkey_sock *pfk) { struct net *net = sock_net(&pfk->sk); return xfrm_state_walk(net, &pfk->dump.u.state, dump_sa, (void *) pfk); } static void pfkey_dump_sa_done(struct pfkey_sock *pfk) { xfrm_state_walk_done(&pfk->dump.u.state); } static int pfkey_dump(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { u8 proto; struct pfkey_sock *pfk = pfkey_sk(sk); if (pfk->dump.dump != NULL) return -EBUSY; proto = pfkey_satype2proto(hdr->sadb_msg_satype); if (proto == 0) return -EINVAL; pfk->dump.msg_version = hdr->sadb_msg_version; pfk->dump.msg_portid = hdr->sadb_msg_pid; pfk->dump.dump = pfkey_dump_sa; pfk->dump.done = pfkey_dump_sa_done; xfrm_state_walk_init(&pfk->dump.u.state, proto); return pfkey_do_dump(pfk); } static int pfkey_promisc(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { struct pfkey_sock *pfk = pfkey_sk(sk); int satype = hdr->sadb_msg_satype; bool reset_errno = false; if (hdr->sadb_msg_len == (sizeof(*hdr) / sizeof(uint64_t))) { reset_errno = true; if (satype != 0 && satype != 1) return -EINVAL; pfk->promisc = satype; } if (reset_errno && skb_cloned(skb)) skb = skb_copy(skb, GFP_KERNEL); else skb = skb_clone(skb, GFP_KERNEL); if (reset_errno && skb) { struct sadb_msg *new_hdr = (struct sadb_msg *) skb->data; new_hdr->sadb_msg_errno = 0; } pfkey_broadcast(skb, GFP_KERNEL, BROADCAST_ALL, NULL, sock_net(sk)); return 0; } static int check_reqid(struct xfrm_policy *xp, int dir, int count, void *ptr) { int i; u32 reqid = *(u32*)ptr; for (i=0; i<xp->xfrm_nr; i++) { if (xp->xfrm_vec[i].reqid == reqid) return -EEXIST; } return 0; } static u32 gen_reqid(struct net *net) { struct xfrm_policy_walk walk; u32 start; int rc; static u32 reqid = IPSEC_MANUAL_REQID_MAX; start = reqid; do { ++reqid; if (reqid == 0) reqid = IPSEC_MANUAL_REQID_MAX+1; xfrm_policy_walk_init(&walk, XFRM_POLICY_TYPE_MAIN); rc = xfrm_policy_walk(net, &walk, check_reqid, (void*)&reqid); xfrm_policy_walk_done(&walk); if (rc != -EEXIST) return reqid; } while (reqid != start); return 0; } static int parse_ipsecrequest(struct xfrm_policy *xp, struct sadb_x_ipsecrequest *rq) { struct net *net = xp_net(xp); struct xfrm_tmpl *t = xp->xfrm_vec + xp->xfrm_nr; int mode; if (xp->xfrm_nr >= XFRM_MAX_DEPTH) return -ELOOP; if (rq->sadb_x_ipsecrequest_mode == 0) return -EINVAL; t->id.proto = rq->sadb_x_ipsecrequest_proto; /* XXX check proto */ if ((mode = pfkey_mode_to_xfrm(rq->sadb_x_ipsecrequest_mode)) < 0) return -EINVAL; t->mode = mode; if (rq->sadb_x_ipsecrequest_level == IPSEC_LEVEL_USE) t->optional = 1; else if (rq->sadb_x_ipsecrequest_level == IPSEC_LEVEL_UNIQUE) { t->reqid = rq->sadb_x_ipsecrequest_reqid; if (t->reqid > IPSEC_MANUAL_REQID_MAX) t->reqid = 0; if (!t->reqid && !(t->reqid = gen_reqid(net))) return -ENOBUFS; } /* addresses present only in tunnel mode */ if (t->mode == XFRM_MODE_TUNNEL) { u8 *sa = (u8 *) (rq + 1); int family, socklen; family = pfkey_sockaddr_extract((struct sockaddr *)sa, &t->saddr); if (!family) return -EINVAL; socklen = pfkey_sockaddr_len(family); if (pfkey_sockaddr_extract((struct sockaddr *)(sa + socklen), &t->id.daddr) != family) return -EINVAL; t->encap_family = family; } else t->encap_family = xp->family; /* No way to set this via kame pfkey */ t->allalgs = 1; xp->xfrm_nr++; return 0; } static int parse_ipsecrequests(struct xfrm_policy *xp, struct sadb_x_policy *pol) { int err; int len = pol->sadb_x_policy_len*8 - sizeof(struct sadb_x_policy); struct sadb_x_ipsecrequest *rq = (void*)(pol+1); if (pol->sadb_x_policy_len * 8 < sizeof(struct sadb_x_policy)) return -EINVAL; while (len >= sizeof(struct sadb_x_ipsecrequest)) { if ((err = parse_ipsecrequest(xp, rq)) < 0) return err; len -= rq->sadb_x_ipsecrequest_len; rq = (void*)((u8*)rq + rq->sadb_x_ipsecrequest_len); } return 0; } static inline int pfkey_xfrm_policy2sec_ctx_size(const struct xfrm_policy *xp) { struct xfrm_sec_ctx *xfrm_ctx = xp->security; if (xfrm_ctx) { int len = sizeof(struct sadb_x_sec_ctx); len += xfrm_ctx->ctx_len; return PFKEY_ALIGN8(len); } return 0; } static int pfkey_xfrm_policy2msg_size(const struct xfrm_policy *xp) { const struct xfrm_tmpl *t; int sockaddr_size = pfkey_sockaddr_size(xp->family); int socklen = 0; int i; for (i=0; i<xp->xfrm_nr; i++) { t = xp->xfrm_vec + i; socklen += pfkey_sockaddr_len(t->encap_family); } return sizeof(struct sadb_msg) + (sizeof(struct sadb_lifetime) * 3) + (sizeof(struct sadb_address) * 2) + (sockaddr_size * 2) + sizeof(struct sadb_x_policy) + (xp->xfrm_nr * sizeof(struct sadb_x_ipsecrequest)) + (socklen * 2) + pfkey_xfrm_policy2sec_ctx_size(xp); } static struct sk_buff * pfkey_xfrm_policy2msg_prep(const struct xfrm_policy *xp) { struct sk_buff *skb; int size; size = pfkey_xfrm_policy2msg_size(xp); skb = alloc_skb(size + 16, GFP_ATOMIC); if (skb == NULL) return ERR_PTR(-ENOBUFS); return skb; } static int pfkey_xfrm_policy2msg(struct sk_buff *skb, const struct xfrm_policy *xp, int dir) { struct sadb_msg *hdr; struct sadb_address *addr; struct sadb_lifetime *lifetime; struct sadb_x_policy *pol; struct sadb_x_sec_ctx *sec_ctx; struct xfrm_sec_ctx *xfrm_ctx; int i; int size; int sockaddr_size = pfkey_sockaddr_size(xp->family); int socklen = pfkey_sockaddr_len(xp->family); size = pfkey_xfrm_policy2msg_size(xp); /* call should fill header later */ hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg)); memset(hdr, 0, size); /* XXX do we need this ? */ /* src address */ addr = (struct sadb_address*) skb_put(skb, sizeof(struct sadb_address)+sockaddr_size); addr->sadb_address_len = (sizeof(struct sadb_address)+sockaddr_size)/ sizeof(uint64_t); addr->sadb_address_exttype = SADB_EXT_ADDRESS_SRC; addr->sadb_address_proto = pfkey_proto_from_xfrm(xp->selector.proto); addr->sadb_address_prefixlen = xp->selector.prefixlen_s; addr->sadb_address_reserved = 0; if (!pfkey_sockaddr_fill(&xp->selector.saddr, xp->selector.sport, (struct sockaddr *) (addr + 1), xp->family)) BUG(); /* dst address */ addr = (struct sadb_address*) skb_put(skb, sizeof(struct sadb_address)+sockaddr_size); addr->sadb_address_len = (sizeof(struct sadb_address)+sockaddr_size)/ sizeof(uint64_t); addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST; addr->sadb_address_proto = pfkey_proto_from_xfrm(xp->selector.proto); addr->sadb_address_prefixlen = xp->selector.prefixlen_d; addr->sadb_address_reserved = 0; pfkey_sockaddr_fill(&xp->selector.daddr, xp->selector.dport, (struct sockaddr *) (addr + 1), xp->family); /* hard time */ lifetime = (struct sadb_lifetime *) skb_put(skb, sizeof(struct sadb_lifetime)); lifetime->sadb_lifetime_len = sizeof(struct sadb_lifetime)/sizeof(uint64_t); lifetime->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD; lifetime->sadb_lifetime_allocations = _X2KEY(xp->lft.hard_packet_limit); lifetime->sadb_lifetime_bytes = _X2KEY(xp->lft.hard_byte_limit); lifetime->sadb_lifetime_addtime = xp->lft.hard_add_expires_seconds; lifetime->sadb_lifetime_usetime = xp->lft.hard_use_expires_seconds; /* soft time */ lifetime = (struct sadb_lifetime *) skb_put(skb, sizeof(struct sadb_lifetime)); lifetime->sadb_lifetime_len = sizeof(struct sadb_lifetime)/sizeof(uint64_t); lifetime->sadb_lifetime_exttype = SADB_EXT_LIFETIME_SOFT; lifetime->sadb_lifetime_allocations = _X2KEY(xp->lft.soft_packet_limit); lifetime->sadb_lifetime_bytes = _X2KEY(xp->lft.soft_byte_limit); lifetime->sadb_lifetime_addtime = xp->lft.soft_add_expires_seconds; lifetime->sadb_lifetime_usetime = xp->lft.soft_use_expires_seconds; /* current time */ lifetime = (struct sadb_lifetime *) skb_put(skb, sizeof(struct sadb_lifetime)); lifetime->sadb_lifetime_len = sizeof(struct sadb_lifetime)/sizeof(uint64_t); lifetime->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT; lifetime->sadb_lifetime_allocations = xp->curlft.packets; lifetime->sadb_lifetime_bytes = xp->curlft.bytes; lifetime->sadb_lifetime_addtime = xp->curlft.add_time; lifetime->sadb_lifetime_usetime = xp->curlft.use_time; pol = (struct sadb_x_policy *) skb_put(skb, sizeof(struct sadb_x_policy)); pol->sadb_x_policy_len = sizeof(struct sadb_x_policy)/sizeof(uint64_t); pol->sadb_x_policy_exttype = SADB_X_EXT_POLICY; pol->sadb_x_policy_type = IPSEC_POLICY_DISCARD; if (xp->action == XFRM_POLICY_ALLOW) { if (xp->xfrm_nr) pol->sadb_x_policy_type = IPSEC_POLICY_IPSEC; else pol->sadb_x_policy_type = IPSEC_POLICY_NONE; } pol->sadb_x_policy_dir = dir+1; pol->sadb_x_policy_id = xp->index; pol->sadb_x_policy_priority = xp->priority; for (i=0; i<xp->xfrm_nr; i++) { const struct xfrm_tmpl *t = xp->xfrm_vec + i; struct sadb_x_ipsecrequest *rq; int req_size; int mode; req_size = sizeof(struct sadb_x_ipsecrequest); if (t->mode == XFRM_MODE_TUNNEL) { socklen = pfkey_sockaddr_len(t->encap_family); req_size += socklen * 2; } else { size -= 2*socklen; } rq = (void*)skb_put(skb, req_size); pol->sadb_x_policy_len += req_size/8; memset(rq, 0, sizeof(*rq)); rq->sadb_x_ipsecrequest_len = req_size; rq->sadb_x_ipsecrequest_proto = t->id.proto; if ((mode = pfkey_mode_from_xfrm(t->mode)) < 0) return -EINVAL; rq->sadb_x_ipsecrequest_mode = mode; rq->sadb_x_ipsecrequest_level = IPSEC_LEVEL_REQUIRE; if (t->reqid) rq->sadb_x_ipsecrequest_level = IPSEC_LEVEL_UNIQUE; if (t->optional) rq->sadb_x_ipsecrequest_level = IPSEC_LEVEL_USE; rq->sadb_x_ipsecrequest_reqid = t->reqid; if (t->mode == XFRM_MODE_TUNNEL) { u8 *sa = (void *)(rq + 1); pfkey_sockaddr_fill(&t->saddr, 0, (struct sockaddr *)sa, t->encap_family); pfkey_sockaddr_fill(&t->id.daddr, 0, (struct sockaddr *) (sa + socklen), t->encap_family); } } /* security context */ if ((xfrm_ctx = xp->security)) { int ctx_size = pfkey_xfrm_policy2sec_ctx_size(xp); sec_ctx = (struct sadb_x_sec_ctx *) skb_put(skb, ctx_size); sec_ctx->sadb_x_sec_len = ctx_size / sizeof(uint64_t); sec_ctx->sadb_x_sec_exttype = SADB_X_EXT_SEC_CTX; sec_ctx->sadb_x_ctx_doi = xfrm_ctx->ctx_doi; sec_ctx->sadb_x_ctx_alg = xfrm_ctx->ctx_alg; sec_ctx->sadb_x_ctx_len = xfrm_ctx->ctx_len; memcpy(sec_ctx + 1, xfrm_ctx->ctx_str, xfrm_ctx->ctx_len); } hdr->sadb_msg_len = size / sizeof(uint64_t); hdr->sadb_msg_reserved = atomic_read(&xp->refcnt); return 0; } static int key_notify_policy(struct xfrm_policy *xp, int dir, const struct km_event *c) { struct sk_buff *out_skb; struct sadb_msg *out_hdr; int err; out_skb = pfkey_xfrm_policy2msg_prep(xp); if (IS_ERR(out_skb)) return PTR_ERR(out_skb); err = pfkey_xfrm_policy2msg(out_skb, xp, dir); if (err < 0) return err; out_hdr = (struct sadb_msg *) out_skb->data; out_hdr->sadb_msg_version = PF_KEY_V2; if (c->data.byid && c->event == XFRM_MSG_DELPOLICY) out_hdr->sadb_msg_type = SADB_X_SPDDELETE2; else out_hdr->sadb_msg_type = event2poltype(c->event); out_hdr->sadb_msg_errno = 0; out_hdr->sadb_msg_seq = c->seq; out_hdr->sadb_msg_pid = c->portid; pfkey_broadcast(out_skb, GFP_ATOMIC, BROADCAST_ALL, NULL, xp_net(xp)); return 0; } static int pfkey_spdadd(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { struct net *net = sock_net(sk); int err = 0; struct sadb_lifetime *lifetime; struct sadb_address *sa; struct sadb_x_policy *pol; struct xfrm_policy *xp; struct km_event c; struct sadb_x_sec_ctx *sec_ctx; if (!present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1], ext_hdrs[SADB_EXT_ADDRESS_DST-1]) || !ext_hdrs[SADB_X_EXT_POLICY-1]) return -EINVAL; pol = ext_hdrs[SADB_X_EXT_POLICY-1]; if (pol->sadb_x_policy_type > IPSEC_POLICY_IPSEC) return -EINVAL; if (!pol->sadb_x_policy_dir || pol->sadb_x_policy_dir >= IPSEC_DIR_MAX) return -EINVAL; xp = xfrm_policy_alloc(net, GFP_KERNEL); if (xp == NULL) return -ENOBUFS; xp->action = (pol->sadb_x_policy_type == IPSEC_POLICY_DISCARD ? XFRM_POLICY_BLOCK : XFRM_POLICY_ALLOW); xp->priority = pol->sadb_x_policy_priority; sa = ext_hdrs[SADB_EXT_ADDRESS_SRC-1]; xp->family = pfkey_sadb_addr2xfrm_addr(sa, &xp->selector.saddr); if (!xp->family) { err = -EINVAL; goto out; } xp->selector.family = xp->family; xp->selector.prefixlen_s = sa->sadb_address_prefixlen; xp->selector.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto); xp->selector.sport = ((struct sockaddr_in *)(sa+1))->sin_port; if (xp->selector.sport) xp->selector.sport_mask = htons(0xffff); sa = ext_hdrs[SADB_EXT_ADDRESS_DST-1]; pfkey_sadb_addr2xfrm_addr(sa, &xp->selector.daddr); xp->selector.prefixlen_d = sa->sadb_address_prefixlen; /* Amusing, we set this twice. KAME apps appear to set same value * in both addresses. */ xp->selector.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto); xp->selector.dport = ((struct sockaddr_in *)(sa+1))->sin_port; if (xp->selector.dport) xp->selector.dport_mask = htons(0xffff); sec_ctx = ext_hdrs[SADB_X_EXT_SEC_CTX - 1]; if (sec_ctx != NULL) { struct xfrm_user_sec_ctx *uctx = pfkey_sadb2xfrm_user_sec_ctx(sec_ctx); if (!uctx) { err = -ENOBUFS; goto out; } err = security_xfrm_policy_alloc(&xp->security, uctx); kfree(uctx); if (err) goto out; } xp->lft.soft_byte_limit = XFRM_INF; xp->lft.hard_byte_limit = XFRM_INF; xp->lft.soft_packet_limit = XFRM_INF; xp->lft.hard_packet_limit = XFRM_INF; if ((lifetime = ext_hdrs[SADB_EXT_LIFETIME_HARD-1]) != NULL) { xp->lft.hard_packet_limit = _KEY2X(lifetime->sadb_lifetime_allocations); xp->lft.hard_byte_limit = _KEY2X(lifetime->sadb_lifetime_bytes); xp->lft.hard_add_expires_seconds = lifetime->sadb_lifetime_addtime; xp->lft.hard_use_expires_seconds = lifetime->sadb_lifetime_usetime; } if ((lifetime = ext_hdrs[SADB_EXT_LIFETIME_SOFT-1]) != NULL) { xp->lft.soft_packet_limit = _KEY2X(lifetime->sadb_lifetime_allocations); xp->lft.soft_byte_limit = _KEY2X(lifetime->sadb_lifetime_bytes); xp->lft.soft_add_expires_seconds = lifetime->sadb_lifetime_addtime; xp->lft.soft_use_expires_seconds = lifetime->sadb_lifetime_usetime; } xp->xfrm_nr = 0; if (pol->sadb_x_policy_type == IPSEC_POLICY_IPSEC && (err = parse_ipsecrequests(xp, pol)) < 0) goto out; err = xfrm_policy_insert(pol->sadb_x_policy_dir-1, xp, hdr->sadb_msg_type != SADB_X_SPDUPDATE); xfrm_audit_policy_add(xp, err ? 0 : 1, audit_get_loginuid(current), audit_get_sessionid(current), 0); if (err) goto out; if (hdr->sadb_msg_type == SADB_X_SPDUPDATE) c.event = XFRM_MSG_UPDPOLICY; else c.event = XFRM_MSG_NEWPOLICY; c.seq = hdr->sadb_msg_seq; c.portid = hdr->sadb_msg_pid; km_policy_notify(xp, pol->sadb_x_policy_dir-1, &c); xfrm_pol_put(xp); return 0; out: xp->walk.dead = 1; xfrm_policy_destroy(xp); return err; } static int pfkey_spddelete(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { struct net *net = sock_net(sk); int err; struct sadb_address *sa; struct sadb_x_policy *pol; struct xfrm_policy *xp; struct xfrm_selector sel; struct km_event c; struct sadb_x_sec_ctx *sec_ctx; struct xfrm_sec_ctx *pol_ctx = NULL; if (!present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1], ext_hdrs[SADB_EXT_ADDRESS_DST-1]) || !ext_hdrs[SADB_X_EXT_POLICY-1]) return -EINVAL; pol = ext_hdrs[SADB_X_EXT_POLICY-1]; if (!pol->sadb_x_policy_dir || pol->sadb_x_policy_dir >= IPSEC_DIR_MAX) return -EINVAL; memset(&sel, 0, sizeof(sel)); sa = ext_hdrs[SADB_EXT_ADDRESS_SRC-1]; sel.family = pfkey_sadb_addr2xfrm_addr(sa, &sel.saddr); sel.prefixlen_s = sa->sadb_address_prefixlen; sel.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto); sel.sport = ((struct sockaddr_in *)(sa+1))->sin_port; if (sel.sport) sel.sport_mask = htons(0xffff); sa = ext_hdrs[SADB_EXT_ADDRESS_DST-1]; pfkey_sadb_addr2xfrm_addr(sa, &sel.daddr); sel.prefixlen_d = sa->sadb_address_prefixlen; sel.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto); sel.dport = ((struct sockaddr_in *)(sa+1))->sin_port; if (sel.dport) sel.dport_mask = htons(0xffff); sec_ctx = ext_hdrs[SADB_X_EXT_SEC_CTX - 1]; if (sec_ctx != NULL) { struct xfrm_user_sec_ctx *uctx = pfkey_sadb2xfrm_user_sec_ctx(sec_ctx); if (!uctx) return -ENOMEM; err = security_xfrm_policy_alloc(&pol_ctx, uctx); kfree(uctx); if (err) return err; } xp = xfrm_policy_bysel_ctx(net, DUMMY_MARK, XFRM_POLICY_TYPE_MAIN, pol->sadb_x_policy_dir - 1, &sel, pol_ctx, 1, &err); security_xfrm_policy_free(pol_ctx); if (xp == NULL) return -ENOENT; xfrm_audit_policy_delete(xp, err ? 0 : 1, audit_get_loginuid(current), audit_get_sessionid(current), 0); if (err) goto out; c.seq = hdr->sadb_msg_seq; c.portid = hdr->sadb_msg_pid; c.data.byid = 0; c.event = XFRM_MSG_DELPOLICY; km_policy_notify(xp, pol->sadb_x_policy_dir-1, &c); out: xfrm_pol_put(xp); if (err == 0) xfrm_garbage_collect(net); return err; } static int key_pol_get_resp(struct sock *sk, struct xfrm_policy *xp, const struct sadb_msg *hdr, int dir) { int err; struct sk_buff *out_skb; struct sadb_msg *out_hdr; err = 0; out_skb = pfkey_xfrm_policy2msg_prep(xp); if (IS_ERR(out_skb)) { err = PTR_ERR(out_skb); goto out; } err = pfkey_xfrm_policy2msg(out_skb, xp, dir); if (err < 0) goto out; out_hdr = (struct sadb_msg *) out_skb->data; out_hdr->sadb_msg_version = hdr->sadb_msg_version; out_hdr->sadb_msg_type = hdr->sadb_msg_type; out_hdr->sadb_msg_satype = 0; out_hdr->sadb_msg_errno = 0; out_hdr->sadb_msg_seq = hdr->sadb_msg_seq; out_hdr->sadb_msg_pid = hdr->sadb_msg_pid; pfkey_broadcast(out_skb, GFP_ATOMIC, BROADCAST_ONE, sk, xp_net(xp)); err = 0; out: return err; } #ifdef CONFIG_NET_KEY_MIGRATE static int pfkey_sockaddr_pair_size(sa_family_t family) { return PFKEY_ALIGN8(pfkey_sockaddr_len(family) * 2); } static int parse_sockaddr_pair(struct sockaddr *sa, int ext_len, xfrm_address_t *saddr, xfrm_address_t *daddr, u16 *family) { int af, socklen; if (ext_len < pfkey_sockaddr_pair_size(sa->sa_family)) return -EINVAL; af = pfkey_sockaddr_extract(sa, saddr); if (!af) return -EINVAL; socklen = pfkey_sockaddr_len(af); if (pfkey_sockaddr_extract((struct sockaddr *) (((u8 *)sa) + socklen), daddr) != af) return -EINVAL; *family = af; return 0; } static int ipsecrequests_to_migrate(struct sadb_x_ipsecrequest *rq1, int len, struct xfrm_migrate *m) { int err; struct sadb_x_ipsecrequest *rq2; int mode; if (len <= sizeof(struct sadb_x_ipsecrequest) || len < rq1->sadb_x_ipsecrequest_len) return -EINVAL; /* old endoints */ err = parse_sockaddr_pair((struct sockaddr *)(rq1 + 1), rq1->sadb_x_ipsecrequest_len, &m->old_saddr, &m->old_daddr, &m->old_family); if (err) return err; rq2 = (struct sadb_x_ipsecrequest *)((u8 *)rq1 + rq1->sadb_x_ipsecrequest_len); len -= rq1->sadb_x_ipsecrequest_len; if (len <= sizeof(struct sadb_x_ipsecrequest) || len < rq2->sadb_x_ipsecrequest_len) return -EINVAL; /* new endpoints */ err = parse_sockaddr_pair((struct sockaddr *)(rq2 + 1), rq2->sadb_x_ipsecrequest_len, &m->new_saddr, &m->new_daddr, &m->new_family); if (err) return err; if (rq1->sadb_x_ipsecrequest_proto != rq2->sadb_x_ipsecrequest_proto || rq1->sadb_x_ipsecrequest_mode != rq2->sadb_x_ipsecrequest_mode || rq1->sadb_x_ipsecrequest_reqid != rq2->sadb_x_ipsecrequest_reqid) return -EINVAL; m->proto = rq1->sadb_x_ipsecrequest_proto; if ((mode = pfkey_mode_to_xfrm(rq1->sadb_x_ipsecrequest_mode)) < 0) return -EINVAL; m->mode = mode; m->reqid = rq1->sadb_x_ipsecrequest_reqid; return ((int)(rq1->sadb_x_ipsecrequest_len + rq2->sadb_x_ipsecrequest_len)); } static int pfkey_migrate(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { int i, len, ret, err = -EINVAL; u8 dir; struct sadb_address *sa; struct sadb_x_kmaddress *kma; struct sadb_x_policy *pol; struct sadb_x_ipsecrequest *rq; struct xfrm_selector sel; struct xfrm_migrate m[XFRM_MAX_DEPTH]; struct xfrm_kmaddress k; if (!present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC - 1], ext_hdrs[SADB_EXT_ADDRESS_DST - 1]) || !ext_hdrs[SADB_X_EXT_POLICY - 1]) { err = -EINVAL; goto out; } kma = ext_hdrs[SADB_X_EXT_KMADDRESS - 1]; pol = ext_hdrs[SADB_X_EXT_POLICY - 1]; if (pol->sadb_x_policy_dir >= IPSEC_DIR_MAX) { err = -EINVAL; goto out; } if (kma) { /* convert sadb_x_kmaddress to xfrm_kmaddress */ k.reserved = kma->sadb_x_kmaddress_reserved; ret = parse_sockaddr_pair((struct sockaddr *)(kma + 1), 8*(kma->sadb_x_kmaddress_len) - sizeof(*kma), &k.local, &k.remote, &k.family); if (ret < 0) { err = ret; goto out; } } dir = pol->sadb_x_policy_dir - 1; memset(&sel, 0, sizeof(sel)); /* set source address info of selector */ sa = ext_hdrs[SADB_EXT_ADDRESS_SRC - 1]; sel.family = pfkey_sadb_addr2xfrm_addr(sa, &sel.saddr); sel.prefixlen_s = sa->sadb_address_prefixlen; sel.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto); sel.sport = ((struct sockaddr_in *)(sa + 1))->sin_port; if (sel.sport) sel.sport_mask = htons(0xffff); /* set destination address info of selector */ sa = ext_hdrs[SADB_EXT_ADDRESS_DST - 1], pfkey_sadb_addr2xfrm_addr(sa, &sel.daddr); sel.prefixlen_d = sa->sadb_address_prefixlen; sel.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto); sel.dport = ((struct sockaddr_in *)(sa + 1))->sin_port; if (sel.dport) sel.dport_mask = htons(0xffff); rq = (struct sadb_x_ipsecrequest *)(pol + 1); /* extract ipsecrequests */ i = 0; len = pol->sadb_x_policy_len * 8 - sizeof(struct sadb_x_policy); while (len > 0 && i < XFRM_MAX_DEPTH) { ret = ipsecrequests_to_migrate(rq, len, &m[i]); if (ret < 0) { err = ret; goto out; } else { rq = (struct sadb_x_ipsecrequest *)((u8 *)rq + ret); len -= ret; i++; } } if (!i || len > 0) { err = -EINVAL; goto out; } return xfrm_migrate(&sel, dir, XFRM_POLICY_TYPE_MAIN, m, i, kma ? &k : NULL); out: return err; } #else static int pfkey_migrate(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { return -ENOPROTOOPT; } #endif static int pfkey_spdget(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { struct net *net = sock_net(sk); unsigned int dir; int err = 0, delete; struct sadb_x_policy *pol; struct xfrm_policy *xp; struct km_event c; if ((pol = ext_hdrs[SADB_X_EXT_POLICY-1]) == NULL) return -EINVAL; dir = xfrm_policy_id2dir(pol->sadb_x_policy_id); if (dir >= XFRM_POLICY_MAX) return -EINVAL; delete = (hdr->sadb_msg_type == SADB_X_SPDDELETE2); xp = xfrm_policy_byid(net, DUMMY_MARK, XFRM_POLICY_TYPE_MAIN, dir, pol->sadb_x_policy_id, delete, &err); if (xp == NULL) return -ENOENT; if (delete) { xfrm_audit_policy_delete(xp, err ? 0 : 1, audit_get_loginuid(current), audit_get_sessionid(current), 0); if (err) goto out; c.seq = hdr->sadb_msg_seq; c.portid = hdr->sadb_msg_pid; c.data.byid = 1; c.event = XFRM_MSG_DELPOLICY; km_policy_notify(xp, dir, &c); } else { err = key_pol_get_resp(sk, xp, hdr, dir); } out: xfrm_pol_put(xp); if (delete && err == 0) xfrm_garbage_collect(net); return err; } static int dump_sp(struct xfrm_policy *xp, int dir, int count, void *ptr) { struct pfkey_sock *pfk = ptr; struct sk_buff *out_skb; struct sadb_msg *out_hdr; int err; if (!pfkey_can_dump(&pfk->sk)) return -ENOBUFS; out_skb = pfkey_xfrm_policy2msg_prep(xp); if (IS_ERR(out_skb)) return PTR_ERR(out_skb); err = pfkey_xfrm_policy2msg(out_skb, xp, dir); if (err < 0) return err; out_hdr = (struct sadb_msg *) out_skb->data; out_hdr->sadb_msg_version = pfk->dump.msg_version; out_hdr->sadb_msg_type = SADB_X_SPDDUMP; out_hdr->sadb_msg_satype = SADB_SATYPE_UNSPEC; out_hdr->sadb_msg_errno = 0; out_hdr->sadb_msg_seq = count + 1; out_hdr->sadb_msg_pid = pfk->dump.msg_portid; if (pfk->dump.skb) pfkey_broadcast(pfk->dump.skb, GFP_ATOMIC, BROADCAST_ONE, &pfk->sk, sock_net(&pfk->sk)); pfk->dump.skb = out_skb; return 0; } static int pfkey_dump_sp(struct pfkey_sock *pfk) { struct net *net = sock_net(&pfk->sk); return xfrm_policy_walk(net, &pfk->dump.u.policy, dump_sp, (void *) pfk); } static void pfkey_dump_sp_done(struct pfkey_sock *pfk) { xfrm_policy_walk_done(&pfk->dump.u.policy); } static int pfkey_spddump(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { struct pfkey_sock *pfk = pfkey_sk(sk); if (pfk->dump.dump != NULL) return -EBUSY; pfk->dump.msg_version = hdr->sadb_msg_version; pfk->dump.msg_portid = hdr->sadb_msg_pid; pfk->dump.dump = pfkey_dump_sp; pfk->dump.done = pfkey_dump_sp_done; xfrm_policy_walk_init(&pfk->dump.u.policy, XFRM_POLICY_TYPE_MAIN); return pfkey_do_dump(pfk); } static int key_notify_policy_flush(const struct km_event *c) { struct sk_buff *skb_out; struct sadb_msg *hdr; skb_out = alloc_skb(sizeof(struct sadb_msg) + 16, GFP_ATOMIC); if (!skb_out) return -ENOBUFS; hdr = (struct sadb_msg *) skb_put(skb_out, sizeof(struct sadb_msg)); hdr->sadb_msg_type = SADB_X_SPDFLUSH; hdr->sadb_msg_seq = c->seq; hdr->sadb_msg_pid = c->portid; hdr->sadb_msg_version = PF_KEY_V2; hdr->sadb_msg_errno = (uint8_t) 0; hdr->sadb_msg_satype = SADB_SATYPE_UNSPEC; hdr->sadb_msg_len = (sizeof(struct sadb_msg) / sizeof(uint64_t)); pfkey_broadcast(skb_out, GFP_ATOMIC, BROADCAST_ALL, NULL, c->net); return 0; } static int pfkey_spdflush(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { struct net *net = sock_net(sk); struct km_event c; struct xfrm_audit audit_info; int err, err2; audit_info.loginuid = audit_get_loginuid(current); audit_info.sessionid = audit_get_sessionid(current); audit_info.secid = 0; err = xfrm_policy_flush(net, XFRM_POLICY_TYPE_MAIN, &audit_info); err2 = unicast_flush_resp(sk, hdr); if (err || err2) { if (err == -ESRCH) /* empty table - old silent behavior */ return 0; return err; } c.data.type = XFRM_POLICY_TYPE_MAIN; c.event = XFRM_MSG_FLUSHPOLICY; c.portid = hdr->sadb_msg_pid; c.seq = hdr->sadb_msg_seq; c.net = net; km_policy_notify(NULL, 0, &c); return 0; } typedef int (*pfkey_handler)(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs); static pfkey_handler pfkey_funcs[SADB_MAX + 1] = { [SADB_RESERVED] = pfkey_reserved, [SADB_GETSPI] = pfkey_getspi, [SADB_UPDATE] = pfkey_add, [SADB_ADD] = pfkey_add, [SADB_DELETE] = pfkey_delete, [SADB_GET] = pfkey_get, [SADB_ACQUIRE] = pfkey_acquire, [SADB_REGISTER] = pfkey_register, [SADB_EXPIRE] = NULL, [SADB_FLUSH] = pfkey_flush, [SADB_DUMP] = pfkey_dump, [SADB_X_PROMISC] = pfkey_promisc, [SADB_X_PCHANGE] = NULL, [SADB_X_SPDUPDATE] = pfkey_spdadd, [SADB_X_SPDADD] = pfkey_spdadd, [SADB_X_SPDDELETE] = pfkey_spddelete, [SADB_X_SPDGET] = pfkey_spdget, [SADB_X_SPDACQUIRE] = NULL, [SADB_X_SPDDUMP] = pfkey_spddump, [SADB_X_SPDFLUSH] = pfkey_spdflush, [SADB_X_SPDSETIDX] = pfkey_spdadd, [SADB_X_SPDDELETE2] = pfkey_spdget, [SADB_X_MIGRATE] = pfkey_migrate, }; static int pfkey_process(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr) { void *ext_hdrs[SADB_EXT_MAX]; int err; pfkey_broadcast(skb_clone(skb, GFP_KERNEL), GFP_KERNEL, BROADCAST_PROMISC_ONLY, NULL, sock_net(sk)); memset(ext_hdrs, 0, sizeof(ext_hdrs)); err = parse_exthdrs(skb, hdr, ext_hdrs); if (!err) { err = -EOPNOTSUPP; if (pfkey_funcs[hdr->sadb_msg_type]) err = pfkey_funcs[hdr->sadb_msg_type](sk, skb, hdr, ext_hdrs); } return err; } static struct sadb_msg *pfkey_get_base_msg(struct sk_buff *skb, int *errp) { struct sadb_msg *hdr = NULL; if (skb->len < sizeof(*hdr)) { *errp = -EMSGSIZE; } else { hdr = (struct sadb_msg *) skb->data; if (hdr->sadb_msg_version != PF_KEY_V2 || hdr->sadb_msg_reserved != 0 || (hdr->sadb_msg_type <= SADB_RESERVED || hdr->sadb_msg_type > SADB_MAX)) { hdr = NULL; *errp = -EINVAL; } else if (hdr->sadb_msg_len != (skb->len / sizeof(uint64_t)) || hdr->sadb_msg_len < (sizeof(struct sadb_msg) / sizeof(uint64_t))) { hdr = NULL; *errp = -EMSGSIZE; } else { *errp = 0; } } return hdr; } static inline int aalg_tmpl_set(const struct xfrm_tmpl *t, const struct xfrm_algo_desc *d) { unsigned int id = d->desc.sadb_alg_id; if (id >= sizeof(t->aalgos) * 8) return 0; return (t->aalgos >> id) & 1; } static inline int ealg_tmpl_set(const struct xfrm_tmpl *t, const struct xfrm_algo_desc *d) { unsigned int id = d->desc.sadb_alg_id; if (id >= sizeof(t->ealgos) * 8) return 0; return (t->ealgos >> id) & 1; } static int count_ah_combs(const struct xfrm_tmpl *t) { int i, sz = 0; for (i = 0; ; i++) { const struct xfrm_algo_desc *aalg = xfrm_aalg_get_byidx(i); if (!aalg) break; if (!aalg->pfkey_supported) continue; if (aalg_tmpl_set(t, aalg) && aalg->available) sz += sizeof(struct sadb_comb); } return sz + sizeof(struct sadb_prop); } static int count_esp_combs(const struct xfrm_tmpl *t) { int i, k, sz = 0; for (i = 0; ; i++) { const struct xfrm_algo_desc *ealg = xfrm_ealg_get_byidx(i); if (!ealg) break; if (!ealg->pfkey_supported) continue; if (!(ealg_tmpl_set(t, ealg) && ealg->available)) continue; for (k = 1; ; k++) { const struct xfrm_algo_desc *aalg = xfrm_aalg_get_byidx(k); if (!aalg) break; if (!aalg->pfkey_supported) continue; if (aalg_tmpl_set(t, aalg) && aalg->available) sz += sizeof(struct sadb_comb); } } return sz + sizeof(struct sadb_prop); } static void dump_ah_combs(struct sk_buff *skb, const struct xfrm_tmpl *t) { struct sadb_prop *p; int i; p = (struct sadb_prop*)skb_put(skb, sizeof(struct sadb_prop)); p->sadb_prop_len = sizeof(struct sadb_prop)/8; p->sadb_prop_exttype = SADB_EXT_PROPOSAL; p->sadb_prop_replay = 32; memset(p->sadb_prop_reserved, 0, sizeof(p->sadb_prop_reserved)); for (i = 0; ; i++) { const struct xfrm_algo_desc *aalg = xfrm_aalg_get_byidx(i); if (!aalg) break; if (!aalg->pfkey_supported) continue; if (aalg_tmpl_set(t, aalg) && aalg->available) { struct sadb_comb *c; c = (struct sadb_comb*)skb_put(skb, sizeof(struct sadb_comb)); memset(c, 0, sizeof(*c)); p->sadb_prop_len += sizeof(struct sadb_comb)/8; c->sadb_comb_auth = aalg->desc.sadb_alg_id; c->sadb_comb_auth_minbits = aalg->desc.sadb_alg_minbits; c->sadb_comb_auth_maxbits = aalg->desc.sadb_alg_maxbits; c->sadb_comb_hard_addtime = 24*60*60; c->sadb_comb_soft_addtime = 20*60*60; c->sadb_comb_hard_usetime = 8*60*60; c->sadb_comb_soft_usetime = 7*60*60; } } } static void dump_esp_combs(struct sk_buff *skb, const struct xfrm_tmpl *t) { struct sadb_prop *p; int i, k; p = (struct sadb_prop*)skb_put(skb, sizeof(struct sadb_prop)); p->sadb_prop_len = sizeof(struct sadb_prop)/8; p->sadb_prop_exttype = SADB_EXT_PROPOSAL; p->sadb_prop_replay = 32; memset(p->sadb_prop_reserved, 0, sizeof(p->sadb_prop_reserved)); for (i=0; ; i++) { const struct xfrm_algo_desc *ealg = xfrm_ealg_get_byidx(i); if (!ealg) break; if (!ealg->pfkey_supported) continue; if (!(ealg_tmpl_set(t, ealg) && ealg->available)) continue; for (k = 1; ; k++) { struct sadb_comb *c; const struct xfrm_algo_desc *aalg = xfrm_aalg_get_byidx(k); if (!aalg) break; if (!aalg->pfkey_supported) continue; if (!(aalg_tmpl_set(t, aalg) && aalg->available)) continue; c = (struct sadb_comb*)skb_put(skb, sizeof(struct sadb_comb)); memset(c, 0, sizeof(*c)); p->sadb_prop_len += sizeof(struct sadb_comb)/8; c->sadb_comb_auth = aalg->desc.sadb_alg_id; c->sadb_comb_auth_minbits = aalg->desc.sadb_alg_minbits; c->sadb_comb_auth_maxbits = aalg->desc.sadb_alg_maxbits; c->sadb_comb_encrypt = ealg->desc.sadb_alg_id; c->sadb_comb_encrypt_minbits = ealg->desc.sadb_alg_minbits; c->sadb_comb_encrypt_maxbits = ealg->desc.sadb_alg_maxbits; c->sadb_comb_hard_addtime = 24*60*60; c->sadb_comb_soft_addtime = 20*60*60; c->sadb_comb_hard_usetime = 8*60*60; c->sadb_comb_soft_usetime = 7*60*60; } } } static int key_notify_policy_expire(struct xfrm_policy *xp, const struct km_event *c) { return 0; } static int key_notify_sa_expire(struct xfrm_state *x, const struct km_event *c) { struct sk_buff *out_skb; struct sadb_msg *out_hdr; int hard; int hsc; hard = c->data.hard; if (hard) hsc = 2; else hsc = 1; out_skb = pfkey_xfrm_state2msg_expire(x, hsc); if (IS_ERR(out_skb)) return PTR_ERR(out_skb); out_hdr = (struct sadb_msg *) out_skb->data; out_hdr->sadb_msg_version = PF_KEY_V2; out_hdr->sadb_msg_type = SADB_EXPIRE; out_hdr->sadb_msg_satype = pfkey_proto2satype(x->id.proto); out_hdr->sadb_msg_errno = 0; out_hdr->sadb_msg_reserved = 0; out_hdr->sadb_msg_seq = 0; out_hdr->sadb_msg_pid = 0; pfkey_broadcast(out_skb, GFP_ATOMIC, BROADCAST_REGISTERED, NULL, xs_net(x)); return 0; } static int pfkey_send_notify(struct xfrm_state *x, const struct km_event *c) { struct net *net = x ? xs_net(x) : c->net; struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id); if (atomic_read(&net_pfkey->socks_nr) == 0) return 0; switch (c->event) { case XFRM_MSG_EXPIRE: return key_notify_sa_expire(x, c); case XFRM_MSG_DELSA: case XFRM_MSG_NEWSA: case XFRM_MSG_UPDSA: return key_notify_sa(x, c); case XFRM_MSG_FLUSHSA: return key_notify_sa_flush(c); case XFRM_MSG_NEWAE: /* not yet supported */ break; default: pr_err("pfkey: Unknown SA event %d\n", c->event); break; } return 0; } static int pfkey_send_policy_notify(struct xfrm_policy *xp, int dir, const struct km_event *c) { if (xp && xp->type != XFRM_POLICY_TYPE_MAIN) return 0; switch (c->event) { case XFRM_MSG_POLEXPIRE: return key_notify_policy_expire(xp, c); case XFRM_MSG_DELPOLICY: case XFRM_MSG_NEWPOLICY: case XFRM_MSG_UPDPOLICY: return key_notify_policy(xp, dir, c); case XFRM_MSG_FLUSHPOLICY: if (c->data.type != XFRM_POLICY_TYPE_MAIN) break; return key_notify_policy_flush(c); default: pr_err("pfkey: Unknown policy event %d\n", c->event); break; } return 0; } static u32 get_acqseq(void) { u32 res; static atomic_t acqseq; do { res = atomic_inc_return(&acqseq); } while (!res); return res; } static int pfkey_send_acquire(struct xfrm_state *x, struct xfrm_tmpl *t, struct xfrm_policy *xp) { struct sk_buff *skb; struct sadb_msg *hdr; struct sadb_address *addr; struct sadb_x_policy *pol; int sockaddr_size; int size; struct sadb_x_sec_ctx *sec_ctx; struct xfrm_sec_ctx *xfrm_ctx; int ctx_size = 0; sockaddr_size = pfkey_sockaddr_size(x->props.family); if (!sockaddr_size) return -EINVAL; size = sizeof(struct sadb_msg) + (sizeof(struct sadb_address) * 2) + (sockaddr_size * 2) + sizeof(struct sadb_x_policy); if (x->id.proto == IPPROTO_AH) size += count_ah_combs(t); else if (x->id.proto == IPPROTO_ESP) size += count_esp_combs(t); if ((xfrm_ctx = x->security)) { ctx_size = PFKEY_ALIGN8(xfrm_ctx->ctx_len); size += sizeof(struct sadb_x_sec_ctx) + ctx_size; } skb = alloc_skb(size + 16, GFP_ATOMIC); if (skb == NULL) return -ENOMEM; hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg)); hdr->sadb_msg_version = PF_KEY_V2; hdr->sadb_msg_type = SADB_ACQUIRE; hdr->sadb_msg_satype = pfkey_proto2satype(x->id.proto); hdr->sadb_msg_len = size / sizeof(uint64_t); hdr->sadb_msg_errno = 0; hdr->sadb_msg_reserved = 0; hdr->sadb_msg_seq = x->km.seq = get_acqseq(); hdr->sadb_msg_pid = 0; /* src address */ addr = (struct sadb_address*) skb_put(skb, sizeof(struct sadb_address)+sockaddr_size); addr->sadb_address_len = (sizeof(struct sadb_address)+sockaddr_size)/ sizeof(uint64_t); addr->sadb_address_exttype = SADB_EXT_ADDRESS_SRC; addr->sadb_address_proto = 0; addr->sadb_address_reserved = 0; addr->sadb_address_prefixlen = pfkey_sockaddr_fill(&x->props.saddr, 0, (struct sockaddr *) (addr + 1), x->props.family); if (!addr->sadb_address_prefixlen) BUG(); /* dst address */ addr = (struct sadb_address*) skb_put(skb, sizeof(struct sadb_address)+sockaddr_size); addr->sadb_address_len = (sizeof(struct sadb_address)+sockaddr_size)/ sizeof(uint64_t); addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST; addr->sadb_address_proto = 0; addr->sadb_address_reserved = 0; addr->sadb_address_prefixlen = pfkey_sockaddr_fill(&x->id.daddr, 0, (struct sockaddr *) (addr + 1), x->props.family); if (!addr->sadb_address_prefixlen) BUG(); pol = (struct sadb_x_policy *) skb_put(skb, sizeof(struct sadb_x_policy)); pol->sadb_x_policy_len = sizeof(struct sadb_x_policy)/sizeof(uint64_t); pol->sadb_x_policy_exttype = SADB_X_EXT_POLICY; pol->sadb_x_policy_type = IPSEC_POLICY_IPSEC; pol->sadb_x_policy_dir = XFRM_POLICY_OUT + 1; pol->sadb_x_policy_id = xp->index; /* Set sadb_comb's. */ if (x->id.proto == IPPROTO_AH) dump_ah_combs(skb, t); else if (x->id.proto == IPPROTO_ESP) dump_esp_combs(skb, t); /* security context */ if (xfrm_ctx) { sec_ctx = (struct sadb_x_sec_ctx *) skb_put(skb, sizeof(struct sadb_x_sec_ctx) + ctx_size); sec_ctx->sadb_x_sec_len = (sizeof(struct sadb_x_sec_ctx) + ctx_size) / sizeof(uint64_t); sec_ctx->sadb_x_sec_exttype = SADB_X_EXT_SEC_CTX; sec_ctx->sadb_x_ctx_doi = xfrm_ctx->ctx_doi; sec_ctx->sadb_x_ctx_alg = xfrm_ctx->ctx_alg; sec_ctx->sadb_x_ctx_len = xfrm_ctx->ctx_len; memcpy(sec_ctx + 1, xfrm_ctx->ctx_str, xfrm_ctx->ctx_len); } return pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_REGISTERED, NULL, xs_net(x)); } static struct xfrm_policy *pfkey_compile_policy(struct sock *sk, int opt, u8 *data, int len, int *dir) { struct net *net = sock_net(sk); struct xfrm_policy *xp; struct sadb_x_policy *pol = (struct sadb_x_policy*)data; struct sadb_x_sec_ctx *sec_ctx; switch (sk->sk_family) { case AF_INET: if (opt != IP_IPSEC_POLICY) { *dir = -EOPNOTSUPP; return NULL; } break; #if IS_ENABLED(CONFIG_IPV6) case AF_INET6: if (opt != IPV6_IPSEC_POLICY) { *dir = -EOPNOTSUPP; return NULL; } break; #endif default: *dir = -EINVAL; return NULL; } *dir = -EINVAL; if (len < sizeof(struct sadb_x_policy) || pol->sadb_x_policy_len*8 > len || pol->sadb_x_policy_type > IPSEC_POLICY_BYPASS || (!pol->sadb_x_policy_dir || pol->sadb_x_policy_dir > IPSEC_DIR_OUTBOUND)) return NULL; xp = xfrm_policy_alloc(net, GFP_ATOMIC); if (xp == NULL) { *dir = -ENOBUFS; return NULL; } xp->action = (pol->sadb_x_policy_type == IPSEC_POLICY_DISCARD ? XFRM_POLICY_BLOCK : XFRM_POLICY_ALLOW); xp->lft.soft_byte_limit = XFRM_INF; xp->lft.hard_byte_limit = XFRM_INF; xp->lft.soft_packet_limit = XFRM_INF; xp->lft.hard_packet_limit = XFRM_INF; xp->family = sk->sk_family; xp->xfrm_nr = 0; if (pol->sadb_x_policy_type == IPSEC_POLICY_IPSEC && (*dir = parse_ipsecrequests(xp, pol)) < 0) goto out; /* security context too */ if (len >= (pol->sadb_x_policy_len*8 + sizeof(struct sadb_x_sec_ctx))) { char *p = (char *)pol; struct xfrm_user_sec_ctx *uctx; p += pol->sadb_x_policy_len*8; sec_ctx = (struct sadb_x_sec_ctx *)p; if (len < pol->sadb_x_policy_len*8 + sec_ctx->sadb_x_sec_len) { *dir = -EINVAL; goto out; } if ((*dir = verify_sec_ctx_len(p))) goto out; uctx = pfkey_sadb2xfrm_user_sec_ctx(sec_ctx); *dir = security_xfrm_policy_alloc(&xp->security, uctx); kfree(uctx); if (*dir) goto out; } *dir = pol->sadb_x_policy_dir-1; return xp; out: xp->walk.dead = 1; xfrm_policy_destroy(xp); return NULL; } static int pfkey_send_new_mapping(struct xfrm_state *x, xfrm_address_t *ipaddr, __be16 sport) { struct sk_buff *skb; struct sadb_msg *hdr; struct sadb_sa *sa; struct sadb_address *addr; struct sadb_x_nat_t_port *n_port; int sockaddr_size; int size; __u8 satype = (x->id.proto == IPPROTO_ESP ? SADB_SATYPE_ESP : 0); struct xfrm_encap_tmpl *natt = NULL; sockaddr_size = pfkey_sockaddr_size(x->props.family); if (!sockaddr_size) return -EINVAL; if (!satype) return -EINVAL; if (!x->encap) return -EINVAL; natt = x->encap; /* Build an SADB_X_NAT_T_NEW_MAPPING message: * * HDR | SA | ADDRESS_SRC (old addr) | NAT_T_SPORT (old port) | * ADDRESS_DST (new addr) | NAT_T_DPORT (new port) */ size = sizeof(struct sadb_msg) + sizeof(struct sadb_sa) + (sizeof(struct sadb_address) * 2) + (sockaddr_size * 2) + (sizeof(struct sadb_x_nat_t_port) * 2); skb = alloc_skb(size + 16, GFP_ATOMIC); if (skb == NULL) return -ENOMEM; hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg)); hdr->sadb_msg_version = PF_KEY_V2; hdr->sadb_msg_type = SADB_X_NAT_T_NEW_MAPPING; hdr->sadb_msg_satype = satype; hdr->sadb_msg_len = size / sizeof(uint64_t); hdr->sadb_msg_errno = 0; hdr->sadb_msg_reserved = 0; hdr->sadb_msg_seq = x->km.seq = get_acqseq(); hdr->sadb_msg_pid = 0; /* SA */ sa = (struct sadb_sa *) skb_put(skb, sizeof(struct sadb_sa)); sa->sadb_sa_len = sizeof(struct sadb_sa)/sizeof(uint64_t); sa->sadb_sa_exttype = SADB_EXT_SA; sa->sadb_sa_spi = x->id.spi; sa->sadb_sa_replay = 0; sa->sadb_sa_state = 0; sa->sadb_sa_auth = 0; sa->sadb_sa_encrypt = 0; sa->sadb_sa_flags = 0; /* ADDRESS_SRC (old addr) */ addr = (struct sadb_address*) skb_put(skb, sizeof(struct sadb_address)+sockaddr_size); addr->sadb_address_len = (sizeof(struct sadb_address)+sockaddr_size)/ sizeof(uint64_t); addr->sadb_address_exttype = SADB_EXT_ADDRESS_SRC; addr->sadb_address_proto = 0; addr->sadb_address_reserved = 0; addr->sadb_address_prefixlen = pfkey_sockaddr_fill(&x->props.saddr, 0, (struct sockaddr *) (addr + 1), x->props.family); if (!addr->sadb_address_prefixlen) BUG(); /* NAT_T_SPORT (old port) */ n_port = (struct sadb_x_nat_t_port*) skb_put(skb, sizeof (*n_port)); n_port->sadb_x_nat_t_port_len = sizeof(*n_port)/sizeof(uint64_t); n_port->sadb_x_nat_t_port_exttype = SADB_X_EXT_NAT_T_SPORT; n_port->sadb_x_nat_t_port_port = natt->encap_sport; n_port->sadb_x_nat_t_port_reserved = 0; /* ADDRESS_DST (new addr) */ addr = (struct sadb_address*) skb_put(skb, sizeof(struct sadb_address)+sockaddr_size); addr->sadb_address_len = (sizeof(struct sadb_address)+sockaddr_size)/ sizeof(uint64_t); addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST; addr->sadb_address_proto = 0; addr->sadb_address_reserved = 0; addr->sadb_address_prefixlen = pfkey_sockaddr_fill(ipaddr, 0, (struct sockaddr *) (addr + 1), x->props.family); if (!addr->sadb_address_prefixlen) BUG(); /* NAT_T_DPORT (new port) */ n_port = (struct sadb_x_nat_t_port*) skb_put(skb, sizeof (*n_port)); n_port->sadb_x_nat_t_port_len = sizeof(*n_port)/sizeof(uint64_t); n_port->sadb_x_nat_t_port_exttype = SADB_X_EXT_NAT_T_DPORT; n_port->sadb_x_nat_t_port_port = sport; n_port->sadb_x_nat_t_port_reserved = 0; return pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_REGISTERED, NULL, xs_net(x)); } #ifdef CONFIG_NET_KEY_MIGRATE static int set_sadb_address(struct sk_buff *skb, int sasize, int type, const struct xfrm_selector *sel) { struct sadb_address *addr; addr = (struct sadb_address *)skb_put(skb, sizeof(struct sadb_address) + sasize); addr->sadb_address_len = (sizeof(struct sadb_address) + sasize)/8; addr->sadb_address_exttype = type; addr->sadb_address_proto = sel->proto; addr->sadb_address_reserved = 0; switch (type) { case SADB_EXT_ADDRESS_SRC: addr->sadb_address_prefixlen = sel->prefixlen_s; pfkey_sockaddr_fill(&sel->saddr, 0, (struct sockaddr *)(addr + 1), sel->family); break; case SADB_EXT_ADDRESS_DST: addr->sadb_address_prefixlen = sel->prefixlen_d; pfkey_sockaddr_fill(&sel->daddr, 0, (struct sockaddr *)(addr + 1), sel->family); break; default: return -EINVAL; } return 0; } static int set_sadb_kmaddress(struct sk_buff *skb, const struct xfrm_kmaddress *k) { struct sadb_x_kmaddress *kma; u8 *sa; int family = k->family; int socklen = pfkey_sockaddr_len(family); int size_req; size_req = (sizeof(struct sadb_x_kmaddress) + pfkey_sockaddr_pair_size(family)); kma = (struct sadb_x_kmaddress *)skb_put(skb, size_req); memset(kma, 0, size_req); kma->sadb_x_kmaddress_len = size_req / 8; kma->sadb_x_kmaddress_exttype = SADB_X_EXT_KMADDRESS; kma->sadb_x_kmaddress_reserved = k->reserved; sa = (u8 *)(kma + 1); if (!pfkey_sockaddr_fill(&k->local, 0, (struct sockaddr *)sa, family) || !pfkey_sockaddr_fill(&k->remote, 0, (struct sockaddr *)(sa+socklen), family)) return -EINVAL; return 0; } static int set_ipsecrequest(struct sk_buff *skb, uint8_t proto, uint8_t mode, int level, uint32_t reqid, uint8_t family, const xfrm_address_t *src, const xfrm_address_t *dst) { struct sadb_x_ipsecrequest *rq; u8 *sa; int socklen = pfkey_sockaddr_len(family); int size_req; size_req = sizeof(struct sadb_x_ipsecrequest) + pfkey_sockaddr_pair_size(family); rq = (struct sadb_x_ipsecrequest *)skb_put(skb, size_req); memset(rq, 0, size_req); rq->sadb_x_ipsecrequest_len = size_req; rq->sadb_x_ipsecrequest_proto = proto; rq->sadb_x_ipsecrequest_mode = mode; rq->sadb_x_ipsecrequest_level = level; rq->sadb_x_ipsecrequest_reqid = reqid; sa = (u8 *) (rq + 1); if (!pfkey_sockaddr_fill(src, 0, (struct sockaddr *)sa, family) || !pfkey_sockaddr_fill(dst, 0, (struct sockaddr *)(sa + socklen), family)) return -EINVAL; return 0; } #endif #ifdef CONFIG_NET_KEY_MIGRATE static int pfkey_send_migrate(const struct xfrm_selector *sel, u8 dir, u8 type, const struct xfrm_migrate *m, int num_bundles, const struct xfrm_kmaddress *k) { int i; int sasize_sel; int size = 0; int size_pol = 0; struct sk_buff *skb; struct sadb_msg *hdr; struct sadb_x_policy *pol; const struct xfrm_migrate *mp; if (type != XFRM_POLICY_TYPE_MAIN) return 0; if (num_bundles <= 0 || num_bundles > XFRM_MAX_DEPTH) return -EINVAL; if (k != NULL) { /* addresses for KM */ size += PFKEY_ALIGN8(sizeof(struct sadb_x_kmaddress) + pfkey_sockaddr_pair_size(k->family)); } /* selector */ sasize_sel = pfkey_sockaddr_size(sel->family); if (!sasize_sel) return -EINVAL; size += (sizeof(struct sadb_address) + sasize_sel) * 2; /* policy info */ size_pol += sizeof(struct sadb_x_policy); /* ipsecrequests */ for (i = 0, mp = m; i < num_bundles; i++, mp++) { /* old locator pair */ size_pol += sizeof(struct sadb_x_ipsecrequest) + pfkey_sockaddr_pair_size(mp->old_family); /* new locator pair */ size_pol += sizeof(struct sadb_x_ipsecrequest) + pfkey_sockaddr_pair_size(mp->new_family); } size += sizeof(struct sadb_msg) + size_pol; /* alloc buffer */ skb = alloc_skb(size, GFP_ATOMIC); if (skb == NULL) return -ENOMEM; hdr = (struct sadb_msg *)skb_put(skb, sizeof(struct sadb_msg)); hdr->sadb_msg_version = PF_KEY_V2; hdr->sadb_msg_type = SADB_X_MIGRATE; hdr->sadb_msg_satype = pfkey_proto2satype(m->proto); hdr->sadb_msg_len = size / 8; hdr->sadb_msg_errno = 0; hdr->sadb_msg_reserved = 0; hdr->sadb_msg_seq = 0; hdr->sadb_msg_pid = 0; /* Addresses to be used by KM for negotiation, if ext is available */ if (k != NULL && (set_sadb_kmaddress(skb, k) < 0)) goto err; /* selector src */ set_sadb_address(skb, sasize_sel, SADB_EXT_ADDRESS_SRC, sel); /* selector dst */ set_sadb_address(skb, sasize_sel, SADB_EXT_ADDRESS_DST, sel); /* policy information */ pol = (struct sadb_x_policy *)skb_put(skb, sizeof(struct sadb_x_policy)); pol->sadb_x_policy_len = size_pol / 8; pol->sadb_x_policy_exttype = SADB_X_EXT_POLICY; pol->sadb_x_policy_type = IPSEC_POLICY_IPSEC; pol->sadb_x_policy_dir = dir + 1; pol->sadb_x_policy_id = 0; pol->sadb_x_policy_priority = 0; for (i = 0, mp = m; i < num_bundles; i++, mp++) { /* old ipsecrequest */ int mode = pfkey_mode_from_xfrm(mp->mode); if (mode < 0) goto err; if (set_ipsecrequest(skb, mp->proto, mode, (mp->reqid ? IPSEC_LEVEL_UNIQUE : IPSEC_LEVEL_REQUIRE), mp->reqid, mp->old_family, &mp->old_saddr, &mp->old_daddr) < 0) goto err; /* new ipsecrequest */ if (set_ipsecrequest(skb, mp->proto, mode, (mp->reqid ? IPSEC_LEVEL_UNIQUE : IPSEC_LEVEL_REQUIRE), mp->reqid, mp->new_family, &mp->new_saddr, &mp->new_daddr) < 0) goto err; } /* broadcast migrate message to sockets */ pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_ALL, NULL, &init_net); return 0; err: kfree_skb(skb); return -EINVAL; } #else static int pfkey_send_migrate(const struct xfrm_selector *sel, u8 dir, u8 type, const struct xfrm_migrate *m, int num_bundles, const struct xfrm_kmaddress *k) { return -ENOPROTOOPT; } #endif static int pfkey_sendmsg(struct kiocb *kiocb, struct socket *sock, struct msghdr *msg, size_t len) { struct sock *sk = sock->sk; struct sk_buff *skb = NULL; struct sadb_msg *hdr = NULL; int err; err = -EOPNOTSUPP; if (msg->msg_flags & MSG_OOB) goto out; err = -EMSGSIZE; if ((unsigned int)len > sk->sk_sndbuf - 32) goto out; err = -ENOBUFS; skb = alloc_skb(len, GFP_KERNEL); if (skb == NULL) goto out; err = -EFAULT; if (memcpy_fromiovec(skb_put(skb,len), msg->msg_iov, len)) goto out; hdr = pfkey_get_base_msg(skb, &err); if (!hdr) goto out; mutex_lock(&xfrm_cfg_mutex); err = pfkey_process(sk, skb, hdr); mutex_unlock(&xfrm_cfg_mutex); out: if (err && hdr && pfkey_error(hdr, err, sk) == 0) err = 0; kfree_skb(skb); return err ? : len; } static int pfkey_recvmsg(struct kiocb *kiocb, struct socket *sock, struct msghdr *msg, size_t len, int flags) { struct sock *sk = sock->sk; struct pfkey_sock *pfk = pfkey_sk(sk); struct sk_buff *skb; int copied, err; err = -EINVAL; if (flags & ~(MSG_PEEK|MSG_DONTWAIT|MSG_TRUNC|MSG_CMSG_COMPAT)) goto out; msg->msg_namelen = 0; skb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &err); if (skb == NULL) goto out; copied = skb->len; if (copied > len) { msg->msg_flags |= MSG_TRUNC; copied = len; } skb_reset_transport_header(skb); err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (err) goto out_free; sock_recv_ts_and_drops(msg, sk, skb); err = (flags & MSG_TRUNC) ? skb->len : copied; if (pfk->dump.dump != NULL && 3 * atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf) pfkey_do_dump(pfk); out_free: skb_free_datagram(sk, skb); out: return err; } static const struct proto_ops pfkey_ops = { .family = PF_KEY, .owner = THIS_MODULE, /* Operations that make no sense on pfkey sockets. */ .bind = sock_no_bind, .connect = sock_no_connect, .socketpair = sock_no_socketpair, .accept = sock_no_accept, .getname = sock_no_getname, .ioctl = sock_no_ioctl, .listen = sock_no_listen, .shutdown = sock_no_shutdown, .setsockopt = sock_no_setsockopt, .getsockopt = sock_no_getsockopt, .mmap = sock_no_mmap, .sendpage = sock_no_sendpage, /* Now the operations that really occur. */ .release = pfkey_release, .poll = datagram_poll, .sendmsg = pfkey_sendmsg, .recvmsg = pfkey_recvmsg, }; static const struct net_proto_family pfkey_family_ops = { .family = PF_KEY, .create = pfkey_create, .owner = THIS_MODULE, }; #ifdef CONFIG_PROC_FS static int pfkey_seq_show(struct seq_file *f, void *v) { struct sock *s = sk_entry(v); if (v == SEQ_START_TOKEN) seq_printf(f ,"sk RefCnt Rmem Wmem User Inode\n"); else seq_printf(f, "%pK %-6d %-6u %-6u %-6u %-6lu\n", s, atomic_read(&s->sk_refcnt), sk_rmem_alloc_get(s), sk_wmem_alloc_get(s), from_kuid_munged(seq_user_ns(f), sock_i_uid(s)), sock_i_ino(s) ); return 0; } static void *pfkey_seq_start(struct seq_file *f, loff_t *ppos) __acquires(rcu) { struct net *net = seq_file_net(f); struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id); rcu_read_lock(); return seq_hlist_start_head_rcu(&net_pfkey->table, *ppos); } static void *pfkey_seq_next(struct seq_file *f, void *v, loff_t *ppos) { struct net *net = seq_file_net(f); struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id); return seq_hlist_next_rcu(v, &net_pfkey->table, ppos); } static void pfkey_seq_stop(struct seq_file *f, void *v) __releases(rcu) { rcu_read_unlock(); } static const struct seq_operations pfkey_seq_ops = { .start = pfkey_seq_start, .next = pfkey_seq_next, .stop = pfkey_seq_stop, .show = pfkey_seq_show, }; static int pfkey_seq_open(struct inode *inode, struct file *file) { return seq_open_net(inode, file, &pfkey_seq_ops, sizeof(struct seq_net_private)); } static const struct file_operations pfkey_proc_ops = { .open = pfkey_seq_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release_net, }; static int __net_init pfkey_init_proc(struct net *net) { struct proc_dir_entry *e; e = proc_create("pfkey", 0, net->proc_net, &pfkey_proc_ops); if (e == NULL) return -ENOMEM; return 0; } static void __net_exit pfkey_exit_proc(struct net *net) { remove_proc_entry("pfkey", net->proc_net); } #else static inline int pfkey_init_proc(struct net *net) { return 0; } static inline void pfkey_exit_proc(struct net *net) { } #endif static struct xfrm_mgr pfkeyv2_mgr = { .id = "pfkeyv2", .notify = pfkey_send_notify, .acquire = pfkey_send_acquire, .compile_policy = pfkey_compile_policy, .new_mapping = pfkey_send_new_mapping, .notify_policy = pfkey_send_policy_notify, .migrate = pfkey_send_migrate, }; static int __net_init pfkey_net_init(struct net *net) { struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id); int rv; INIT_HLIST_HEAD(&net_pfkey->table); atomic_set(&net_pfkey->socks_nr, 0); rv = pfkey_init_proc(net); return rv; } static void __net_exit pfkey_net_exit(struct net *net) { struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id); pfkey_exit_proc(net); BUG_ON(!hlist_empty(&net_pfkey->table)); } static struct pernet_operations pfkey_net_ops = { .init = pfkey_net_init, .exit = pfkey_net_exit, .id = &pfkey_net_id, .size = sizeof(struct netns_pfkey), }; static void __exit ipsec_pfkey_exit(void) { xfrm_unregister_km(&pfkeyv2_mgr); sock_unregister(PF_KEY); unregister_pernet_subsys(&pfkey_net_ops); proto_unregister(&key_proto); } static int __init ipsec_pfkey_init(void) { int err = proto_register(&key_proto, 0); if (err != 0) goto out; err = register_pernet_subsys(&pfkey_net_ops); if (err != 0) goto out_unregister_key_proto; err = sock_register(&pfkey_family_ops); if (err != 0) goto out_unregister_pernet; err = xfrm_register_km(&pfkeyv2_mgr); if (err != 0) goto out_sock_unregister; out: return err; out_sock_unregister: sock_unregister(PF_KEY); out_unregister_pernet: unregister_pernet_subsys(&pfkey_net_ops); out_unregister_key_proto: proto_unregister(&key_proto); goto out; } module_init(ipsec_pfkey_init); module_exit(ipsec_pfkey_exit); MODULE_LICENSE("GPL"); MODULE_ALIAS_NETPROTO(PF_KEY);
./CrossVul/dataset_final_sorted/CWE-119/c/bad_5661_0
crossvul-cpp_data_good_2899_0
/* radare - LGPL - Copyright 2008-2017 - nibble, pancake, alvaro_fe */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <r_types.h> #include <r_util.h> #include "elf.h" #ifdef IFDBG #undef IFDBG #endif #define DO_THE_DBG 0 #define IFDBG if (DO_THE_DBG) #define IFINT if (0) #define ELF_PAGE_MASK 0xFFFFFFFFFFFFF000LL #define ELF_PAGE_SIZE 12 #define R_ELF_NO_RELRO 0 #define R_ELF_PART_RELRO 1 #define R_ELF_FULL_RELRO 2 #define bprintf if(bin->verbose)eprintf #define READ8(x, i) r_read_ble8(x + i); i += 1; #define READ16(x, i) r_read_ble16(x + i, bin->endian); i += 2; #define READ32(x, i) r_read_ble32(x + i, bin->endian); i += 4; #define READ64(x, i) r_read_ble64(x + i, bin->endian); i += 8; #define GROWTH_FACTOR (1.5) static inline int __strnlen(const char *str, int len) { int l = 0; while (IS_PRINTABLE (*str) && --len) { if (((ut8)*str) == 0xff) { break; } str++; l++; } return l + 1; } static int handle_e_ident(ELFOBJ *bin) { return !strncmp ((char *)bin->ehdr.e_ident, ELFMAG, SELFMAG) || !strncmp ((char *)bin->ehdr.e_ident, CGCMAG, SCGCMAG); } static int init_ehdr(ELFOBJ *bin) { ut8 e_ident[EI_NIDENT]; ut8 ehdr[sizeof (Elf_(Ehdr))] = {0}; int i, len; if (r_buf_read_at (bin->b, 0, e_ident, EI_NIDENT) == -1) { bprintf ("Warning: read (magic)\n"); return false; } sdb_set (bin->kv, "elf_type.cparse", "enum elf_type { ET_NONE=0, ET_REL=1," " ET_EXEC=2, ET_DYN=3, ET_CORE=4, ET_LOOS=0xfe00, ET_HIOS=0xfeff," " ET_LOPROC=0xff00, ET_HIPROC=0xffff };", 0); sdb_set (bin->kv, "elf_machine.cparse", "enum elf_machine{EM_NONE=0, EM_M32=1," " EM_SPARC=2, EM_386=3, EM_68K=4, EM_88K=5, EM_486=6, " " EM_860=7, EM_MIPS=8, EM_S370=9, EM_MIPS_RS3_LE=10, EM_RS6000=11," " EM_UNKNOWN12=12, EM_UNKNOWN13=13, EM_UNKNOWN14=14, " " EM_PA_RISC=15, EM_PARISC=EM_PA_RISC, EM_nCUBE=16, EM_VPP500=17," " EM_SPARC32PLUS=18, EM_960=19, EM_PPC=20, EM_PPC64=21, " " EM_S390=22, EM_UNKNOWN22=EM_S390, EM_UNKNOWN23=23, EM_UNKNOWN24=24," " EM_UNKNOWN25=25, EM_UNKNOWN26=26, EM_UNKNOWN27=27, EM_UNKNOWN28=28," " EM_UNKNOWN29=29, EM_UNKNOWN30=30, EM_UNKNOWN31=31, EM_UNKNOWN32=32," " EM_UNKNOWN33=33, EM_UNKNOWN34=34, EM_UNKNOWN35=35, EM_V800=36," " EM_FR20=37, EM_RH32=38, EM_RCE=39, EM_ARM=40, EM_ALPHA=41, EM_SH=42," " EM_SPARCV9=43, EM_TRICORE=44, EM_ARC=45, EM_H8_300=46, EM_H8_300H=47," " EM_H8S=48, EM_H8_500=49, EM_IA_64=50, EM_MIPS_X=51, EM_COLDFIRE=52," " EM_68HC12=53, EM_MMA=54, EM_PCP=55, EM_NCPU=56, EM_NDR1=57," " EM_STARCORE=58, EM_ME16=59, EM_ST100=60, EM_TINYJ=61, EM_AMD64=62," " EM_X86_64=EM_AMD64, EM_PDSP=63, EM_UNKNOWN64=64, EM_UNKNOWN65=65," " EM_FX66=66, EM_ST9PLUS=67, EM_ST7=68, EM_68HC16=69, EM_68HC11=70," " EM_68HC08=71, EM_68HC05=72, EM_SVX=73, EM_ST19=74, EM_VAX=75, " " EM_CRIS=76, EM_JAVELIN=77, EM_FIREPATH=78, EM_ZSP=79, EM_MMIX=80," " EM_HUANY=81, EM_PRISM=82, EM_AVR=83, EM_FR30=84, EM_D10V=85, EM_D30V=86," " EM_V850=87, EM_M32R=88, EM_MN10300=89, EM_MN10200=90, EM_PJ=91," " EM_OPENRISC=92, EM_ARC_A5=93, EM_XTENSA=94, EM_NUM=95};", 0); sdb_num_set (bin->kv, "elf_header.offset", 0, 0); sdb_num_set (bin->kv, "elf_header.size", sizeof (Elf_(Ehdr)), 0); #if R_BIN_ELF64 sdb_set (bin->kv, "elf_header.format", "[16]z[2]E[2]Exqqqxwwwwww" " ident (elf_type)type (elf_machine)machine version entry phoff shoff flags ehsize" " phentsize phnum shentsize shnum shstrndx", 0); #else sdb_set (bin->kv, "elf_header.format", "[16]z[2]E[2]Exxxxxwwwwww" " ident (elf_type)type (elf_machine)machine version entry phoff shoff flags ehsize" " phentsize phnum shentsize shnum shstrndx", 0); #endif bin->endian = (e_ident[EI_DATA] == ELFDATA2MSB)? 1: 0; memset (&bin->ehdr, 0, sizeof (Elf_(Ehdr))); len = r_buf_read_at (bin->b, 0, ehdr, sizeof (Elf_(Ehdr))); if (len < 1) { bprintf ("Warning: read (ehdr)\n"); return false; } memcpy (&bin->ehdr.e_ident, ehdr, 16); i = 16; bin->ehdr.e_type = READ16 (ehdr, i) bin->ehdr.e_machine = READ16 (ehdr, i) bin->ehdr.e_version = READ32 (ehdr, i) #if R_BIN_ELF64 bin->ehdr.e_entry = READ64 (ehdr, i) bin->ehdr.e_phoff = READ64 (ehdr, i) bin->ehdr.e_shoff = READ64 (ehdr, i) #else bin->ehdr.e_entry = READ32 (ehdr, i) bin->ehdr.e_phoff = READ32 (ehdr, i) bin->ehdr.e_shoff = READ32 (ehdr, i) #endif bin->ehdr.e_flags = READ32 (ehdr, i) bin->ehdr.e_ehsize = READ16 (ehdr, i) bin->ehdr.e_phentsize = READ16 (ehdr, i) bin->ehdr.e_phnum = READ16 (ehdr, i) bin->ehdr.e_shentsize = READ16 (ehdr, i) bin->ehdr.e_shnum = READ16 (ehdr, i) bin->ehdr.e_shstrndx = READ16 (ehdr, i) return handle_e_ident (bin); // Usage example: // > td `k bin/cur/info/elf_type.cparse`; td `k bin/cur/info/elf_machine.cparse` // > pf `k bin/cur/info/elf_header.format` @ `k bin/cur/info/elf_header.offset` } static int init_phdr(ELFOBJ *bin) { ut32 phdr_size; ut8 phdr[sizeof (Elf_(Phdr))] = {0}; int i, j, len; if (!bin->ehdr.e_phnum) { return false; } if (bin->phdr) { return true; } if (!UT32_MUL (&phdr_size, (ut32)bin->ehdr.e_phnum, sizeof (Elf_(Phdr)))) { return false; } if (!phdr_size) { return false; } if (phdr_size > bin->size) { return false; } if (phdr_size > (ut32)bin->size) { return false; } if (bin->ehdr.e_phoff > bin->size) { return false; } if (bin->ehdr.e_phoff + phdr_size > bin->size) { return false; } if (!(bin->phdr = calloc (phdr_size, 1))) { perror ("malloc (phdr)"); return false; } for (i = 0; i < bin->ehdr.e_phnum; i++) { j = 0; len = r_buf_read_at (bin->b, bin->ehdr.e_phoff + i * sizeof (Elf_(Phdr)), phdr, sizeof (Elf_(Phdr))); if (len < 1) { bprintf ("Warning: read (phdr)\n"); R_FREE (bin->phdr); return false; } bin->phdr[i].p_type = READ32 (phdr, j) #if R_BIN_ELF64 bin->phdr[i].p_flags = READ32 (phdr, j) bin->phdr[i].p_offset = READ64 (phdr, j) bin->phdr[i].p_vaddr = READ64 (phdr, j) bin->phdr[i].p_paddr = READ64 (phdr, j) bin->phdr[i].p_filesz = READ64 (phdr, j) bin->phdr[i].p_memsz = READ64 (phdr, j) bin->phdr[i].p_align = READ64 (phdr, j) #else bin->phdr[i].p_offset = READ32 (phdr, j) bin->phdr[i].p_vaddr = READ32 (phdr, j) bin->phdr[i].p_paddr = READ32 (phdr, j) bin->phdr[i].p_filesz = READ32 (phdr, j) bin->phdr[i].p_memsz = READ32 (phdr, j) bin->phdr[i].p_flags = READ32 (phdr, j) bin->phdr[i].p_align = READ32 (phdr, j) #endif } sdb_num_set (bin->kv, "elf_phdr.offset", bin->ehdr.e_phoff, 0); sdb_num_set (bin->kv, "elf_phdr.size", sizeof (Elf_(Phdr)), 0); sdb_set (bin->kv, "elf_p_type.cparse", "enum elf_p_type {PT_NULL=0,PT_LOAD=1,PT_DYNAMIC=2," "PT_INTERP=3,PT_NOTE=4,PT_SHLIB=5,PT_PHDR=6,PT_LOOS=0x60000000," "PT_HIOS=0x6fffffff,PT_LOPROC=0x70000000,PT_HIPROC=0x7fffffff};", 0); sdb_set (bin->kv, "elf_p_flags.cparse", "enum elf_p_flags {PF_None=0,PF_Exec=1," "PF_Write=2,PF_Write_Exec=3,PF_Read=4,PF_Read_Exec=5,PF_Read_Write=6," "PF_Read_Write_Exec=7};", 0); #if R_BIN_ELF64 sdb_set (bin->kv, "elf_phdr.format", "[4]E[4]Eqqqqqq (elf_p_type)type (elf_p_flags)flags" " offset vaddr paddr filesz memsz align", 0); #else sdb_set (bin->kv, "elf_phdr.format", "[4]Exxxxx[4]Ex (elf_p_type)type offset vaddr paddr" " filesz memsz (elf_p_flags)flags align", 0); #endif return true; // Usage example: // > td `k bin/cur/info/elf_p_type.cparse`; td `k bin/cur/info/elf_p_flags.cparse` // > pf `k bin/cur/info/elf_phdr.format` @ `k bin/cur/info/elf_phdr.offset` } static int init_shdr(ELFOBJ *bin) { ut32 shdr_size; ut8 shdr[sizeof (Elf_(Shdr))] = {0}; int i, j, len; if (!bin || bin->shdr) { return true; } if (!UT32_MUL (&shdr_size, bin->ehdr.e_shnum, sizeof (Elf_(Shdr)))) { return false; } if (shdr_size < 1) { return false; } if (shdr_size > bin->size) { return false; } if (bin->ehdr.e_shoff > bin->size) { return false; } if (bin->ehdr.e_shoff + shdr_size > bin->size) { return false; } if (!(bin->shdr = calloc (1, shdr_size + 1))) { perror ("malloc (shdr)"); return false; } sdb_num_set (bin->kv, "elf_shdr.offset", bin->ehdr.e_shoff, 0); sdb_num_set (bin->kv, "elf_shdr.size", sizeof (Elf_(Shdr)), 0); sdb_set (bin->kv, "elf_s_type.cparse", "enum elf_s_type {SHT_NULL=0,SHT_PROGBITS=1," "SHT_SYMTAB=2,SHT_STRTAB=3,SHT_RELA=4,SHT_HASH=5,SHT_DYNAMIC=6,SHT_NOTE=7," "SHT_NOBITS=8,SHT_REL=9,SHT_SHLIB=10,SHT_DYNSYM=11,SHT_LOOS=0x60000000," "SHT_HIOS=0x6fffffff,SHT_LOPROC=0x70000000,SHT_HIPROC=0x7fffffff};", 0); for (i = 0; i < bin->ehdr.e_shnum; i++) { j = 0; len = r_buf_read_at (bin->b, bin->ehdr.e_shoff + i * sizeof (Elf_(Shdr)), shdr, sizeof (Elf_(Shdr))); if (len < 1) { bprintf ("Warning: read (shdr) at 0x%"PFMT64x"\n", (ut64) bin->ehdr.e_shoff); R_FREE (bin->shdr); return false; } bin->shdr[i].sh_name = READ32 (shdr, j) bin->shdr[i].sh_type = READ32 (shdr, j) #if R_BIN_ELF64 bin->shdr[i].sh_flags = READ64 (shdr, j) bin->shdr[i].sh_addr = READ64 (shdr, j) bin->shdr[i].sh_offset = READ64 (shdr, j) bin->shdr[i].sh_size = READ64 (shdr, j) bin->shdr[i].sh_link = READ32 (shdr, j) bin->shdr[i].sh_info = READ32 (shdr, j) bin->shdr[i].sh_addralign = READ64 (shdr, j) bin->shdr[i].sh_entsize = READ64 (shdr, j) #else bin->shdr[i].sh_flags = READ32 (shdr, j) bin->shdr[i].sh_addr = READ32 (shdr, j) bin->shdr[i].sh_offset = READ32 (shdr, j) bin->shdr[i].sh_size = READ32 (shdr, j) bin->shdr[i].sh_link = READ32 (shdr, j) bin->shdr[i].sh_info = READ32 (shdr, j) bin->shdr[i].sh_addralign = READ32 (shdr, j) bin->shdr[i].sh_entsize = READ32 (shdr, j) #endif } #if R_BIN_ELF64 sdb_set (bin->kv, "elf_s_flags_64.cparse", "enum elf_s_flags_64 {SF64_None=0,SF64_Exec=1," "SF64_Alloc=2,SF64_Alloc_Exec=3,SF64_Write=4,SF64_Write_Exec=5," "SF64_Write_Alloc=6,SF64_Write_Alloc_Exec=7};", 0); sdb_set (bin->kv, "elf_shdr.format", "x[4]E[8]Eqqqxxqq name (elf_s_type)type" " (elf_s_flags_64)flags addr offset size link info addralign entsize", 0); #else sdb_set (bin->kv, "elf_s_flags_32.cparse", "enum elf_s_flags_32 {SF32_None=0,SF32_Exec=1," "SF32_Alloc=2,SF32_Alloc_Exec=3,SF32_Write=4,SF32_Write_Exec=5," "SF32_Write_Alloc=6,SF32_Write_Alloc_Exec=7};", 0); sdb_set (bin->kv, "elf_shdr.format", "x[4]E[4]Exxxxxxx name (elf_s_type)type" " (elf_s_flags_32)flags addr offset size link info addralign entsize", 0); #endif return true; // Usage example: // > td `k bin/cur/info/elf_s_type.cparse`; td `k bin/cur/info/elf_s_flags_64.cparse` // > pf `k bin/cur/info/elf_shdr.format` @ `k bin/cur/info/elf_shdr.offset` } static int init_strtab(ELFOBJ *bin) { if (bin->strtab || !bin->shdr) { return false; } if (bin->ehdr.e_shstrndx != SHN_UNDEF && (bin->ehdr.e_shstrndx >= bin->ehdr.e_shnum || (bin->ehdr.e_shstrndx >= SHN_LORESERVE && bin->ehdr.e_shstrndx < SHN_HIRESERVE))) return false; /* sh_size must be lower than UT32_MAX and not equal to zero, to avoid bugs on malloc() */ if (bin->shdr[bin->ehdr.e_shstrndx].sh_size > UT32_MAX) { return false; } if (!bin->shdr[bin->ehdr.e_shstrndx].sh_size) { return false; } bin->shstrtab_section = bin->strtab_section = &bin->shdr[bin->ehdr.e_shstrndx]; bin->shstrtab_size = bin->strtab_section->sh_size; if (bin->shstrtab_size > bin->size) { return false; } if (!(bin->shstrtab = calloc (1, bin->shstrtab_size + 1))) { perror ("malloc"); bin->shstrtab = NULL; return false; } if (bin->shstrtab_section->sh_offset > bin->size) { R_FREE (bin->shstrtab); return false; } if (bin->shstrtab_section->sh_offset + bin->shstrtab_section->sh_size > bin->size) { R_FREE (bin->shstrtab); return false; } if (r_buf_read_at (bin->b, bin->shstrtab_section->sh_offset, (ut8*)bin->shstrtab, bin->shstrtab_section->sh_size + 1) < 1) { bprintf ("Warning: read (shstrtab) at 0x%"PFMT64x"\n", (ut64) bin->shstrtab_section->sh_offset); R_FREE (bin->shstrtab); return false; } bin->shstrtab[bin->shstrtab_section->sh_size] = '\0'; sdb_num_set (bin->kv, "elf_shstrtab.offset", bin->shstrtab_section->sh_offset, 0); sdb_num_set (bin->kv, "elf_shstrtab.size", bin->shstrtab_section->sh_size, 0); return true; } static int init_dynamic_section(struct Elf_(r_bin_elf_obj_t) *bin) { Elf_(Dyn) *dyn = NULL; Elf_(Dyn) d = {0}; Elf_(Addr) strtabaddr = 0; ut64 offset = 0; char *strtab = NULL; size_t relentry = 0, strsize = 0; int entries; int i, j, len, r; ut8 sdyn[sizeof (Elf_(Dyn))] = {0}; ut32 dyn_size = 0; if (!bin || !bin->phdr || !bin->ehdr.e_phnum) { return false; } for (i = 0; i < bin->ehdr.e_phnum ; i++) { if (bin->phdr[i].p_type == PT_DYNAMIC) { dyn_size = bin->phdr[i].p_filesz; break; } } if (i == bin->ehdr.e_phnum) { return false; } if (bin->phdr[i].p_filesz > bin->size) { return false; } if (bin->phdr[i].p_offset > bin->size) { return false; } if (bin->phdr[i].p_offset + sizeof(Elf_(Dyn)) > bin->size) { return false; } for (entries = 0; entries < (dyn_size / sizeof (Elf_(Dyn))); entries++) { j = 0; len = r_buf_read_at (bin->b, bin->phdr[i].p_offset + entries * sizeof (Elf_(Dyn)), sdyn, sizeof (Elf_(Dyn))); if (len < 1) { goto beach; } #if R_BIN_ELF64 d.d_tag = READ64 (sdyn, j) #else d.d_tag = READ32 (sdyn, j) #endif if (d.d_tag == DT_NULL) { break; } } if (entries < 1) { return false; } dyn = (Elf_(Dyn)*)calloc (entries, sizeof (Elf_(Dyn))); if (!dyn) { return false; } if (!UT32_MUL (&dyn_size, entries, sizeof (Elf_(Dyn)))) { goto beach; } if (!dyn_size) { goto beach; } offset = Elf_(r_bin_elf_v2p) (bin, bin->phdr[i].p_vaddr); if (offset > bin->size || offset + dyn_size > bin->size) { goto beach; } for (i = 0; i < entries; i++) { j = 0; r_buf_read_at (bin->b, offset + i * sizeof (Elf_(Dyn)), sdyn, sizeof (Elf_(Dyn))); if (len < 1) { bprintf("Warning: read (dyn)\n"); } #if R_BIN_ELF64 dyn[i].d_tag = READ64 (sdyn, j) dyn[i].d_un.d_ptr = READ64 (sdyn, j) #else dyn[i].d_tag = READ32 (sdyn, j) dyn[i].d_un.d_ptr = READ32 (sdyn, j) #endif switch (dyn[i].d_tag) { case DT_STRTAB: strtabaddr = Elf_(r_bin_elf_v2p) (bin, dyn[i].d_un.d_ptr); break; case DT_STRSZ: strsize = dyn[i].d_un.d_val; break; case DT_PLTREL: bin->is_rela = dyn[i].d_un.d_val; break; case DT_RELAENT: relentry = dyn[i].d_un.d_val; break; default: if ((dyn[i].d_tag >= DT_VERSYM) && (dyn[i].d_tag <= DT_VERNEEDNUM)) { bin->version_info[DT_VERSIONTAGIDX (dyn[i].d_tag)] = dyn[i].d_un.d_val; } break; } } if (!bin->is_rela) { bin->is_rela = sizeof (Elf_(Rela)) == relentry? DT_RELA : DT_REL; } if (!strtabaddr || strtabaddr > bin->size || strsize > ST32_MAX || !strsize || strsize > bin->size) { if (!strtabaddr) { bprintf ("Warning: section.shstrtab not found or invalid\n"); } goto beach; } strtab = (char *)calloc (1, strsize + 1); if (!strtab) { goto beach; } if (strtabaddr + strsize > bin->size) { free (strtab); goto beach; } r = r_buf_read_at (bin->b, strtabaddr, (ut8 *)strtab, strsize); if (r < 1) { free (strtab); goto beach; } bin->dyn_buf = dyn; bin->dyn_entries = entries; bin->strtab = strtab; bin->strtab_size = strsize; r = Elf_(r_bin_elf_has_relro)(bin); switch (r) { case R_ELF_FULL_RELRO: sdb_set (bin->kv, "elf.relro", "full", 0); break; case R_ELF_PART_RELRO: sdb_set (bin->kv, "elf.relro", "partial", 0); break; default: sdb_set (bin->kv, "elf.relro", "no", 0); break; } sdb_num_set (bin->kv, "elf_strtab.offset", strtabaddr, 0); sdb_num_set (bin->kv, "elf_strtab.size", strsize, 0); return true; beach: free (dyn); return false; } static RBinElfSection* get_section_by_name(ELFOBJ *bin, const char *section_name) { int i; if (!bin->g_sections) { return NULL; } for (i = 0; !bin->g_sections[i].last; i++) { if (!strncmp (bin->g_sections[i].name, section_name, ELF_STRING_LENGTH-1)) { return &bin->g_sections[i]; } } return NULL; } static char *get_ver_flags(ut32 flags) { static char buff[32]; buff[0] = 0; if (!flags) { return "none"; } if (flags & VER_FLG_BASE) { strcpy (buff, "BASE "); } if (flags & VER_FLG_WEAK) { if (flags & VER_FLG_BASE) { strcat (buff, "| "); } strcat (buff, "WEAK "); } if (flags & ~(VER_FLG_BASE | VER_FLG_WEAK)) { strcat (buff, "| <unknown>"); } return buff; } static Sdb *store_versioninfo_gnu_versym(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) { int i; const ut64 num_entries = sz / sizeof (Elf_(Versym)); const char *section_name = ""; const char *link_section_name = ""; Elf_(Shdr) *link_shdr = NULL; Sdb *sdb = sdb_new0(); if (!sdb) { return NULL; } if (!bin->version_info[DT_VERSIONTAGIDX (DT_VERSYM)]) { sdb_free (sdb); return NULL; } if (shdr->sh_link > bin->ehdr.e_shnum) { sdb_free (sdb); return NULL; } link_shdr = &bin->shdr[shdr->sh_link]; ut8 *edata = (ut8*) calloc (R_MAX (1, num_entries), sizeof (ut16)); if (!edata) { sdb_free (sdb); return NULL; } ut16 *data = (ut16*) calloc (R_MAX (1, num_entries), sizeof (ut16)); if (!data) { free (edata); sdb_free (sdb); return NULL; } ut64 off = Elf_(r_bin_elf_v2p) (bin, bin->version_info[DT_VERSIONTAGIDX (DT_VERSYM)]); if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) { section_name = &bin->shstrtab[shdr->sh_name]; } if (bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) { link_section_name = &bin->shstrtab[link_shdr->sh_name]; } r_buf_read_at (bin->b, off, edata, sizeof (ut16) * num_entries); sdb_set (sdb, "section_name", section_name, 0); sdb_num_set (sdb, "num_entries", num_entries, 0); sdb_num_set (sdb, "addr", shdr->sh_addr, 0); sdb_num_set (sdb, "offset", shdr->sh_offset, 0); sdb_num_set (sdb, "link", shdr->sh_link, 0); sdb_set (sdb, "link_section_name", link_section_name, 0); for (i = num_entries; i--;) { data[i] = r_read_ble16 (&edata[i * sizeof (ut16)], bin->endian); } R_FREE (edata); for (i = 0; i < num_entries; i += 4) { int j; int check_def; char key[32] = {0}; Sdb *sdb_entry = sdb_new0 (); snprintf (key, sizeof (key), "entry%d", i / 4); sdb_ns_set (sdb, key, sdb_entry); sdb_num_set (sdb_entry, "idx", i, 0); for (j = 0; (j < 4) && (i + j) < num_entries; ++j) { int k; char *tmp_val = NULL; snprintf (key, sizeof (key), "value%d", j); switch (data[i + j]) { case 0: sdb_set (sdb_entry, key, "0 (*local*)", 0); break; case 1: sdb_set (sdb_entry, key, "1 (*global*)", 0); break; default: tmp_val = sdb_fmt (0, "%x ", data[i+j] & 0x7FFF); check_def = true; if (bin->version_info[DT_VERSIONTAGIDX (DT_VERNEED)]) { Elf_(Verneed) vn; ut8 svn[sizeof (Elf_(Verneed))] = {0}; ut64 offset = Elf_(r_bin_elf_v2p) (bin, bin->version_info[DT_VERSIONTAGIDX (DT_VERNEED)]); do { Elf_(Vernaux) vna; ut8 svna[sizeof (Elf_(Vernaux))] = {0}; ut64 a_off; if (offset > bin->size || offset + sizeof (vn) > bin->size) { goto beach; } if (r_buf_read_at (bin->b, offset, svn, sizeof (svn)) < 0) { bprintf ("Warning: Cannot read Verneed for Versym\n"); goto beach; } k = 0; vn.vn_version = READ16 (svn, k) vn.vn_cnt = READ16 (svn, k) vn.vn_file = READ32 (svn, k) vn.vn_aux = READ32 (svn, k) vn.vn_next = READ32 (svn, k) a_off = offset + vn.vn_aux; do { if (a_off > bin->size || a_off + sizeof (vna) > bin->size) { goto beach; } if (r_buf_read_at (bin->b, a_off, svna, sizeof (svna)) < 0) { bprintf ("Warning: Cannot read Vernaux for Versym\n"); goto beach; } k = 0; vna.vna_hash = READ32 (svna, k) vna.vna_flags = READ16 (svna, k) vna.vna_other = READ16 (svna, k) vna.vna_name = READ32 (svna, k) vna.vna_next = READ32 (svna, k) a_off += vna.vna_next; } while (vna.vna_other != data[i + j] && vna.vna_next != 0); if (vna.vna_other == data[i + j]) { if (vna.vna_name > bin->strtab_size) { goto beach; } sdb_set (sdb_entry, key, sdb_fmt (0, "%s(%s)", tmp_val, bin->strtab + vna.vna_name), 0); check_def = false; break; } offset += vn.vn_next; } while (vn.vn_next); } ut64 vinfoaddr = bin->version_info[DT_VERSIONTAGIDX (DT_VERDEF)]; if (check_def && data[i + j] != 0x8001 && vinfoaddr) { Elf_(Verdef) vd; ut8 svd[sizeof (Elf_(Verdef))] = {0}; ut64 offset = Elf_(r_bin_elf_v2p) (bin, vinfoaddr); if (offset > bin->size || offset + sizeof (vd) > bin->size) { goto beach; } do { if (r_buf_read_at (bin->b, offset, svd, sizeof (svd)) < 0) { bprintf ("Warning: Cannot read Verdef for Versym\n"); goto beach; } k = 0; vd.vd_version = READ16 (svd, k) vd.vd_flags = READ16 (svd, k) vd.vd_ndx = READ16 (svd, k) vd.vd_cnt = READ16 (svd, k) vd.vd_hash = READ32 (svd, k) vd.vd_aux = READ32 (svd, k) vd.vd_next = READ32 (svd, k) offset += vd.vd_next; } while (vd.vd_ndx != (data[i + j] & 0x7FFF) && vd.vd_next != 0); if (vd.vd_ndx == (data[i + j] & 0x7FFF)) { Elf_(Verdaux) vda; ut8 svda[sizeof (Elf_(Verdaux))] = {0}; ut64 off_vda = offset - vd.vd_next + vd.vd_aux; if (off_vda > bin->size || off_vda + sizeof (vda) > bin->size) { goto beach; } if (r_buf_read_at (bin->b, off_vda, svda, sizeof (svda)) < 0) { bprintf ("Warning: Cannot read Verdaux for Versym\n"); goto beach; } k = 0; vda.vda_name = READ32 (svda, k) vda.vda_next = READ32 (svda, k) if (vda.vda_name > bin->strtab_size) { goto beach; } const char *name = bin->strtab + vda.vda_name; sdb_set (sdb_entry, key, sdb_fmt (0,"%s(%s%-*s)", tmp_val, name, (int)(12 - strlen (name)),")") , 0); } } } } } beach: free (data); return sdb; } static Sdb *store_versioninfo_gnu_verdef(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) { const char *section_name = ""; const char *link_section_name = ""; char *end = NULL; Elf_(Shdr) *link_shdr = NULL; ut8 dfs[sizeof (Elf_(Verdef))] = {0}; Sdb *sdb; int cnt, i; if (shdr->sh_link > bin->ehdr.e_shnum) { return false; } link_shdr = &bin->shdr[shdr->sh_link]; if (shdr->sh_size < 1 || shdr->sh_size > SIZE_MAX) { return false; } Elf_(Verdef) *defs = calloc (shdr->sh_size, sizeof (char)); if (!defs) { return false; } if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) { section_name = &bin->shstrtab[shdr->sh_name]; } if (link_shdr && bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) { link_section_name = &bin->shstrtab[link_shdr->sh_name]; } if (!defs) { bprintf ("Warning: Cannot allocate memory (Check Elf_(Verdef))\n"); return NULL; } sdb = sdb_new0 (); end = (char *)defs + shdr->sh_size; sdb_set (sdb, "section_name", section_name, 0); sdb_num_set (sdb, "entries", shdr->sh_info, 0); sdb_num_set (sdb, "addr", shdr->sh_addr, 0); sdb_num_set (sdb, "offset", shdr->sh_offset, 0); sdb_num_set (sdb, "link", shdr->sh_link, 0); sdb_set (sdb, "link_section_name", link_section_name, 0); for (cnt = 0, i = 0; i >= 0 && cnt < shdr->sh_info && ((char *)defs + i < end); ++cnt) { Sdb *sdb_verdef = sdb_new0 (); char *vstart = ((char*)defs) + i; char key[32] = {0}; Elf_(Verdef) *verdef = (Elf_(Verdef)*)vstart; Elf_(Verdaux) aux = {0}; int j = 0; int isum = 0; r_buf_read_at (bin->b, shdr->sh_offset + i, dfs, sizeof (Elf_(Verdef))); verdef->vd_version = READ16 (dfs, j) verdef->vd_flags = READ16 (dfs, j) verdef->vd_ndx = READ16 (dfs, j) verdef->vd_cnt = READ16 (dfs, j) verdef->vd_hash = READ32 (dfs, j) verdef->vd_aux = READ32 (dfs, j) verdef->vd_next = READ32 (dfs, j) int vdaux = verdef->vd_aux; if (vdaux < 1) { sdb_free (sdb_verdef); goto out_error; } vstart += vdaux; if (vstart > end || vstart + sizeof (Elf_(Verdaux)) > end) { sdb_free (sdb_verdef); goto out_error; } j = 0; aux.vda_name = READ32 (vstart, j) aux.vda_next = READ32 (vstart, j) isum = i + verdef->vd_aux; if (aux.vda_name > bin->dynstr_size) { sdb_free (sdb_verdef); goto out_error; } sdb_num_set (sdb_verdef, "idx", i, 0); sdb_num_set (sdb_verdef, "vd_version", verdef->vd_version, 0); sdb_num_set (sdb_verdef, "vd_ndx", verdef->vd_ndx, 0); sdb_num_set (sdb_verdef, "vd_cnt", verdef->vd_cnt, 0); sdb_set (sdb_verdef, "vda_name", &bin->dynstr[aux.vda_name], 0); sdb_set (sdb_verdef, "flags", get_ver_flags (verdef->vd_flags), 0); for (j = 1; j < verdef->vd_cnt; ++j) { int k; Sdb *sdb_parent = sdb_new0 (); isum += aux.vda_next; vstart += aux.vda_next; if (vstart > end || vstart + sizeof(Elf_(Verdaux)) > end) { sdb_free (sdb_verdef); sdb_free (sdb_parent); goto out_error; } k = 0; aux.vda_name = READ32 (vstart, k) aux.vda_next = READ32 (vstart, k) if (aux.vda_name > bin->dynstr_size) { sdb_free (sdb_verdef); sdb_free (sdb_parent); goto out_error; } sdb_num_set (sdb_parent, "idx", isum, 0); sdb_num_set (sdb_parent, "parent", j, 0); sdb_set (sdb_parent, "vda_name", &bin->dynstr[aux.vda_name], 0); snprintf (key, sizeof (key), "parent%d", j - 1); sdb_ns_set (sdb_verdef, key, sdb_parent); } snprintf (key, sizeof (key), "verdef%d", cnt); sdb_ns_set (sdb, key, sdb_verdef); if (!verdef->vd_next) { sdb_free (sdb_verdef); goto out_error; } if ((st32)verdef->vd_next < 1) { eprintf ("Warning: Invalid vd_next in the ELF version\n"); break; } i += verdef->vd_next; } free (defs); return sdb; out_error: free (defs); sdb_free (sdb); return NULL; } static Sdb *store_versioninfo_gnu_verneed(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) { ut8 *end, *need = NULL; const char *section_name = ""; Elf_(Shdr) *link_shdr = NULL; const char *link_section_name = ""; Sdb *sdb_vernaux = NULL; Sdb *sdb_version = NULL; Sdb *sdb = NULL; int i, cnt; if (!bin || !bin->dynstr) { return NULL; } if (shdr->sh_link > bin->ehdr.e_shnum) { return NULL; } if (shdr->sh_size < 1 || shdr->sh_size > SIZE_MAX) { return NULL; } sdb = sdb_new0 (); if (!sdb) { return NULL; } link_shdr = &bin->shdr[shdr->sh_link]; if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) { section_name = &bin->shstrtab[shdr->sh_name]; } if (bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) { link_section_name = &bin->shstrtab[link_shdr->sh_name]; } if (!(need = (ut8*) calloc (R_MAX (1, shdr->sh_size), sizeof (ut8)))) { bprintf ("Warning: Cannot allocate memory for Elf_(Verneed)\n"); goto beach; } end = need + shdr->sh_size; sdb_set (sdb, "section_name", section_name, 0); sdb_num_set (sdb, "num_entries", shdr->sh_info, 0); sdb_num_set (sdb, "addr", shdr->sh_addr, 0); sdb_num_set (sdb, "offset", shdr->sh_offset, 0); sdb_num_set (sdb, "link", shdr->sh_link, 0); sdb_set (sdb, "link_section_name", link_section_name, 0); if (shdr->sh_offset > bin->size || shdr->sh_offset + shdr->sh_size > bin->size) { goto beach; } if (shdr->sh_offset + shdr->sh_size < shdr->sh_size) { goto beach; } i = r_buf_read_at (bin->b, shdr->sh_offset, need, shdr->sh_size); if (i < 0) goto beach; //XXX we should use DT_VERNEEDNUM instead of sh_info //TODO https://sourceware.org/ml/binutils/2014-11/msg00353.html for (i = 0, cnt = 0; cnt < shdr->sh_info; ++cnt) { int j, isum; ut8 *vstart = need + i; Elf_(Verneed) vvn = {0}; if (vstart + sizeof (Elf_(Verneed)) > end) { goto beach; } Elf_(Verneed) *entry = &vvn; char key[32] = {0}; sdb_version = sdb_new0 (); if (!sdb_version) { goto beach; } j = 0; vvn.vn_version = READ16 (vstart, j) vvn.vn_cnt = READ16 (vstart, j) vvn.vn_file = READ32 (vstart, j) vvn.vn_aux = READ32 (vstart, j) vvn.vn_next = READ32 (vstart, j) sdb_num_set (sdb_version, "vn_version", entry->vn_version, 0); sdb_num_set (sdb_version, "idx", i, 0); if (entry->vn_file > bin->dynstr_size) { goto beach; } { char *s = r_str_ndup (&bin->dynstr[entry->vn_file], 16); sdb_set (sdb_version, "file_name", s, 0); free (s); } sdb_num_set (sdb_version, "cnt", entry->vn_cnt, 0); st32 vnaux = entry->vn_aux; if (vnaux < 1) { goto beach; } vstart += vnaux; for (j = 0, isum = i + entry->vn_aux; j < entry->vn_cnt && vstart + sizeof (Elf_(Vernaux)) <= end; ++j) { int k; Elf_(Vernaux) * aux = NULL; Elf_(Vernaux) vaux = {0}; sdb_vernaux = sdb_new0 (); if (!sdb_vernaux) { goto beach; } aux = (Elf_(Vernaux)*)&vaux; k = 0; vaux.vna_hash = READ32 (vstart, k) vaux.vna_flags = READ16 (vstart, k) vaux.vna_other = READ16 (vstart, k) vaux.vna_name = READ32 (vstart, k) vaux.vna_next = READ32 (vstart, k) if (aux->vna_name > bin->dynstr_size) { goto beach; } sdb_num_set (sdb_vernaux, "idx", isum, 0); if (aux->vna_name > 0 && aux->vna_name + 8 < bin->dynstr_size) { char name [16]; strncpy (name, &bin->dynstr[aux->vna_name], sizeof (name)-1); name[sizeof(name)-1] = 0; sdb_set (sdb_vernaux, "name", name, 0); } sdb_set (sdb_vernaux, "flags", get_ver_flags (aux->vna_flags), 0); sdb_num_set (sdb_vernaux, "version", aux->vna_other, 0); isum += aux->vna_next; vstart += aux->vna_next; snprintf (key, sizeof (key), "vernaux%d", j); sdb_ns_set (sdb_version, key, sdb_vernaux); } if ((int)entry->vn_next < 0) { bprintf ("Invalid vn_next\n"); break; } i += entry->vn_next; snprintf (key, sizeof (key), "version%d", cnt ); sdb_ns_set (sdb, key, sdb_version); //if entry->vn_next is 0 it iterate infinitely if (!entry->vn_next) { break; } } free (need); return sdb; beach: free (need); sdb_free (sdb_vernaux); sdb_free (sdb_version); sdb_free (sdb); return NULL; } static Sdb *store_versioninfo(ELFOBJ *bin) { Sdb *sdb_versioninfo = NULL; int num_verdef = 0; int num_verneed = 0; int num_versym = 0; int i; if (!bin || !bin->shdr) { return NULL; } if (!(sdb_versioninfo = sdb_new0 ())) { return NULL; } for (i = 0; i < bin->ehdr.e_shnum; i++) { Sdb *sdb = NULL; char key[32] = {0}; int size = bin->shdr[i].sh_size; if (size - (i*sizeof(Elf_(Shdr)) > bin->size)) { size = bin->size - (i*sizeof(Elf_(Shdr))); } int left = size - (i * sizeof (Elf_(Shdr))); left = R_MIN (left, bin->shdr[i].sh_size); if (left < 0) { break; } switch (bin->shdr[i].sh_type) { case SHT_GNU_verdef: sdb = store_versioninfo_gnu_verdef (bin, &bin->shdr[i], left); snprintf (key, sizeof (key), "verdef%d", num_verdef++); sdb_ns_set (sdb_versioninfo, key, sdb); break; case SHT_GNU_verneed: sdb = store_versioninfo_gnu_verneed (bin, &bin->shdr[i], left); snprintf (key, sizeof (key), "verneed%d", num_verneed++); sdb_ns_set (sdb_versioninfo, key, sdb); break; case SHT_GNU_versym: sdb = store_versioninfo_gnu_versym (bin, &bin->shdr[i], left); snprintf (key, sizeof (key), "versym%d", num_versym++); sdb_ns_set (sdb_versioninfo, key, sdb); break; } } return sdb_versioninfo; } static bool init_dynstr(ELFOBJ *bin) { int i, r; const char *section_name = NULL; if (!bin || !bin->shdr) { return false; } if (!bin->shstrtab) { return false; } for (i = 0; i < bin->ehdr.e_shnum; ++i) { if (bin->shdr[i].sh_name > bin->shstrtab_size) { return false; } section_name = &bin->shstrtab[bin->shdr[i].sh_name]; if (bin->shdr[i].sh_type == SHT_STRTAB && !strcmp (section_name, ".dynstr")) { if (!(bin->dynstr = (char*) calloc (bin->shdr[i].sh_size + 1, sizeof (char)))) { bprintf("Warning: Cannot allocate memory for dynamic strings\n"); return false; } if (bin->shdr[i].sh_offset > bin->size) { return false; } if (bin->shdr[i].sh_offset + bin->shdr[i].sh_size > bin->size) { return false; } if (bin->shdr[i].sh_offset + bin->shdr[i].sh_size < bin->shdr[i].sh_size) { return false; } r = r_buf_read_at (bin->b, bin->shdr[i].sh_offset, (ut8*)bin->dynstr, bin->shdr[i].sh_size); if (r < 1) { R_FREE (bin->dynstr); bin->dynstr_size = 0; return false; } bin->dynstr_size = bin->shdr[i].sh_size; return true; } } return false; } static int elf_init(ELFOBJ *bin) { bin->phdr = NULL; bin->shdr = NULL; bin->strtab = NULL; bin->shstrtab = NULL; bin->strtab_size = 0; bin->strtab_section = NULL; bin->dyn_buf = NULL; bin->dynstr = NULL; ZERO_FILL (bin->version_info); bin->g_sections = NULL; bin->g_symbols = NULL; bin->g_imports = NULL; /* bin is not an ELF */ if (!init_ehdr (bin)) { return false; } if (!init_phdr (bin)) { bprintf ("Warning: Cannot initialize program headers\n"); } if (!init_shdr (bin)) { bprintf ("Warning: Cannot initialize section headers\n"); } if (!init_strtab (bin)) { bprintf ("Warning: Cannot initialize strings table\n"); } if (!init_dynstr (bin)) { bprintf ("Warning: Cannot initialize dynamic strings\n"); } bin->baddr = Elf_(r_bin_elf_get_baddr) (bin); if (!init_dynamic_section (bin) && !Elf_(r_bin_elf_get_static)(bin)) bprintf ("Warning: Cannot initialize dynamic section\n"); bin->imports_by_ord_size = 0; bin->imports_by_ord = NULL; bin->symbols_by_ord_size = 0; bin->symbols_by_ord = NULL; bin->g_sections = Elf_(r_bin_elf_get_sections) (bin); bin->boffset = Elf_(r_bin_elf_get_boffset) (bin); sdb_ns_set (bin->kv, "versioninfo", store_versioninfo (bin)); return true; } ut64 Elf_(r_bin_elf_get_section_offset)(ELFOBJ *bin, const char *section_name) { RBinElfSection *section = get_section_by_name (bin, section_name); if (!section) return UT64_MAX; return section->offset; } ut64 Elf_(r_bin_elf_get_section_addr)(ELFOBJ *bin, const char *section_name) { RBinElfSection *section = get_section_by_name (bin, section_name); return section? section->rva: UT64_MAX; } ut64 Elf_(r_bin_elf_get_section_addr_end)(ELFOBJ *bin, const char *section_name) { RBinElfSection *section = get_section_by_name (bin, section_name); return section? section->rva + section->size: UT64_MAX; } #define REL (is_rela ? (void*)rela : (void*)rel) #define REL_BUF is_rela ? (ut8*)(&rela[k]) : (ut8*)(&rel[k]) #define REL_OFFSET is_rela ? rela[k].r_offset : rel[k].r_offset #define REL_TYPE is_rela ? rela[k].r_info : rel[k].r_info static ut64 get_import_addr(ELFOBJ *bin, int sym) { Elf_(Rel) *rel = NULL; Elf_(Rela) *rela = NULL; ut8 rl[sizeof (Elf_(Rel))] = {0}; ut8 rla[sizeof (Elf_(Rela))] = {0}; RBinElfSection *rel_sec = NULL; Elf_(Addr) plt_sym_addr = -1; ut64 got_addr, got_offset; ut64 plt_addr; int j, k, tsize, len, nrel; bool is_rela = false; const char *rel_sect[] = { ".rel.plt", ".rela.plt", ".rel.dyn", ".rela.dyn", NULL }; const char *rela_sect[] = { ".rela.plt", ".rel.plt", ".rela.dyn", ".rel.dyn", NULL }; if ((!bin->shdr || !bin->strtab) && !bin->phdr) { return -1; } if ((got_offset = Elf_(r_bin_elf_get_section_offset) (bin, ".got")) == -1 && (got_offset = Elf_(r_bin_elf_get_section_offset) (bin, ".got.plt")) == -1) { return -1; } if ((got_addr = Elf_(r_bin_elf_get_section_addr) (bin, ".got")) == -1 && (got_addr = Elf_(r_bin_elf_get_section_addr) (bin, ".got.plt")) == -1) { return -1; } if (bin->is_rela == DT_REL) { j = 0; while (!rel_sec && rel_sect[j]) { rel_sec = get_section_by_name (bin, rel_sect[j++]); } tsize = sizeof (Elf_(Rel)); } else if (bin->is_rela == DT_RELA) { j = 0; while (!rel_sec && rela_sect[j]) { rel_sec = get_section_by_name (bin, rela_sect[j++]); } is_rela = true; tsize = sizeof (Elf_(Rela)); } if (!rel_sec) { return -1; } if (rel_sec->size < 1) { return -1; } nrel = (ut32)((int)rel_sec->size / (int)tsize); if (nrel < 1) { return -1; } if (is_rela) { rela = calloc (nrel, tsize); if (!rela) { return -1; } } else { rel = calloc (nrel, tsize); if (!rel) { return -1; } } for (j = k = 0; j < rel_sec->size && k < nrel; j += tsize, k++) { int l = 0; if (rel_sec->offset + j > bin->size) { goto out; } if (rel_sec->offset + j + tsize > bin->size) { goto out; } len = r_buf_read_at ( bin->b, rel_sec->offset + j, is_rela ? rla : rl, is_rela ? sizeof (Elf_ (Rela)) : sizeof (Elf_ (Rel))); if (len < 1) { goto out; } #if R_BIN_ELF64 if (is_rela) { rela[k].r_offset = READ64 (rla, l) rela[k].r_info = READ64 (rla, l) rela[k].r_addend = READ64 (rla, l) } else { rel[k].r_offset = READ64 (rl, l) rel[k].r_info = READ64 (rl, l) } #else if (is_rela) { rela[k].r_offset = READ32 (rla, l) rela[k].r_info = READ32 (rla, l) rela[k].r_addend = READ32 (rla, l) } else { rel[k].r_offset = READ32 (rl, l) rel[k].r_info = READ32 (rl, l) } #endif int reloc_type = ELF_R_TYPE (REL_TYPE); int reloc_sym = ELF_R_SYM (REL_TYPE); if (reloc_sym == sym) { int of = REL_OFFSET; of = of - got_addr + got_offset; switch (bin->ehdr.e_machine) { case EM_PPC: case EM_PPC64: { RBinElfSection *s = get_section_by_name (bin, ".plt"); if (s) { ut8 buf[4]; ut64 base; len = r_buf_read_at (bin->b, s->offset, buf, sizeof (buf)); if (len < 4) { goto out; } base = r_read_be32 (buf); base -= (nrel * 16); base += (k * 16); plt_addr = base; free (REL); return plt_addr; } } break; case EM_SPARC: case EM_SPARCV9: case EM_SPARC32PLUS: plt_addr = Elf_(r_bin_elf_get_section_addr) (bin, ".plt"); if (plt_addr == -1) { free (rela); return -1; } if (reloc_type == R_386_PC16) { plt_addr += k * 12 + 20; // thumb symbol if (plt_addr & 1) { plt_addr--; } free (REL); return plt_addr; } else { bprintf ("Unknown sparc reloc type %d\n", reloc_type); } /* SPARC */ break; case EM_ARM: case EM_AARCH64: plt_addr = Elf_(r_bin_elf_get_section_addr) (bin, ".plt"); if (plt_addr == -1) { free (rela); return UT32_MAX; } switch (reloc_type) { case R_386_8: { plt_addr += k * 12 + 20; // thumb symbol if (plt_addr & 1) { plt_addr--; } free (REL); return plt_addr; } break; case 1026: // arm64 aarch64 plt_sym_addr = plt_addr + k * 16 + 32; goto done; default: bprintf ("Unsupported relocation type for imports %d\n", reloc_type); break; } break; case EM_386: case EM_X86_64: switch (reloc_type) { case 1: // unknown relocs found in voidlinux for x86-64 // break; case R_386_GLOB_DAT: case R_386_JMP_SLOT: { ut8 buf[8]; if (of + sizeof(Elf_(Addr)) < bin->size) { // ONLY FOR X86 if (of > bin->size || of + sizeof (Elf_(Addr)) > bin->size) { goto out; } len = r_buf_read_at (bin->b, of, buf, sizeof (Elf_(Addr))); if (len < -1) { goto out; } plt_sym_addr = sizeof (Elf_(Addr)) == 4 ? r_read_le32 (buf) : r_read_le64 (buf); if (!plt_sym_addr) { //XXX HACK ALERT!!!! full relro?? try to fix it //will there always be .plt.got, what would happen if is .got.plt? RBinElfSection *s = get_section_by_name (bin, ".plt.got"); if (Elf_(r_bin_elf_has_relro)(bin) < R_ELF_PART_RELRO || !s) { goto done; } plt_addr = s->offset; of = of + got_addr - got_offset; while (plt_addr + 2 + 4 < s->offset + s->size) { /*we try to locate the plt entry that correspond with the relocation since got does not point back to .plt. In this case it has the following form ff253a152000 JMP QWORD [RIP + 0x20153A] 6690 NOP ---- ff25ec9f0408 JMP DWORD [reloc.puts_236] plt_addr + 2 to remove jmp opcode and get the imm reading 4 and if RIP (plt_addr + 6) + imm == rel->offset return plt_addr, that will be our sym addr perhaps this hack doesn't work on 32 bits */ len = r_buf_read_at (bin->b, plt_addr + 2, buf, 4); if (len < -1) { goto out; } plt_sym_addr = sizeof (Elf_(Addr)) == 4 ? r_read_le32 (buf) : r_read_le64 (buf); //relative address if ((plt_addr + 6 + Elf_(r_bin_elf_v2p) (bin, plt_sym_addr)) == of) { plt_sym_addr = plt_addr; goto done; } else if (plt_sym_addr == of) { plt_sym_addr = plt_addr; goto done; } plt_addr += 8; } } else { plt_sym_addr -= 6; } goto done; } break; } default: bprintf ("Unsupported relocation type for imports %d\n", reloc_type); free (REL); return of; break; } break; case 8: // MIPS32 BIG ENDIAN relocs { RBinElfSection *s = get_section_by_name (bin, ".rela.plt"); if (s) { ut8 buf[1024]; const ut8 *base; plt_addr = s->rva + s->size; len = r_buf_read_at (bin->b, s->offset + s->size, buf, sizeof (buf)); if (len != sizeof (buf)) { // oops } base = r_mem_mem_aligned (buf, sizeof (buf), (const ut8*)"\x3c\x0f\x00", 3, 4); if (base) { plt_addr += (int)(size_t)(base - buf); } else { plt_addr += 108 + 8; // HARDCODED HACK } plt_addr += k * 16; free (REL); return plt_addr; } } break; default: bprintf ("Unsupported relocs type %d for arch %d\n", reloc_type, bin->ehdr.e_machine); break; } } } done: free (REL); return plt_sym_addr; out: free (REL); return -1; } int Elf_(r_bin_elf_has_nx)(ELFOBJ *bin) { int i; if (bin && bin->phdr) { for (i = 0; i < bin->ehdr.e_phnum; i++) { if (bin->phdr[i].p_type == PT_GNU_STACK) { return (!(bin->phdr[i].p_flags & 1))? 1: 0; } } } return 0; } int Elf_(r_bin_elf_has_relro)(ELFOBJ *bin) { int i; bool haveBindNow = false; bool haveGnuRelro = false; if (bin && bin->dyn_buf) { for (i = 0; i < bin->dyn_entries; i++) { switch (bin->dyn_buf[i].d_tag) { case DT_BIND_NOW: haveBindNow = true; break; case DT_FLAGS: for (i++; i < bin->dyn_entries ; i++) { ut32 dTag = bin->dyn_buf[i].d_tag; if (!dTag) { break; } switch (dTag) { case DT_FLAGS_1: if (bin->dyn_buf[i].d_un.d_val & DF_1_NOW) { haveBindNow = true; break; } } } break; } } } if (bin && bin->phdr) { for (i = 0; i < bin->ehdr.e_phnum; i++) { if (bin->phdr[i].p_type == PT_GNU_RELRO) { haveGnuRelro = true; break; } } } if (haveGnuRelro) { if (haveBindNow) { return R_ELF_FULL_RELRO; } return R_ELF_PART_RELRO; } return R_ELF_NO_RELRO; } /* To compute the base address, one determines the memory address associated with the lowest p_vaddr value for a PT_LOAD segment. One then obtains the base address by truncating the memory address to the nearest multiple of the maximum page size */ ut64 Elf_(r_bin_elf_get_baddr)(ELFOBJ *bin) { int i; ut64 tmp, base = UT64_MAX; if (!bin) { return 0; } if (bin->phdr) { for (i = 0; i < bin->ehdr.e_phnum; i++) { if (bin->phdr[i].p_type == PT_LOAD) { tmp = (ut64)bin->phdr[i].p_vaddr & ELF_PAGE_MASK; tmp = tmp - (tmp % (1 << ELF_PAGE_SIZE)); if (tmp < base) { base = tmp; } } } } if (base == UT64_MAX && bin->ehdr.e_type == ET_REL) { //we return our own base address for ET_REL type //we act as a loader for ELF return 0x08000000; } return base == UT64_MAX ? 0 : base; } ut64 Elf_(r_bin_elf_get_boffset)(ELFOBJ *bin) { int i; ut64 tmp, base = UT64_MAX; if (bin && bin->phdr) { for (i = 0; i < bin->ehdr.e_phnum; i++) { if (bin->phdr[i].p_type == PT_LOAD) { tmp = (ut64)bin->phdr[i].p_offset & ELF_PAGE_MASK; tmp = tmp - (tmp % (1 << ELF_PAGE_SIZE)); if (tmp < base) { base = tmp; } } } } return base == UT64_MAX ? 0 : base; } ut64 Elf_(r_bin_elf_get_init_offset)(ELFOBJ *bin) { ut64 entry = Elf_(r_bin_elf_get_entry_offset) (bin); ut8 buf[512]; if (!bin) { return 0LL; } if (r_buf_read_at (bin->b, entry + 16, buf, sizeof (buf)) < 1) { bprintf ("Warning: read (init_offset)\n"); return 0; } if (buf[0] == 0x68) { // push // x86 only ut64 addr; memmove (buf, buf+1, 4); addr = (ut64)r_read_le32 (buf); return Elf_(r_bin_elf_v2p) (bin, addr); } return 0; } ut64 Elf_(r_bin_elf_get_fini_offset)(ELFOBJ *bin) { ut64 entry = Elf_(r_bin_elf_get_entry_offset) (bin); ut8 buf[512]; if (!bin) { return 0LL; } if (r_buf_read_at (bin->b, entry+11, buf, sizeof (buf)) == -1) { bprintf ("Warning: read (get_fini)\n"); return 0; } if (*buf == 0x68) { // push // x86/32 only ut64 addr; memmove (buf, buf+1, 4); addr = (ut64)r_read_le32 (buf); return Elf_(r_bin_elf_v2p) (bin, addr); } return 0; } ut64 Elf_(r_bin_elf_get_entry_offset)(ELFOBJ *bin) { ut64 entry; if (!bin) { return 0LL; } entry = bin->ehdr.e_entry; if (!entry) { entry = Elf_(r_bin_elf_get_section_offset)(bin, ".init.text"); if (entry != UT64_MAX) { return entry; } entry = Elf_(r_bin_elf_get_section_offset)(bin, ".text"); if (entry != UT64_MAX) { return entry; } entry = Elf_(r_bin_elf_get_section_offset)(bin, ".init"); if (entry != UT64_MAX) { return entry; } if (entry == UT64_MAX) { return 0; } } return Elf_(r_bin_elf_v2p) (bin, entry); } static ut64 getmainsymbol(ELFOBJ *bin) { struct r_bin_elf_symbol_t *symbol; int i; if (!(symbol = Elf_(r_bin_elf_get_symbols) (bin))) { return UT64_MAX; } for (i = 0; !symbol[i].last; i++) { if (!strcmp (symbol[i].name, "main")) { ut64 paddr = symbol[i].offset; return Elf_(r_bin_elf_p2v) (bin, paddr); } } return UT64_MAX; } ut64 Elf_(r_bin_elf_get_main_offset)(ELFOBJ *bin) { ut64 entry = Elf_(r_bin_elf_get_entry_offset) (bin); ut8 buf[512]; if (!bin) { return 0LL; } if (entry > bin->size || (entry + sizeof (buf)) > bin->size) { return 0; } if (r_buf_read_at (bin->b, entry, buf, sizeof (buf)) < 1) { bprintf ("Warning: read (main)\n"); return 0; } // ARM64 if (buf[0x18+3] == 0x58 && buf[0x2f] == 0x00) { ut32 entry_vaddr = Elf_(r_bin_elf_p2v) (bin, entry); ut32 main_addr = r_read_le32 (&buf[0x30]); if ((main_addr >> 16) == (entry_vaddr >> 16)) { return Elf_(r_bin_elf_v2p) (bin, main_addr); } } // TODO: Use arch to identify arch before memcmp's // ARM ut64 text = Elf_(r_bin_elf_get_section_offset)(bin, ".text"); ut64 text_end = text + bin->size; // ARM-Thumb-Linux if (entry & 1 && !memcmp (buf, "\xf0\x00\x0b\x4f\xf0\x00", 6)) { ut32 * ptr = (ut32*)(buf+40-1); if (*ptr &1) { return Elf_(r_bin_elf_v2p) (bin, *ptr -1); } } if (!memcmp (buf, "\x00\xb0\xa0\xe3\x00\xe0\xa0\xe3", 8)) { // endian stuff here ut32 *addr = (ut32*)(buf+0x34); /* 0x00012000 00b0a0e3 mov fp, 0 0x00012004 00e0a0e3 mov lr, 0 */ if (*addr > text && *addr < (text_end)) { return Elf_(r_bin_elf_v2p) (bin, *addr); } } // MIPS /* get .got, calculate offset of main symbol */ if (!memcmp (buf, "\x21\x00\xe0\x03\x01\x00\x11\x04", 8)) { /* assuming the startup code looks like got = gp-0x7ff0 got[index__libc_start_main] ( got[index_main] ); looking for the instruction generating the first argument to find main lw a0, offset(gp) */ ut64 got_offset; if ((got_offset = Elf_(r_bin_elf_get_section_offset) (bin, ".got")) != -1 || (got_offset = Elf_(r_bin_elf_get_section_offset) (bin, ".got.plt")) != -1) { const ut64 gp = got_offset + 0x7ff0; unsigned i; for (i = 0; i < sizeof(buf) / sizeof(buf[0]); i += 4) { const ut32 instr = r_read_le32 (&buf[i]); if ((instr & 0xffff0000) == 0x8f840000) { // lw a0, offset(gp) const short delta = instr & 0x0000ffff; r_buf_read_at (bin->b, /* got_entry_offset = */ gp + delta, buf, 4); return Elf_(r_bin_elf_v2p) (bin, r_read_le32 (&buf[0])); } } } return 0; } // ARM if (!memcmp (buf, "\x24\xc0\x9f\xe5\x00\xb0\xa0\xe3", 8)) { ut64 addr = r_read_le32 (&buf[48]); return Elf_(r_bin_elf_v2p) (bin, addr); } // X86-CGC if (buf[0] == 0xe8 && !memcmp (buf + 5, "\x50\xe8\x00\x00\x00\x00\xb8\x01\x00\x00\x00\x53", 12)) { size_t SIZEOF_CALL = 5; ut64 rel_addr = (ut64)((int)(buf[1] + (buf[2] << 8) + (buf[3] << 16) + (buf[4] << 24))); ut64 addr = Elf_(r_bin_elf_p2v)(bin, entry + SIZEOF_CALL); addr += rel_addr; return Elf_(r_bin_elf_v2p) (bin, addr); } // X86-PIE if (buf[0x00] == 0x48 && buf[0x1e] == 0x8d && buf[0x11] == 0xe8) { ut32 *pmain = (ut32*)(buf + 0x30); ut64 vmain = Elf_(r_bin_elf_p2v) (bin, (ut64)*pmain); ut64 ventry = Elf_(r_bin_elf_p2v) (bin, entry); if (vmain >> 16 == ventry >> 16) { return (ut64)vmain; } } // X86-PIE if (buf[0x1d] == 0x48 && buf[0x1e] == 0x8b) { if (!memcmp (buf, "\x31\xed\x49\x89", 4)) {// linux ut64 maddr, baddr; ut8 n32s[sizeof (ut32)] = {0}; maddr = entry + 0x24 + r_read_le32 (buf + 0x20); if (r_buf_read_at (bin->b, maddr, n32s, sizeof (ut32)) == -1) { bprintf ("Warning: read (maddr) 2\n"); return 0; } maddr = (ut64)r_read_le32 (&n32s[0]); baddr = (bin->ehdr.e_entry >> 16) << 16; if (bin->phdr) { baddr = Elf_(r_bin_elf_get_baddr) (bin); } maddr += baddr; return maddr; } } // X86-NONPIE #if R_BIN_ELF64 if (!memcmp (buf, "\x49\x89\xd9", 3) && buf[156] == 0xe8) { // openbsd return r_read_le32 (&buf[157]) + entry + 156 + 5; } if (!memcmp (buf+29, "\x48\xc7\xc7", 3)) { // linux ut64 addr = (ut64)r_read_le32 (&buf[29 + 3]); return Elf_(r_bin_elf_v2p) (bin, addr); } #else if (buf[23] == '\x68') { ut64 addr = (ut64)r_read_le32 (&buf[23 + 1]); return Elf_(r_bin_elf_v2p) (bin, addr); } #endif /* linux64 pie main -- probably buggy in some cases */ if (buf[29] == 0x48 && buf[30] == 0x8d) { // lea rdi, qword [rip-0x21c4] ut8 *p = buf + 32; st32 maindelta = (st32)r_read_le32 (p); ut64 vmain = (ut64)(entry + 29 + maindelta) + 7; ut64 ventry = Elf_(r_bin_elf_p2v) (bin, entry); if (vmain>>16 == ventry>>16) { return (ut64)vmain; } } /* find sym.main if possible */ { ut64 m = getmainsymbol (bin); if (m != UT64_MAX) return m; } return UT64_MAX; } int Elf_(r_bin_elf_get_stripped)(ELFOBJ *bin) { int i; if (!bin->shdr) { return false; } for (i = 0; i < bin->ehdr.e_shnum; i++) { if (bin->shdr[i].sh_type == SHT_SYMTAB) { return false; } } return true; } char *Elf_(r_bin_elf_intrp)(ELFOBJ *bin) { int i; if (!bin || !bin->phdr) { return NULL; } for (i = 0; i < bin->ehdr.e_phnum; i++) { if (bin->phdr[i].p_type == PT_INTERP) { char *str = NULL; ut64 addr = bin->phdr[i].p_offset; int sz = bin->phdr[i].p_memsz; sdb_num_set (bin->kv, "elf_header.intrp_addr", addr, 0); sdb_num_set (bin->kv, "elf_header.intrp_size", sz, 0); if (sz < 1) { return NULL; } str = malloc (sz + 1); if (!str) { return NULL; } if (r_buf_read_at (bin->b, addr, (ut8*)str, sz) < 1) { bprintf ("Warning: read (main)\n"); return 0; } str[sz] = 0; sdb_set (bin->kv, "elf_header.intrp", str, 0); return str; } } return NULL; } int Elf_(r_bin_elf_get_static)(ELFOBJ *bin) { int i; if (!bin->phdr) { return false; } for (i = 0; i < bin->ehdr.e_phnum; i++) { if (bin->phdr[i].p_type == PT_INTERP) { return false; } } return true; } char* Elf_(r_bin_elf_get_data_encoding)(ELFOBJ *bin) { switch (bin->ehdr.e_ident[EI_DATA]) { case ELFDATANONE: return strdup ("none"); case ELFDATA2LSB: return strdup ("2's complement, little endian"); case ELFDATA2MSB: return strdup ("2's complement, big endian"); default: return r_str_newf ("<unknown: %x>", bin->ehdr.e_ident[EI_DATA]); } } int Elf_(r_bin_elf_has_va)(ELFOBJ *bin) { return true; } char* Elf_(r_bin_elf_get_arch)(ELFOBJ *bin) { switch (bin->ehdr.e_machine) { case EM_ARC: case EM_ARC_A5: return strdup ("arc"); case EM_AVR: return strdup ("avr"); case EM_CRIS: return strdup ("cris"); case EM_68K: return strdup ("m68k"); case EM_MIPS: case EM_MIPS_RS3_LE: case EM_MIPS_X: return strdup ("mips"); case EM_MCST_ELBRUS: return strdup ("elbrus"); case EM_TRICORE: return strdup ("tricore"); case EM_ARM: case EM_AARCH64: return strdup ("arm"); case EM_HEXAGON: return strdup ("hexagon"); case EM_BLACKFIN: return strdup ("blackfin"); case EM_SPARC: case EM_SPARC32PLUS: case EM_SPARCV9: return strdup ("sparc"); case EM_PPC: case EM_PPC64: return strdup ("ppc"); case EM_PARISC: return strdup ("hppa"); case EM_PROPELLER: return strdup ("propeller"); case EM_MICROBLAZE: return strdup ("microblaze.gnu"); case EM_RISCV: return strdup ("riscv"); case EM_VAX: return strdup ("vax"); case EM_XTENSA: return strdup ("xtensa"); case EM_LANAI: return strdup ("lanai"); case EM_VIDEOCORE3: case EM_VIDEOCORE4: return strdup ("vc4"); case EM_SH: return strdup ("sh"); case EM_V850: return strdup ("v850"); case EM_IA_64: return strdup("ia64"); default: return strdup ("x86"); } } char* Elf_(r_bin_elf_get_machine_name)(ELFOBJ *bin) { switch (bin->ehdr.e_machine) { case EM_NONE: return strdup ("No machine"); case EM_M32: return strdup ("AT&T WE 32100"); case EM_SPARC: return strdup ("SUN SPARC"); case EM_386: return strdup ("Intel 80386"); case EM_68K: return strdup ("Motorola m68k family"); case EM_88K: return strdup ("Motorola m88k family"); case EM_860: return strdup ("Intel 80860"); case EM_MIPS: return strdup ("MIPS R3000"); case EM_S370: return strdup ("IBM System/370"); case EM_MIPS_RS3_LE: return strdup ("MIPS R3000 little-endian"); case EM_PARISC: return strdup ("HPPA"); case EM_VPP500: return strdup ("Fujitsu VPP500"); case EM_SPARC32PLUS: return strdup ("Sun's \"v8plus\""); case EM_960: return strdup ("Intel 80960"); case EM_PPC: return strdup ("PowerPC"); case EM_PPC64: return strdup ("PowerPC 64-bit"); case EM_S390: return strdup ("IBM S390"); case EM_V800: return strdup ("NEC V800 series"); case EM_FR20: return strdup ("Fujitsu FR20"); case EM_RH32: return strdup ("TRW RH-32"); case EM_RCE: return strdup ("Motorola RCE"); case EM_ARM: return strdup ("ARM"); case EM_BLACKFIN: return strdup ("Analog Devices Blackfin"); case EM_FAKE_ALPHA: return strdup ("Digital Alpha"); case EM_SH: return strdup ("Hitachi SH"); case EM_SPARCV9: return strdup ("SPARC v9 64-bit"); case EM_TRICORE: return strdup ("Siemens Tricore"); case EM_ARC: return strdup ("Argonaut RISC Core"); case EM_H8_300: return strdup ("Hitachi H8/300"); case EM_H8_300H: return strdup ("Hitachi H8/300H"); case EM_H8S: return strdup ("Hitachi H8S"); case EM_H8_500: return strdup ("Hitachi H8/500"); case EM_IA_64: return strdup ("Intel Merced"); case EM_MIPS_X: return strdup ("Stanford MIPS-X"); case EM_COLDFIRE: return strdup ("Motorola Coldfire"); case EM_68HC12: return strdup ("Motorola M68HC12"); case EM_MMA: return strdup ("Fujitsu MMA Multimedia Accelerator"); case EM_PCP: return strdup ("Siemens PCP"); case EM_NCPU: return strdup ("Sony nCPU embeeded RISC"); case EM_NDR1: return strdup ("Denso NDR1 microprocessor"); case EM_STARCORE: return strdup ("Motorola Start*Core processor"); case EM_ME16: return strdup ("Toyota ME16 processor"); case EM_ST100: return strdup ("STMicroelectronic ST100 processor"); case EM_TINYJ: return strdup ("Advanced Logic Corp. Tinyj emb.fam"); case EM_X86_64: return strdup ("AMD x86-64 architecture"); case EM_LANAI: return strdup ("32bit LANAI architecture"); case EM_PDSP: return strdup ("Sony DSP Processor"); case EM_FX66: return strdup ("Siemens FX66 microcontroller"); case EM_ST9PLUS: return strdup ("STMicroelectronics ST9+ 8/16 mc"); case EM_ST7: return strdup ("STmicroelectronics ST7 8 bit mc"); case EM_68HC16: return strdup ("Motorola MC68HC16 microcontroller"); case EM_68HC11: return strdup ("Motorola MC68HC11 microcontroller"); case EM_68HC08: return strdup ("Motorola MC68HC08 microcontroller"); case EM_68HC05: return strdup ("Motorola MC68HC05 microcontroller"); case EM_SVX: return strdup ("Silicon Graphics SVx"); case EM_ST19: return strdup ("STMicroelectronics ST19 8 bit mc"); case EM_VAX: return strdup ("Digital VAX"); case EM_CRIS: return strdup ("Axis Communications 32-bit embedded processor"); case EM_JAVELIN: return strdup ("Infineon Technologies 32-bit embedded processor"); case EM_FIREPATH: return strdup ("Element 14 64-bit DSP Processor"); case EM_ZSP: return strdup ("LSI Logic 16-bit DSP Processor"); case EM_MMIX: return strdup ("Donald Knuth's educational 64-bit processor"); case EM_HUANY: return strdup ("Harvard University machine-independent object files"); case EM_PRISM: return strdup ("SiTera Prism"); case EM_AVR: return strdup ("Atmel AVR 8-bit microcontroller"); case EM_FR30: return strdup ("Fujitsu FR30"); case EM_D10V: return strdup ("Mitsubishi D10V"); case EM_D30V: return strdup ("Mitsubishi D30V"); case EM_V850: return strdup ("NEC v850"); case EM_M32R: return strdup ("Mitsubishi M32R"); case EM_MN10300: return strdup ("Matsushita MN10300"); case EM_MN10200: return strdup ("Matsushita MN10200"); case EM_PJ: return strdup ("picoJava"); case EM_OPENRISC: return strdup ("OpenRISC 32-bit embedded processor"); case EM_ARC_A5: return strdup ("ARC Cores Tangent-A5"); case EM_XTENSA: return strdup ("Tensilica Xtensa Architecture"); case EM_AARCH64: return strdup ("ARM aarch64"); case EM_PROPELLER: return strdup ("Parallax Propeller"); case EM_MICROBLAZE: return strdup ("Xilinx MicroBlaze"); case EM_RISCV: return strdup ("RISC V"); case EM_VIDEOCORE3: return strdup ("VideoCore III"); case EM_VIDEOCORE4: return strdup ("VideoCore IV"); default: return r_str_newf ("<unknown>: 0x%x", bin->ehdr.e_machine); } } char* Elf_(r_bin_elf_get_file_type)(ELFOBJ *bin) { ut32 e_type; if (!bin) { return NULL; } e_type = (ut32)bin->ehdr.e_type; // cast to avoid warn in iphone-gcc, must be ut16 switch (e_type) { case ET_NONE: return strdup ("NONE (None)"); case ET_REL: return strdup ("REL (Relocatable file)"); case ET_EXEC: return strdup ("EXEC (Executable file)"); case ET_DYN: return strdup ("DYN (Shared object file)"); case ET_CORE: return strdup ("CORE (Core file)"); } if ((e_type >= ET_LOPROC) && (e_type <= ET_HIPROC)) { return r_str_newf ("Processor Specific: %x", e_type); } if ((e_type >= ET_LOOS) && (e_type <= ET_HIOS)) { return r_str_newf ("OS Specific: %x", e_type); } return r_str_newf ("<unknown>: %x", e_type); } char* Elf_(r_bin_elf_get_elf_class)(ELFOBJ *bin) { switch (bin->ehdr.e_ident[EI_CLASS]) { case ELFCLASSNONE: return strdup ("none"); case ELFCLASS32: return strdup ("ELF32"); case ELFCLASS64: return strdup ("ELF64"); default: return r_str_newf ("<unknown: %x>", bin->ehdr.e_ident[EI_CLASS]); } } int Elf_(r_bin_elf_get_bits)(ELFOBJ *bin) { /* Hack for ARCompact */ if (bin->ehdr.e_machine == EM_ARC_A5) { return 16; } /* Hack for Ps2 */ if (bin->phdr && bin->ehdr.e_machine == EM_MIPS) { const ut32 mipsType = bin->ehdr.e_flags & EF_MIPS_ARCH; if (bin->ehdr.e_type == ET_EXEC) { int i; bool haveInterp = false; for (i = 0; i < bin->ehdr.e_phnum; i++) { if (bin->phdr[i].p_type == PT_INTERP) { haveInterp = true; } } if (!haveInterp && mipsType == EF_MIPS_ARCH_3) { // Playstation2 Hack return 64; } } // TODO: show this specific asm.cpu somewhere in bininfo (mips1, mips2, mips3, mips32r2, ...) switch (mipsType) { case EF_MIPS_ARCH_1: case EF_MIPS_ARCH_2: case EF_MIPS_ARCH_3: case EF_MIPS_ARCH_4: case EF_MIPS_ARCH_5: case EF_MIPS_ARCH_32: return 32; case EF_MIPS_ARCH_64: return 64; case EF_MIPS_ARCH_32R2: return 32; case EF_MIPS_ARCH_64R2: return 64; break; } return 32; } /* Hack for Thumb */ if (bin->ehdr.e_machine == EM_ARM) { if (bin->ehdr.e_type != ET_EXEC) { struct r_bin_elf_symbol_t *symbol; if ((symbol = Elf_(r_bin_elf_get_symbols) (bin))) { int i = 0; for (i = 0; !symbol[i].last; i++) { ut64 paddr = symbol[i].offset; if (paddr & 1) { return 16; } } } } { ut64 entry = Elf_(r_bin_elf_get_entry_offset) (bin); if (entry & 1) { return 16; } } } switch (bin->ehdr.e_ident[EI_CLASS]) { case ELFCLASS32: return 32; case ELFCLASS64: return 64; case ELFCLASSNONE: default: return 32; // defaults } } static inline int noodle(ELFOBJ *bin, const char *s) { const ut8 *p = bin->b->buf; if (bin->b->length > 64) { p += bin->b->length - 64; } else { return 0; } return r_mem_mem (p, 64, (const ut8 *)s, strlen (s)) != NULL; } static inline int needle(ELFOBJ *bin, const char *s) { if (bin->shstrtab) { ut32 len = bin->shstrtab_size; if (len > 4096) { len = 4096; // avoid slow loading .. can be buggy? } return r_mem_mem ((const ut8*)bin->shstrtab, len, (const ut8*)s, strlen (s)) != NULL; } return 0; } // TODO: must return const char * all those strings must be const char os[LINUX] or so char* Elf_(r_bin_elf_get_osabi_name)(ELFOBJ *bin) { switch (bin->ehdr.e_ident[EI_OSABI]) { case ELFOSABI_LINUX: return strdup("linux"); case ELFOSABI_SOLARIS: return strdup("solaris"); case ELFOSABI_FREEBSD: return strdup("freebsd"); case ELFOSABI_HPUX: return strdup("hpux"); } /* Hack to identify OS */ if (needle (bin, "openbsd")) return strdup ("openbsd"); if (needle (bin, "netbsd")) return strdup ("netbsd"); if (needle (bin, "freebsd")) return strdup ("freebsd"); if (noodle (bin, "BEOS:APP_VERSION")) return strdup ("beos"); if (needle (bin, "GNU")) return strdup ("linux"); return strdup ("linux"); } ut8 *Elf_(r_bin_elf_grab_regstate)(ELFOBJ *bin, int *len) { if (bin->phdr) { int i; int num = bin->ehdr.e_phnum; for (i = 0; i < num; i++) { if (bin->phdr[i].p_type != PT_NOTE) { continue; } int bits = Elf_(r_bin_elf_get_bits)(bin); int regdelta = (bits == 64)? 0x84: 0x40; // x64 vs x32 int regsize = 160; // for x86-64 ut8 *buf = malloc (regsize); if (r_buf_read_at (bin->b, bin->phdr[i].p_offset + regdelta, buf, regsize) != regsize) { free (buf); bprintf ("Cannot read register state from CORE file\n"); return NULL; } if (len) { *len = regsize; } return buf; } } bprintf ("Cannot find NOTE section\n"); return NULL; } int Elf_(r_bin_elf_is_big_endian)(ELFOBJ *bin) { return (bin->ehdr.e_ident[EI_DATA] == ELFDATA2MSB); } /* XXX Init dt_strtab? */ char *Elf_(r_bin_elf_get_rpath)(ELFOBJ *bin) { char *ret = NULL; int j; if (!bin || !bin->phdr || !bin->dyn_buf || !bin->strtab) { return NULL; } for (j = 0; j< bin->dyn_entries; j++) { if (bin->dyn_buf[j].d_tag == DT_RPATH || bin->dyn_buf[j].d_tag == DT_RUNPATH) { if (!(ret = calloc (1, ELF_STRING_LENGTH))) { perror ("malloc (rpath)"); return NULL; } if (bin->dyn_buf[j].d_un.d_val > bin->strtab_size) { free (ret); return NULL; } strncpy (ret, bin->strtab + bin->dyn_buf[j].d_un.d_val, ELF_STRING_LENGTH); ret[ELF_STRING_LENGTH - 1] = '\0'; break; } } return ret; } static size_t get_relocs_num(ELFOBJ *bin) { size_t i, size, ret = 0; /* we need to be careful here, in malformed files the section size might * not be a multiple of a Rel/Rela size; round up so we allocate enough * space. */ #define NUMENTRIES_ROUNDUP(sectionsize, entrysize) (((sectionsize)+(entrysize)-1)/(entrysize)) if (!bin->g_sections) { return 0; } size = bin->is_rela == DT_REL ? sizeof (Elf_(Rel)) : sizeof (Elf_(Rela)); for (i = 0; !bin->g_sections[i].last; i++) { if (!strncmp (bin->g_sections[i].name, ".rela.", strlen (".rela."))) { if (!bin->is_rela) { size = sizeof (Elf_(Rela)); } ret += NUMENTRIES_ROUNDUP (bin->g_sections[i].size, size); } else if (!strncmp (bin->g_sections[i].name, ".rel.", strlen (".rel."))){ if (!bin->is_rela) { size = sizeof (Elf_(Rel)); } ret += NUMENTRIES_ROUNDUP (bin->g_sections[i].size, size); } } return ret; #undef NUMENTRIES_ROUNDUP } static int read_reloc(ELFOBJ *bin, RBinElfReloc *r, int is_rela, ut64 offset) { ut8 *buf = bin->b->buf; int j = 0; if (offset + sizeof (Elf_ (Rela)) > bin->size || offset + sizeof (Elf_(Rela)) < offset) { return -1; } if (is_rela == DT_RELA) { Elf_(Rela) rela; #if R_BIN_ELF64 rela.r_offset = READ64 (buf + offset, j) rela.r_info = READ64 (buf + offset, j) rela.r_addend = READ64 (buf + offset, j) #else rela.r_offset = READ32 (buf + offset, j) rela.r_info = READ32 (buf + offset, j) rela.r_addend = READ32 (buf + offset, j) #endif r->is_rela = is_rela; r->offset = rela.r_offset; r->type = ELF_R_TYPE (rela.r_info); r->sym = ELF_R_SYM (rela.r_info); r->last = 0; r->addend = rela.r_addend; return sizeof (Elf_(Rela)); } else { Elf_(Rel) rel; #if R_BIN_ELF64 rel.r_offset = READ64 (buf + offset, j) rel.r_info = READ64 (buf + offset, j) #else rel.r_offset = READ32 (buf + offset, j) rel.r_info = READ32 (buf + offset, j) #endif r->is_rela = is_rela; r->offset = rel.r_offset; r->type = ELF_R_TYPE (rel.r_info); r->sym = ELF_R_SYM (rel.r_info); r->last = 0; return sizeof (Elf_(Rel)); } } RBinElfReloc* Elf_(r_bin_elf_get_relocs)(ELFOBJ *bin) { int res, rel, rela, i, j; size_t reloc_num = 0; RBinElfReloc *ret = NULL; if (!bin || !bin->g_sections) { return NULL; } reloc_num = get_relocs_num (bin); if (!reloc_num) { return NULL; } bin->reloc_num = reloc_num; ret = (RBinElfReloc*)calloc ((size_t)reloc_num + 1, sizeof(RBinElfReloc)); if (!ret) { return NULL; } #if DEAD_CODE ut64 section_text_offset = Elf_(r_bin_elf_get_section_offset) (bin, ".text"); if (section_text_offset == -1) { section_text_offset = 0; } #endif for (i = 0, rel = 0; !bin->g_sections[i].last && rel < reloc_num ; i++) { bool is_rela = 0 == strncmp (bin->g_sections[i].name, ".rela.", strlen (".rela.")); bool is_rel = 0 == strncmp (bin->g_sections[i].name, ".rel.", strlen (".rel.")); if (!is_rela && !is_rel) { continue; } for (j = 0; j < bin->g_sections[i].size; j += res) { if (bin->g_sections[i].size > bin->size) { break; } if (bin->g_sections[i].offset > bin->size) { break; } if (rel >= reloc_num) { bprintf ("Internal error: ELF relocation buffer too small," "please file a bug report."); break; } if (!bin->is_rela) { rela = is_rela? DT_RELA : DT_REL; } else { rela = bin->is_rela; } res = read_reloc (bin, &ret[rel], rela, bin->g_sections[i].offset + j); if (j + res > bin->g_sections[i].size) { bprintf ("Warning: malformed file, relocation entry #%u is partially beyond the end of section %u.\n", rel, i); } if (bin->ehdr.e_type == ET_REL) { if (bin->g_sections[i].info < bin->ehdr.e_shnum && bin->shdr) { ret[rel].rva = bin->shdr[bin->g_sections[i].info].sh_offset + ret[rel].offset; ret[rel].rva = Elf_(r_bin_elf_p2v) (bin, ret[rel].rva); } else { ret[rel].rva = ret[rel].offset; } } else { ret[rel].rva = ret[rel].offset; ret[rel].offset = Elf_(r_bin_elf_v2p) (bin, ret[rel].offset); } ret[rel].last = 0; if (res < 0) { break; } rel++; } } ret[reloc_num].last = 1; return ret; } RBinElfLib* Elf_(r_bin_elf_get_libs)(ELFOBJ *bin) { RBinElfLib *ret = NULL; int j, k; if (!bin || !bin->phdr || !bin->dyn_buf || !bin->strtab || *(bin->strtab+1) == '0') { return NULL; } for (j = 0, k = 0; j < bin->dyn_entries; j++) if (bin->dyn_buf[j].d_tag == DT_NEEDED) { RBinElfLib *r = realloc (ret, (k + 1) * sizeof (RBinElfLib)); if (!r) { perror ("realloc (libs)"); free (ret); return NULL; } ret = r; if (bin->dyn_buf[j].d_un.d_val > bin->strtab_size) { free (ret); return NULL; } strncpy (ret[k].name, bin->strtab + bin->dyn_buf[j].d_un.d_val, ELF_STRING_LENGTH); ret[k].name[ELF_STRING_LENGTH - 1] = '\0'; ret[k].last = 0; if (ret[k].name[0]) { k++; } } RBinElfLib *r = realloc (ret, (k + 1) * sizeof (RBinElfLib)); if (!r) { perror ("realloc (libs)"); free (ret); return NULL; } ret = r; ret[k].last = 1; return ret; } static RBinElfSection* get_sections_from_phdr(ELFOBJ *bin) { RBinElfSection *ret; int i, num_sections = 0; ut64 reldyn = 0, relava = 0, pltgotva = 0, relva = 0; ut64 reldynsz = 0, relasz = 0, pltgotsz = 0; if (!bin || !bin->phdr || !bin->ehdr.e_phnum) return NULL; for (i = 0; i < bin->dyn_entries; i++) { switch (bin->dyn_buf[i].d_tag) { case DT_REL: reldyn = bin->dyn_buf[i].d_un.d_ptr; num_sections++; break; case DT_RELA: relva = bin->dyn_buf[i].d_un.d_ptr; num_sections++; break; case DT_RELSZ: reldynsz = bin->dyn_buf[i].d_un.d_val; break; case DT_RELASZ: relasz = bin->dyn_buf[i].d_un.d_val; break; case DT_PLTGOT: pltgotva = bin->dyn_buf[i].d_un.d_ptr; num_sections++; break; case DT_PLTRELSZ: pltgotsz = bin->dyn_buf[i].d_un.d_val; break; case DT_JMPREL: relava = bin->dyn_buf[i].d_un.d_ptr; num_sections++; break; default: break; } } ret = calloc (num_sections + 1, sizeof(RBinElfSection)); if (!ret) { return NULL; } i = 0; if (reldyn) { ret[i].offset = Elf_(r_bin_elf_v2p) (bin, reldyn); ret[i].rva = reldyn; ret[i].size = reldynsz; strcpy (ret[i].name, ".rel.dyn"); ret[i].last = 0; i++; } if (relava) { ret[i].offset = Elf_(r_bin_elf_v2p) (bin, relava); ret[i].rva = relava; ret[i].size = pltgotsz; strcpy (ret[i].name, ".rela.plt"); ret[i].last = 0; i++; } if (relva) { ret[i].offset = Elf_(r_bin_elf_v2p) (bin, relva); ret[i].rva = relva; ret[i].size = relasz; strcpy (ret[i].name, ".rel.plt"); ret[i].last = 0; i++; } if (pltgotva) { ret[i].offset = Elf_(r_bin_elf_v2p) (bin, pltgotva); ret[i].rva = pltgotva; ret[i].size = pltgotsz; strcpy (ret[i].name, ".got.plt"); ret[i].last = 0; i++; } ret[i].last = 1; return ret; } RBinElfSection* Elf_(r_bin_elf_get_sections)(ELFOBJ *bin) { RBinElfSection *ret = NULL; char unknown_s[20], invalid_s[20]; int i, nidx, unknown_c=0, invalid_c=0; if (!bin) { return NULL; } if (bin->g_sections) { return bin->g_sections; } if (!bin->shdr) { //we don't give up search in phdr section return get_sections_from_phdr (bin); } if (!(ret = calloc ((bin->ehdr.e_shnum + 1), sizeof (RBinElfSection)))) { return NULL; } for (i = 0; i < bin->ehdr.e_shnum; i++) { ret[i].offset = bin->shdr[i].sh_offset; ret[i].size = bin->shdr[i].sh_size; ret[i].align = bin->shdr[i].sh_addralign; ret[i].flags = bin->shdr[i].sh_flags; ret[i].link = bin->shdr[i].sh_link; ret[i].info = bin->shdr[i].sh_info; ret[i].type = bin->shdr[i].sh_type; if (bin->ehdr.e_type == ET_REL) { ret[i].rva = bin->baddr + bin->shdr[i].sh_offset; } else { ret[i].rva = bin->shdr[i].sh_addr; } nidx = bin->shdr[i].sh_name; #define SHNAME (int)bin->shdr[i].sh_name #define SHNLEN ELF_STRING_LENGTH - 4 #define SHSIZE (int)bin->shstrtab_size if (nidx < 0 || !bin->shstrtab_section || !bin->shstrtab_size || nidx > bin->shstrtab_size) { snprintf (invalid_s, sizeof (invalid_s) - 4, "invalid%d", invalid_c); strncpy (ret[i].name, invalid_s, SHNLEN); invalid_c++; } else { if (bin->shstrtab && (SHNAME > 0) && (SHNAME < SHSIZE)) { strncpy (ret[i].name, &bin->shstrtab[SHNAME], SHNLEN); } else { if (bin->shdr[i].sh_type == SHT_NULL) { //to follow the same behaviour as readelf strncpy (ret[i].name, "", sizeof (ret[i].name) - 4); } else { snprintf (unknown_s, sizeof (unknown_s)-4, "unknown%d", unknown_c); strncpy (ret[i].name, unknown_s, sizeof (ret[i].name)-4); unknown_c++; } } } ret[i].name[ELF_STRING_LENGTH-2] = '\0'; ret[i].last = 0; } ret[i].last = 1; return ret; } static void fill_symbol_bind_and_type (struct r_bin_elf_symbol_t *ret, Elf_(Sym) *sym) { #define s_bind(x) ret->bind = x #define s_type(x) ret->type = x switch (ELF_ST_BIND(sym->st_info)) { case STB_LOCAL: s_bind ("LOCAL"); break; case STB_GLOBAL: s_bind ("GLOBAL"); break; case STB_WEAK: s_bind ("WEAK"); break; case STB_NUM: s_bind ("NUM"); break; case STB_LOOS: s_bind ("LOOS"); break; case STB_HIOS: s_bind ("HIOS"); break; case STB_LOPROC: s_bind ("LOPROC"); break; case STB_HIPROC: s_bind ("HIPROC"); break; default: s_bind ("UNKNOWN"); } switch (ELF_ST_TYPE (sym->st_info)) { case STT_NOTYPE: s_type ("NOTYPE"); break; case STT_OBJECT: s_type ("OBJECT"); break; case STT_FUNC: s_type ("FUNC"); break; case STT_SECTION: s_type ("SECTION"); break; case STT_FILE: s_type ("FILE"); break; case STT_COMMON: s_type ("COMMON"); break; case STT_TLS: s_type ("TLS"); break; case STT_NUM: s_type ("NUM"); break; case STT_LOOS: s_type ("LOOS"); break; case STT_HIOS: s_type ("HIOS"); break; case STT_LOPROC: s_type ("LOPROC"); break; case STT_HIPROC: s_type ("HIPROC"); break; default: s_type ("UNKNOWN"); } } static RBinElfSymbol* get_symbols_from_phdr(ELFOBJ *bin, int type) { Elf_(Sym) *sym = NULL; Elf_(Addr) addr_sym_table = 0; ut8 s[sizeof (Elf_(Sym))] = {0}; RBinElfSymbol *ret = NULL; int i, j, r, tsize, nsym, ret_ctr; ut64 toffset = 0, tmp_offset; ut32 size, sym_size = 0; if (!bin || !bin->phdr || !bin->ehdr.e_phnum) { return NULL; } for (j = 0; j < bin->dyn_entries; j++) { switch (bin->dyn_buf[j].d_tag) { case (DT_SYMTAB): addr_sym_table = Elf_(r_bin_elf_v2p) (bin, bin->dyn_buf[j].d_un.d_ptr); break; case (DT_SYMENT): sym_size = bin->dyn_buf[j].d_un.d_val; break; default: break; } } if (!addr_sym_table) { return NULL; } if (!sym_size) { return NULL; } //since ELF doesn't specify the symbol table size we may read until the end of the buffer nsym = (bin->size - addr_sym_table) / sym_size; if (!UT32_MUL (&size, nsym, sizeof (Elf_ (Sym)))) { goto beach; } if (size < 1) { goto beach; } if (addr_sym_table > bin->size || addr_sym_table + size > bin->size) { goto beach; } if (nsym < 1) { return NULL; } // we reserve room for 4096 and grow as needed. size_t capacity1 = 4096; size_t capacity2 = 4096; sym = (Elf_(Sym)*) calloc (capacity1, sym_size); ret = (RBinElfSymbol *) calloc (capacity2, sizeof (struct r_bin_elf_symbol_t)); if (!sym || !ret) { goto beach; } for (i = 1, ret_ctr = 0; i < nsym; i++) { if (i >= capacity1) { // maybe grow // You take what you want, but you eat what you take. Elf_(Sym)* temp_sym = (Elf_(Sym)*) realloc(sym, (capacity1 * GROWTH_FACTOR) * sym_size); if (!temp_sym) { goto beach; } sym = temp_sym; capacity1 *= GROWTH_FACTOR; } if (ret_ctr >= capacity2) { // maybe grow RBinElfSymbol *temp_ret = realloc (ret, capacity2 * GROWTH_FACTOR * sizeof (struct r_bin_elf_symbol_t)); if (!temp_ret) { goto beach; } ret = temp_ret; capacity2 *= GROWTH_FACTOR; } // read in one entry r = r_buf_read_at (bin->b, addr_sym_table + i * sizeof (Elf_ (Sym)), s, sizeof (Elf_ (Sym))); if (r < 1) { goto beach; } int j = 0; #if R_BIN_ELF64 sym[i].st_name = READ32 (s, j); sym[i].st_info = READ8 (s, j); sym[i].st_other = READ8 (s, j); sym[i].st_shndx = READ16 (s, j); sym[i].st_value = READ64 (s, j); sym[i].st_size = READ64 (s, j); #else sym[i].st_name = READ32 (s, j); sym[i].st_value = READ32 (s, j); sym[i].st_size = READ32 (s, j); sym[i].st_info = READ8 (s, j); sym[i].st_other = READ8 (s, j); sym[i].st_shndx = READ16 (s, j); #endif // zero symbol is always empty // Examine entry and maybe store if (type == R_BIN_ELF_IMPORTS && sym[i].st_shndx == STN_UNDEF) { if (sym[i].st_value) { toffset = sym[i].st_value; } else if ((toffset = get_import_addr (bin, i)) == -1){ toffset = 0; } tsize = 16; } else if (type == R_BIN_ELF_SYMBOLS && sym[i].st_shndx != STN_UNDEF && ELF_ST_TYPE (sym[i].st_info) != STT_SECTION && ELF_ST_TYPE (sym[i].st_info) != STT_FILE) { tsize = sym[i].st_size; toffset = (ut64) sym[i].st_value; } else { continue; } tmp_offset = Elf_(r_bin_elf_v2p) (bin, toffset); if (tmp_offset > bin->size) { goto done; } if (sym[i].st_name + 2 > bin->strtab_size) { // Since we are reading beyond the symbol table what's happening // is that some entry is trying to dereference the strtab beyond its capacity // is not a symbol so is the end goto done; } ret[ret_ctr].offset = tmp_offset; ret[ret_ctr].size = tsize; { int rest = ELF_STRING_LENGTH - 1; int st_name = sym[i].st_name; int maxsize = R_MIN (bin->size, bin->strtab_size); if (st_name < 0 || st_name >= maxsize) { ret[ret_ctr].name[0] = 0; } else { const int len = __strnlen (bin->strtab + st_name, rest); memcpy (ret[ret_ctr].name, &bin->strtab[st_name], len); } } ret[ret_ctr].ordinal = i; ret[ret_ctr].in_shdr = false; ret[ret_ctr].name[ELF_STRING_LENGTH - 2] = '\0'; fill_symbol_bind_and_type (&ret[ret_ctr], &sym[i]); ret[ret_ctr].last = 0; ret_ctr++; } done: ret[ret_ctr].last = 1; // Size everything down to only what is used { nsym = i > 0 ? i : 1; Elf_ (Sym) * temp_sym = (Elf_ (Sym)*) realloc (sym, (nsym * GROWTH_FACTOR) * sym_size); if (!temp_sym) { goto beach; } sym = temp_sym; } { ret_ctr = ret_ctr > 0 ? ret_ctr : 1; RBinElfSymbol *p = (RBinElfSymbol *) realloc (ret, (ret_ctr + 1) * sizeof (RBinElfSymbol)); if (!p) { goto beach; } ret = p; } if (type == R_BIN_ELF_IMPORTS && !bin->imports_by_ord_size) { bin->imports_by_ord_size = ret_ctr + 1; if (ret_ctr > 0) { bin->imports_by_ord = (RBinImport * *) calloc (ret_ctr + 1, sizeof (RBinImport*)); } else { bin->imports_by_ord = NULL; } } else if (type == R_BIN_ELF_SYMBOLS && !bin->symbols_by_ord_size && ret_ctr) { bin->symbols_by_ord_size = ret_ctr + 1; if (ret_ctr > 0) { bin->symbols_by_ord = (RBinSymbol * *) calloc (ret_ctr + 1, sizeof (RBinSymbol*)); }else { bin->symbols_by_ord = NULL; } } free (sym); return ret; beach: free (sym); free (ret); return NULL; } static RBinElfSymbol *Elf_(r_bin_elf_get_phdr_symbols)(ELFOBJ *bin) { if (!bin) { return NULL; } if (bin->phdr_symbols) { return bin->phdr_symbols; } bin->phdr_symbols = get_symbols_from_phdr (bin, R_BIN_ELF_SYMBOLS); return bin->phdr_symbols; } static RBinElfSymbol *Elf_(r_bin_elf_get_phdr_imports)(ELFOBJ *bin) { if (!bin) { return NULL; } if (bin->phdr_imports) { return bin->phdr_imports; } bin->phdr_imports = get_symbols_from_phdr (bin, R_BIN_ELF_IMPORTS); return bin->phdr_imports; } static int Elf_(fix_symbols)(ELFOBJ *bin, int nsym, int type, RBinElfSymbol **sym) { int count = 0; RBinElfSymbol *ret = *sym; RBinElfSymbol *phdr_symbols = (type == R_BIN_ELF_SYMBOLS) ? Elf_(r_bin_elf_get_phdr_symbols) (bin) : Elf_(r_bin_elf_get_phdr_imports) (bin); RBinElfSymbol *tmp, *p; if (phdr_symbols) { RBinElfSymbol *d = ret; while (!d->last) { /* find match in phdr */ p = phdr_symbols; while (!p->last) { if (p->offset && d->offset == p->offset) { p->in_shdr = true; if (*p->name && strcmp (d->name, p->name)) { strcpy (d->name, p->name); } } p++; } d++; } p = phdr_symbols; while (!p->last) { if (!p->in_shdr) { count++; } p++; } /*Take those symbols that are not present in the shdr but yes in phdr*/ /*This should only should happen with fucked up binaries*/ if (count > 0) { /*what happens if a shdr says it has only one symbol? we should look anyway into phdr*/ tmp = (RBinElfSymbol*)realloc (ret, (nsym + count + 1) * sizeof (RBinElfSymbol)); if (!tmp) { return -1; } ret = tmp; ret[nsym--].last = 0; p = phdr_symbols; while (!p->last) { if (!p->in_shdr) { memcpy (&ret[++nsym], p, sizeof (RBinElfSymbol)); } p++; } ret[nsym + 1].last = 1; } *sym = ret; return nsym + 1; } return nsym; } static RBinElfSymbol* Elf_(_r_bin_elf_get_symbols_imports)(ELFOBJ *bin, int type) { ut32 shdr_size; int tsize, nsym, ret_ctr = 0, i, j, r, k, newsize; ut64 toffset; ut32 size = 0; RBinElfSymbol *ret = NULL; Elf_(Shdr) *strtab_section = NULL; Elf_(Sym) *sym = NULL; ut8 s[sizeof (Elf_(Sym))] = { 0 }; char *strtab = NULL; if (!bin || !bin->shdr || !bin->ehdr.e_shnum || bin->ehdr.e_shnum == 0xffff) { return (type == R_BIN_ELF_SYMBOLS) ? Elf_(r_bin_elf_get_phdr_symbols) (bin) : Elf_(r_bin_elf_get_phdr_imports) (bin); } if (!UT32_MUL (&shdr_size, bin->ehdr.e_shnum, sizeof (Elf_(Shdr)))) { return false; } if (shdr_size + 8 > bin->size) { return false; } for (i = 0; i < bin->ehdr.e_shnum; i++) { if ((type == R_BIN_ELF_IMPORTS && bin->shdr[i].sh_type == (bin->ehdr.e_type == ET_REL ? SHT_SYMTAB : SHT_DYNSYM)) || (type == R_BIN_ELF_SYMBOLS && bin->shdr[i].sh_type == (Elf_(r_bin_elf_get_stripped) (bin) ? SHT_DYNSYM : SHT_SYMTAB))) { if (bin->shdr[i].sh_link < 1) { /* oops. fix out of range pointers */ continue; } // hack to avoid asan cry if ((bin->shdr[i].sh_link * sizeof(Elf_(Shdr))) >= shdr_size) { /* oops. fix out of range pointers */ continue; } strtab_section = &bin->shdr[bin->shdr[i].sh_link]; if (strtab_section->sh_size > ST32_MAX || strtab_section->sh_size+8 > bin->size) { bprintf ("size (syms strtab)"); free (ret); free (strtab); return NULL; } if (!strtab) { if (!(strtab = (char *)calloc (1, 8 + strtab_section->sh_size))) { bprintf ("malloc (syms strtab)"); goto beach; } if (strtab_section->sh_offset > bin->size || strtab_section->sh_offset + strtab_section->sh_size > bin->size) { goto beach; } if (r_buf_read_at (bin->b, strtab_section->sh_offset, (ut8*)strtab, strtab_section->sh_size) == -1) { bprintf ("Warning: read (syms strtab)\n"); goto beach; } } newsize = 1 + bin->shdr[i].sh_size; if (newsize < 0 || newsize > bin->size) { bprintf ("invalid shdr %d size\n", i); goto beach; } nsym = (int)(bin->shdr[i].sh_size / sizeof (Elf_(Sym))); if (nsym < 0) { goto beach; } if (!(sym = (Elf_(Sym) *)calloc (nsym, sizeof (Elf_(Sym))))) { bprintf ("calloc (syms)"); goto beach; } if (!UT32_MUL (&size, nsym, sizeof (Elf_(Sym)))) { goto beach; } if (size < 1 || size > bin->size) { goto beach; } if (bin->shdr[i].sh_offset > bin->size) { goto beach; } if (bin->shdr[i].sh_offset + size > bin->size) { goto beach; } for (j = 0; j < nsym; j++) { int k = 0; r = r_buf_read_at (bin->b, bin->shdr[i].sh_offset + j * sizeof (Elf_(Sym)), s, sizeof (Elf_(Sym))); if (r < 1) { bprintf ("Warning: read (sym)\n"); goto beach; } #if R_BIN_ELF64 sym[j].st_name = READ32 (s, k) sym[j].st_info = READ8 (s, k) sym[j].st_other = READ8 (s, k) sym[j].st_shndx = READ16 (s, k) sym[j].st_value = READ64 (s, k) sym[j].st_size = READ64 (s, k) #else sym[j].st_name = READ32 (s, k) sym[j].st_value = READ32 (s, k) sym[j].st_size = READ32 (s, k) sym[j].st_info = READ8 (s, k) sym[j].st_other = READ8 (s, k) sym[j].st_shndx = READ16 (s, k) #endif } free (ret); ret = calloc (nsym, sizeof (RBinElfSymbol)); if (!ret) { bprintf ("Cannot allocate %d symbols\n", nsym); goto beach; } for (k = 1, ret_ctr = 0; k < nsym; k++) { if (type == R_BIN_ELF_IMPORTS && sym[k].st_shndx == STN_UNDEF) { if (sym[k].st_value) { toffset = sym[k].st_value; } else if ((toffset = get_import_addr (bin, k)) == -1){ toffset = 0; } tsize = 16; } else if (type == R_BIN_ELF_SYMBOLS && sym[k].st_shndx != STN_UNDEF && ELF_ST_TYPE (sym[k].st_info) != STT_SECTION && ELF_ST_TYPE (sym[k].st_info) != STT_FILE) { //int idx = sym[k].st_shndx; tsize = sym[k].st_size; toffset = (ut64)sym[k].st_value; } else { continue; } if (bin->ehdr.e_type == ET_REL) { if (sym[k].st_shndx < bin->ehdr.e_shnum) ret[ret_ctr].offset = sym[k].st_value + bin->shdr[sym[k].st_shndx].sh_offset; } else { ret[ret_ctr].offset = Elf_(r_bin_elf_v2p) (bin, toffset); } ret[ret_ctr].size = tsize; if (sym[k].st_name + 2 > strtab_section->sh_size) { bprintf ("Warning: index out of strtab range\n"); goto beach; } { int rest = ELF_STRING_LENGTH - 1; int st_name = sym[k].st_name; int maxsize = R_MIN (bin->b->length, strtab_section->sh_size); if (st_name < 0 || st_name >= maxsize) { ret[ret_ctr].name[0] = 0; } else { const size_t len = __strnlen (strtab + sym[k].st_name, rest); memcpy (ret[ret_ctr].name, &strtab[sym[k].st_name], len); } } ret[ret_ctr].ordinal = k; ret[ret_ctr].name[ELF_STRING_LENGTH - 2] = '\0'; fill_symbol_bind_and_type (&ret[ret_ctr], &sym[k]); ret[ret_ctr].last = 0; ret_ctr++; } ret[ret_ctr].last = 1; // ugly dirty hack :D R_FREE (strtab); R_FREE (sym); } } if (!ret) { return (type == R_BIN_ELF_SYMBOLS) ? Elf_(r_bin_elf_get_phdr_symbols) (bin) : Elf_(r_bin_elf_get_phdr_imports) (bin); } int max = -1; RBinElfSymbol *aux = NULL; nsym = Elf_(fix_symbols) (bin, ret_ctr, type, &ret); if (nsym == -1) { goto beach; } aux = ret; while (!aux->last) { if ((int)aux->ordinal > max) { max = aux->ordinal; } aux++; } nsym = max; if (type == R_BIN_ELF_IMPORTS) { R_FREE (bin->imports_by_ord); bin->imports_by_ord_size = nsym + 1; bin->imports_by_ord = (RBinImport**)calloc (R_MAX (1, nsym + 1), sizeof (RBinImport*)); } else if (type == R_BIN_ELF_SYMBOLS) { R_FREE (bin->symbols_by_ord); bin->symbols_by_ord_size = nsym + 1; bin->symbols_by_ord = (RBinSymbol**)calloc (R_MAX (1, nsym + 1), sizeof (RBinSymbol*)); } return ret; beach: free (ret); free (sym); free (strtab); return NULL; } RBinElfSymbol *Elf_(r_bin_elf_get_symbols)(ELFOBJ *bin) { if (!bin->g_symbols) { bin->g_symbols = Elf_(_r_bin_elf_get_symbols_imports) (bin, R_BIN_ELF_SYMBOLS); } return bin->g_symbols; } RBinElfSymbol *Elf_(r_bin_elf_get_imports)(ELFOBJ *bin) { if (!bin->g_imports) { bin->g_imports = Elf_(_r_bin_elf_get_symbols_imports) (bin, R_BIN_ELF_IMPORTS); } return bin->g_imports; } RBinElfField* Elf_(r_bin_elf_get_fields)(ELFOBJ *bin) { RBinElfField *ret = NULL; int i = 0, j; if (!bin || !(ret = calloc ((bin->ehdr.e_phnum + 3 + 1), sizeof (RBinElfField)))) { return NULL; } strncpy (ret[i].name, "ehdr", ELF_STRING_LENGTH); ret[i].offset = 0; ret[i++].last = 0; strncpy (ret[i].name, "shoff", ELF_STRING_LENGTH); ret[i].offset = bin->ehdr.e_shoff; ret[i++].last = 0; strncpy (ret[i].name, "phoff", ELF_STRING_LENGTH); ret[i].offset = bin->ehdr.e_phoff; ret[i++].last = 0; for (j = 0; bin->phdr && j < bin->ehdr.e_phnum; i++, j++) { snprintf (ret[i].name, ELF_STRING_LENGTH, "phdr_%i", j); ret[i].offset = bin->phdr[j].p_offset; ret[i].last = 0; } ret[i].last = 1; return ret; } void* Elf_(r_bin_elf_free)(ELFOBJ* bin) { int i; if (!bin) { return NULL; } free (bin->phdr); free (bin->shdr); free (bin->strtab); free (bin->dyn_buf); free (bin->shstrtab); free (bin->dynstr); //free (bin->strtab_section); if (bin->imports_by_ord) { for (i = 0; i<bin->imports_by_ord_size; i++) { free (bin->imports_by_ord[i]); } free (bin->imports_by_ord); } if (bin->symbols_by_ord) { for (i = 0; i<bin->symbols_by_ord_size; i++) { free (bin->symbols_by_ord[i]); } free (bin->symbols_by_ord); } r_buf_free (bin->b); if (bin->g_symbols != bin->phdr_symbols) { R_FREE (bin->phdr_symbols); } if (bin->g_imports != bin->phdr_imports) { R_FREE (bin->phdr_imports); } R_FREE (bin->g_sections); R_FREE (bin->g_symbols); R_FREE (bin->g_imports); free (bin); return NULL; } ELFOBJ* Elf_(r_bin_elf_new)(const char* file, bool verbose) { ut8 *buf; int size; ELFOBJ *bin = R_NEW0 (ELFOBJ); if (!bin) { return NULL; } memset (bin, 0, sizeof (ELFOBJ)); bin->file = file; if (!(buf = (ut8*)r_file_slurp (file, &size))) { return Elf_(r_bin_elf_free) (bin); } bin->size = size; bin->verbose = verbose; bin->b = r_buf_new (); if (!r_buf_set_bytes (bin->b, buf, bin->size)) { free (buf); return Elf_(r_bin_elf_free) (bin); } if (!elf_init (bin)) { free (buf); return Elf_(r_bin_elf_free) (bin); } free (buf); return bin; } ELFOBJ* Elf_(r_bin_elf_new_buf)(RBuffer *buf, bool verbose) { ELFOBJ *bin = R_NEW0 (ELFOBJ); bin->kv = sdb_new0 (); bin->b = r_buf_new (); bin->size = (ut32)buf->length; bin->verbose = verbose; if (!r_buf_set_bytes (bin->b, buf->buf, buf->length)) { return Elf_(r_bin_elf_free) (bin); } if (!elf_init (bin)) { return Elf_(r_bin_elf_free) (bin); } return bin; } static int is_in_pphdr (Elf_(Phdr) *p, ut64 addr) { return addr >= p->p_offset && addr < p->p_offset + p->p_memsz; } static int is_in_vphdr (Elf_(Phdr) *p, ut64 addr) { return addr >= p->p_vaddr && addr < p->p_vaddr + p->p_memsz; } /* converts a physical address to the virtual address, looking * at the program headers in the binary bin */ ut64 Elf_(r_bin_elf_p2v) (ELFOBJ *bin, ut64 paddr) { int i; if (!bin) return 0; if (!bin->phdr) { if (bin->ehdr.e_type == ET_REL) { return bin->baddr + paddr; } return paddr; } for (i = 0; i < bin->ehdr.e_phnum; ++i) { Elf_(Phdr) *p = &bin->phdr[i]; if (!p) { break; } if (p->p_type == PT_LOAD && is_in_pphdr (p, paddr)) { if (!p->p_vaddr && !p->p_offset) { continue; } return p->p_vaddr + paddr - p->p_offset; } } return paddr; } /* converts a virtual address to the relative physical address, looking * at the program headers in the binary bin */ ut64 Elf_(r_bin_elf_v2p) (ELFOBJ *bin, ut64 vaddr) { int i; if (!bin) { return 0; } if (!bin->phdr) { if (bin->ehdr.e_type == ET_REL) { return vaddr - bin->baddr; } return vaddr; } for (i = 0; i < bin->ehdr.e_phnum; ++i) { Elf_(Phdr) *p = &bin->phdr[i]; if (!p) { break; } if (p->p_type == PT_LOAD && is_in_vphdr (p, vaddr)) { if (!p->p_offset && !p->p_vaddr) { continue; } return p->p_offset + vaddr - p->p_vaddr; } } return vaddr; }
./CrossVul/dataset_final_sorted/CWE-119/c/good_2899_0
crossvul-cpp_data_bad_5733_4
/* * Copyright (c) 2010 Nolan Lum <nol888@gmail.com> * Copyright (c) 2009 Loren Merritt <lorenm@u.washignton.edu> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * gradfun debanding filter, ported from MPlayer * libmpcodecs/vf_gradfun.c * * Apply a boxblur debanding algorithm (based on the gradfun2db * AviSynth filter by prunedtree). * Foreach pixel, if it's within threshold of the blurred value, make it closer. * So now we have a smoothed and higher bitdepth version of all the shallow * gradients, while leaving detailed areas untouched. * Dither it back to 8bit. */ #include "libavutil/imgutils.h" #include "libavutil/common.h" #include "libavutil/cpu.h" #include "libavutil/opt.h" #include "libavutil/pixdesc.h" #include "libavutil/opt.h" #include "avfilter.h" #include "formats.h" #include "gradfun.h" #include "internal.h" #include "video.h" DECLARE_ALIGNED(16, static const uint16_t, dither)[8][8] = { {0x00,0x60,0x18,0x78,0x06,0x66,0x1E,0x7E}, {0x40,0x20,0x58,0x38,0x46,0x26,0x5E,0x3E}, {0x10,0x70,0x08,0x68,0x16,0x76,0x0E,0x6E}, {0x50,0x30,0x48,0x28,0x56,0x36,0x4E,0x2E}, {0x04,0x64,0x1C,0x7C,0x02,0x62,0x1A,0x7A}, {0x44,0x24,0x5C,0x3C,0x42,0x22,0x5A,0x3A}, {0x14,0x74,0x0C,0x6C,0x12,0x72,0x0A,0x6A}, {0x54,0x34,0x4C,0x2C,0x52,0x32,0x4A,0x2A}, }; void ff_gradfun_filter_line_c(uint8_t *dst, const uint8_t *src, const uint16_t *dc, int width, int thresh, const uint16_t *dithers) { int x; for (x = 0; x < width; dc += x & 1, x++) { int pix = src[x] << 7; int delta = dc[0] - pix; int m = abs(delta) * thresh >> 16; m = FFMAX(0, 127 - m); m = m * m * delta >> 14; pix += m + dithers[x & 7]; dst[x] = av_clip_uint8(pix >> 7); } } void ff_gradfun_blur_line_c(uint16_t *dc, uint16_t *buf, const uint16_t *buf1, const uint8_t *src, int src_linesize, int width) { int x, v, old; for (x = 0; x < width; x++) { v = buf1[x] + src[2 * x] + src[2 * x + 1] + src[2 * x + src_linesize] + src[2 * x + 1 + src_linesize]; old = buf[x]; buf[x] = v; dc[x] = v - old; } } static void filter(GradFunContext *ctx, uint8_t *dst, const uint8_t *src, int width, int height, int dst_linesize, int src_linesize, int r) { int bstride = FFALIGN(width, 16) / 2; int y; uint32_t dc_factor = (1 << 21) / (r * r); uint16_t *dc = ctx->buf + 16; uint16_t *buf = ctx->buf + bstride + 32; int thresh = ctx->thresh; memset(dc, 0, (bstride + 16) * sizeof(*buf)); for (y = 0; y < r; y++) ctx->blur_line(dc, buf + y * bstride, buf + (y - 1) * bstride, src + 2 * y * src_linesize, src_linesize, width / 2); for (;;) { if (y < height - r) { int mod = ((y + r) / 2) % r; uint16_t *buf0 = buf + mod * bstride; uint16_t *buf1 = buf + (mod ? mod - 1 : r - 1) * bstride; int x, v; ctx->blur_line(dc, buf0, buf1, src + (y + r) * src_linesize, src_linesize, width / 2); for (x = v = 0; x < r; x++) v += dc[x]; for (; x < width / 2; x++) { v += dc[x] - dc[x-r]; dc[x-r] = v * dc_factor >> 16; } for (; x < (width + r + 1) / 2; x++) dc[x-r] = v * dc_factor >> 16; for (x = -r / 2; x < 0; x++) dc[x] = dc[0]; } if (y == r) { for (y = 0; y < r; y++) ctx->filter_line(dst + y * dst_linesize, src + y * src_linesize, dc - r / 2, width, thresh, dither[y & 7]); } ctx->filter_line(dst + y * dst_linesize, src + y * src_linesize, dc - r / 2, width, thresh, dither[y & 7]); if (++y >= height) break; ctx->filter_line(dst + y * dst_linesize, src + y * src_linesize, dc - r / 2, width, thresh, dither[y & 7]); if (++y >= height) break; } } static av_cold int init(AVFilterContext *ctx) { GradFunContext *s = ctx->priv; s->thresh = (1 << 15) / s->strength; s->radius = av_clip((s->radius + 1) & ~1, 4, 32); s->blur_line = ff_gradfun_blur_line_c; s->filter_line = ff_gradfun_filter_line_c; if (ARCH_X86) ff_gradfun_init_x86(s); av_log(ctx, AV_LOG_VERBOSE, "threshold:%.2f radius:%d\n", s->strength, s->radius); return 0; } static av_cold void uninit(AVFilterContext *ctx) { GradFunContext *s = ctx->priv; av_freep(&s->buf); } static int query_formats(AVFilterContext *ctx) { static const enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV420P, AV_PIX_FMT_GRAY8, AV_PIX_FMT_YUV444P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV411P, AV_PIX_FMT_YUV440P, AV_PIX_FMT_NONE }; ff_set_common_formats(ctx, ff_make_format_list(pix_fmts)); return 0; } static int config_input(AVFilterLink *inlink) { GradFunContext *s = inlink->dst->priv; const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format); int hsub = desc->log2_chroma_w; int vsub = desc->log2_chroma_h; av_freep(&s->buf); s->buf = av_mallocz((FFALIGN(inlink->w, 16) * (s->radius + 1) / 2 + 32) * sizeof(uint16_t)); if (!s->buf) return AVERROR(ENOMEM); s->chroma_w = FF_CEIL_RSHIFT(inlink->w, hsub); s->chroma_h = FF_CEIL_RSHIFT(inlink->h, vsub); s->chroma_r = av_clip(((((s->radius >> hsub) + (s->radius >> vsub)) / 2 ) + 1) & ~1, 4, 32); return 0; } static int filter_frame(AVFilterLink *inlink, AVFrame *in) { GradFunContext *s = inlink->dst->priv; AVFilterLink *outlink = inlink->dst->outputs[0]; AVFrame *out; int p, direct; if (av_frame_is_writable(in)) { direct = 1; out = in; } else { direct = 0; out = ff_get_video_buffer(outlink, outlink->w, outlink->h); if (!out) { av_frame_free(&in); return AVERROR(ENOMEM); } av_frame_copy_props(out, in); } for (p = 0; p < 4 && in->data[p]; p++) { int w = inlink->w; int h = inlink->h; int r = s->radius; if (p) { w = s->chroma_w; h = s->chroma_h; r = s->chroma_r; } if (FFMIN(w, h) > 2 * r) filter(s, out->data[p], in->data[p], w, h, out->linesize[p], in->linesize[p], r); else if (out->data[p] != in->data[p]) av_image_copy_plane(out->data[p], out->linesize[p], in->data[p], in->linesize[p], w, h); } if (!direct) av_frame_free(&in); return ff_filter_frame(outlink, out); } #define OFFSET(x) offsetof(GradFunContext, x) #define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM static const AVOption gradfun_options[] = { { "strength", "The maximum amount by which the filter will change any one pixel.", OFFSET(strength), AV_OPT_TYPE_FLOAT, { .dbl = 1.2 }, 0.51, 64, FLAGS }, { "radius", "The neighborhood to fit the gradient to.", OFFSET(radius), AV_OPT_TYPE_INT, { .i64 = 16 }, 4, 32, FLAGS }, { NULL }, }; AVFILTER_DEFINE_CLASS(gradfun); static const AVFilterPad avfilter_vf_gradfun_inputs[] = { { .name = "default", .type = AVMEDIA_TYPE_VIDEO, .config_props = config_input, .filter_frame = filter_frame, }, { NULL } }; static const AVFilterPad avfilter_vf_gradfun_outputs[] = { { .name = "default", .type = AVMEDIA_TYPE_VIDEO, }, { NULL } }; AVFilter avfilter_vf_gradfun = { .name = "gradfun", .description = NULL_IF_CONFIG_SMALL("Debands video quickly using gradients."), .priv_size = sizeof(GradFunContext), .priv_class = &gradfun_class, .init = init, .uninit = uninit, .query_formats = query_formats, .inputs = avfilter_vf_gradfun_inputs, .outputs = avfilter_vf_gradfun_outputs, .flags = AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC, };
./CrossVul/dataset_final_sorted/CWE-119/c/bad_5733_4
crossvul-cpp_data_good_634_5
/************************************************** * isql * ************************************************** * This code was created by Peter Harvey @ CodeByDesign. * Released under GPL 18.FEB.99 * * Contributions from... * ----------------------------------------------- * Peter Harvey - pharvey@codebydesign.com **************************************************/ #include <config.h> #define UNICODE #include "isql.h" #include "ini.h" #include "sqlucode.h" #ifdef HAVE_READLINE #include <readline/readline.h> #include <readline/history.h> #endif #ifdef HAVE_SETLOCALE #ifdef HAVE_LOCALE_H #include <locale.h> #endif #endif static int OpenDatabase( SQLHENV *phEnv, SQLHDBC *phDbc, char *szDSN, char *szUID, char *szPWD ); static int CloseDatabase( SQLHENV hEnv, SQLHDBC hDbc ); static int ExecuteSQL( SQLHDBC hDbc, char *szSQL, char cDelimiter, int bColumnNames, int bHTMLTable ); static int ExecuteHelp( SQLHDBC hDbc, char *szSQL, char cDelimiter, int bColumnNames, int bHTMLTable ); static void WriteHeaderHTMLTable( SQLHSTMT hStmt ); static void WriteHeaderNormal( SQLHSTMT hStmt, SQLCHAR *szSepLine ); static void WriteHeaderDelimited( SQLHSTMT hStmt, char cDelimiter ); static void WriteBodyHTMLTable( SQLHSTMT hStmt ); static SQLLEN WriteBodyNormal( SQLHSTMT hStmt ); static void WriteBodyDelimited( SQLHSTMT hStmt, char cDelimiter ); static void WriteFooterHTMLTable( SQLHSTMT hStmt ); static void WriteFooterNormal( SQLHSTMT hStmt, SQLCHAR *szSepLine, SQLLEN nRows ); static int DumpODBCLog( SQLHENV hEnv, SQLHDBC hDbc, SQLHSTMT hStmt ); static int get_args(char *string, char **args, int maxarg); static void free_args(char **args, int maxarg); static void output_help(void); int bVerbose = 0; SQLHENV hEnv = 0; SQLHDBC hDbc = 0; int buseED = 0; void UWriteHeaderNormal( SQLHSTMT hStmt, SQLTCHAR *szSepLine ); void UWriteFooterNormal( SQLHSTMT hStmt, SQLTCHAR *szSepLine, SQLLEN nRows ); static char * uc_to_ascii( SQLWCHAR *uc ) { char *ascii = (char *)uc; int i; for ( i = 0; uc[ i ]; i ++ ) { ascii[ i ] = uc[ i ] & 0x00ff; } ascii[ i ] = 0; return ascii; } static void ansi_to_unicode( char *szSQL, SQLWCHAR *szUcSQL ) { int i; for ( i = 0; szSQL[ i ]; i ++ ) { szUcSQL[ i ] = szSQL[ i ]; } szUcSQL[ i ] = 0; } int main( int argc, char *argv[] ) { int nArg, count; int bHTMLTable = 0; int bBatch = 0; int cDelimiter = 0; int bColumnNames = 0; char *szDSN; char *szUID; char *szPWD; char *szSQL; char *pEscapeChar; int buffer_size = 9000; szDSN = NULL; szUID = NULL; szPWD = NULL; if ( argc < 2 ) { fputs( szSyntax, stderr ); exit( 1 ); } #ifdef HAVE_SETLOCALE /* * Default locale */ setlocale( LC_ALL, "" ); #endif /**************************** * PARSE ARGS ***************************/ for ( nArg = 1, count = 1 ; nArg < argc; nArg++ ) { if ( argv[nArg][0] == '-' ) { /* Options */ switch ( argv[nArg][1] ) { case 'd': cDelimiter = argv[nArg][2]; break; case 's': buffer_size = atoi( &(argv[nArg][2]) ); break; case 'w': bHTMLTable = 1; break; case 'b': bBatch = 1; break; case 'c': bColumnNames = 1; break; case 'v': bVerbose = 1; break; case 'e': buseED = 1; break; case '-': printf( "unixODBC " VERSION "\n" ); exit(0); #ifdef HAVE_STRTOL case 'x': cDelimiter = strtol( argv[nArg]+2, NULL, 0 ); break; #endif #ifdef HAVE_SETLOCALE case 'l': if ( !setlocale( LC_ALL, argv[nArg]+2 )) { fprintf( stderr, "isql: can't set locale to '%s'\n", argv[nArg]+2 ); exit ( -1 ); } break; #endif default: fputs( szSyntax, stderr ); exit( 1 ); } continue; } else if ( count == 1 ) szDSN = argv[nArg]; else if ( count == 2 ) szUID = argv[nArg]; else if ( count == 3 ) szPWD = argv[nArg]; count++; } szSQL = calloc( 1, buffer_size + 1 ); /**************************** * CONNECT ***************************/ if ( !OpenDatabase( &hEnv, &hDbc, szDSN, szUID, szPWD ) ) exit( 1 ); /**************************** * EXECUTE ***************************/ if ( !bBatch ) { printf( "+---------------------------------------+\n" ); printf( "| Connected! |\n" ); printf( "| |\n" ); printf( "| sql-statement |\n" ); printf( "| help [tablename] |\n" ); printf( "| quit |\n" ); printf( "| |\n" ); printf( "+---------------------------------------+\n" ); } do { if ( !bBatch ) #ifndef HAVE_READLINE printf( "SQL> " ); #else { char *line; int malloced; line=readline("SQL> "); if ( !line ) /* EOF - ctrl D */ { malloced = 1; line = strdup( "quit" ); } else { malloced = 0; } strncpy(szSQL, line, buffer_size ); add_history(line); if ( malloced ) { free(line); } } else #endif { char *line; int malloced; line = fgets( szSQL, buffer_size, stdin ); if ( !line ) /* EOF - ctrl D */ { malloced = 1; line = strdup( "quit" ); } else { malloced = 0; } strncpy(szSQL, line, buffer_size ); if ( malloced ) { free(line); } } /* strip away escape chars */ while ( (pEscapeChar=(char*)strchr(szSQL, '\n')) != NULL || (pEscapeChar=(char*)strchr(szSQL, '\r')) != NULL ) *pEscapeChar = ' '; if ( szSQL[1] != '\0' ) { if ( strncmp( szSQL, "quit", 4 ) == 0 ) szSQL[1] = '\0'; else if ( strncmp( szSQL, "help", 4 ) == 0 ) ExecuteHelp( hDbc, szSQL, cDelimiter, bColumnNames, bHTMLTable ); else if (memcmp(szSQL, "--", 2) != 0) ExecuteSQL( hDbc, szSQL, cDelimiter, bColumnNames, bHTMLTable ); } } while ( szSQL[1] != '\0' ); /**************************** * DISCONNECT ***************************/ CloseDatabase( hEnv, hDbc ); exit( 0 ); } /**************************** * OpenDatabase - do everything we have to do to get a viable connection to szDSN ***************************/ static int OpenDatabase( SQLHENV *phEnv, SQLHDBC *phDbc, char *szDSN, char *szUID, char *szPWD ) { SQLCHAR dsn[ 1024 ], uid[ 1024 ], pwd[ 1024 ]; SQLTCHAR cstr[ 1024 ]; char zcstr[ 1024 ], tmp[ 1024 ]; int i; size_t zclen; if ( SQLAllocEnv( phEnv ) != SQL_SUCCESS ) { fprintf( stderr, "[ISQL]ERROR: Could not SQLAllocEnv\n" ); return 0; } if ( SQLAllocConnect( *phEnv, phDbc ) != SQL_SUCCESS ) { if ( bVerbose ) DumpODBCLog( hEnv, 0, 0 ); fprintf( stderr, "[ISQL]ERROR: Could not SQLAllocConnect\n" ); SQLFreeEnv( *phEnv ); return 0; } if ( szDSN ) { size_t DSNlen=strlen( szDSN ); for ( i = 0; i < DSNlen; i ++ ) { dsn[ i ] = szDSN[ i ]; } dsn[ i ] = '\0'; } else { dsn[ 0 ] = '\0'; } if ( szUID ) { size_t UIDlen=strlen( szUID ); for ( i = 0; i < UIDlen; i ++ ) { uid[ i ] = szUID[ i ]; } uid[ i ] = '\0'; } else { uid[ 0 ] = '\0'; } if ( szPWD ) { size_t PWDlen=strlen( szPWD ); for ( i = 0; i < PWDlen; i ++ ) { pwd[ i ] = szPWD[ i ]; } pwd[ i ] = '\0'; } else { pwd[ 0 ] = '\0'; } sprintf( zcstr, "DSN=%s", dsn ); if ( szUID ) { sprintf( tmp, ";UID=%s", uid ); strcat( zcstr, tmp ); } if ( szPWD ) { sprintf( tmp, ";PWD=%s", pwd ); strcat( zcstr, tmp ); } zclen=strlen( zcstr ); for ( i = 0; i < zclen; i ++ ) { cstr[ i ] = zcstr[ i ]; } cstr[ i ] = 0; if ( !SQL_SUCCEEDED( SQLDriverConnect( *phDbc, NULL, cstr, SQL_NTS, NULL, 0, NULL, SQL_DRIVER_NOPROMPT ))) { if ( bVerbose ) DumpODBCLog( hEnv, hDbc, 0 ); fprintf( stderr, "[ISQL]ERROR: Could not SQLDriverConnect\n" ); SQLFreeConnect( *phDbc ); SQLFreeEnv( *phEnv ); return 0; } if ( bVerbose ) DumpODBCLog( hEnv, hDbc, 0 ); return 1; } /**************************** * ExecuteSQL - create a statement, execute the SQL, and get rid of the statement * - show results as per request; bHTMLTable has precedence over other options ***************************/ static int ExecuteSQL( SQLHDBC hDbc, char *szSQL, char cDelimiter, int bColumnNames, int bHTMLTable ) { SQLHSTMT hStmt; SQLTCHAR szSepLine[32001]; SQLTCHAR szUcSQL[32001]; SQLSMALLINT cols; SQLINTEGER ret; SQLLEN nRows = 0; szSepLine[ 0 ] = 0; ansi_to_unicode( szSQL, szUcSQL ); /**************************** * EXECUTE SQL ***************************/ if ( SQLAllocStmt( hDbc, &hStmt ) != SQL_SUCCESS ) { if ( bVerbose ) DumpODBCLog( hEnv, hDbc, 0 ); fprintf( stderr, "[ISQL]ERROR: Could not SQLAllocStmt\n" ); return 0; } if ( buseED ) { ret = SQLExecDirect( hStmt, szUcSQL, SQL_NTS ); if ( ret == SQL_NO_DATA ) { fprintf( stderr, "[ISQL]INFO: SQLExecDirect returned SQL_NO_DATA\n" ); } else if ( ret == SQL_SUCCESS_WITH_INFO ) { if ( bVerbose ) DumpODBCLog( hEnv, hDbc, hStmt ); fprintf( stderr, "[ISQL]INFO: SQLExecDirect returned SQL_SUCCESS_WITH_INFO\n" ); } else if ( ret != SQL_SUCCESS ) { if ( bVerbose ) DumpODBCLog( hEnv, hDbc, hStmt ); fprintf( stderr, "[ISQL]ERROR: Could not SQLExecDirect\n" ); SQLFreeStmt( hStmt, SQL_DROP ); return 0; } } else { if ( SQLPrepare( hStmt, szUcSQL, SQL_NTS ) != SQL_SUCCESS ) { if ( bVerbose ) DumpODBCLog( hEnv, hDbc, hStmt ); fprintf( stderr, "[ISQL]ERROR: Could not SQLPrepare\n" ); SQLFreeStmt( hStmt, SQL_DROP ); return 0; } ret = SQLExecute( hStmt ); if ( ret == SQL_NO_DATA ) { fprintf( stderr, "[ISQL]INFO: SQLExecute returned SQL_NO_DATA\n" ); } else if ( ret == SQL_SUCCESS_WITH_INFO ) { if ( bVerbose ) DumpODBCLog( hEnv, hDbc, hStmt ); fprintf( stderr, "[ISQL]INFO: SQLExecute returned SQL_SUCCESS_WITH_INFO\n" ); } else if ( ret != SQL_SUCCESS ) { if ( bVerbose ) DumpODBCLog( hEnv, hDbc, hStmt ); fprintf( stderr, "[ISQL]ERROR: Could not SQLExecute\n" ); SQLFreeStmt( hStmt, SQL_DROP ); return 0; } } do { /* * check to see if it has generated a result set */ if ( SQLNumResultCols( hStmt, &cols ) != SQL_SUCCESS ) { if ( bVerbose ) DumpODBCLog( hEnv, hDbc, hStmt ); fprintf( stderr, "[ISQL]ERROR: Could not SQLNumResultCols\n" ); SQLFreeStmt( hStmt, SQL_DROP ); return 0; } if ( cols > 0 ) { /**************************** * WRITE HEADER ***************************/ if ( bHTMLTable ) WriteHeaderHTMLTable( hStmt ); else if ( cDelimiter == 0 ) UWriteHeaderNormal( hStmt, szSepLine ); else if ( cDelimiter && bColumnNames ) WriteHeaderDelimited( hStmt, cDelimiter ); /**************************** * WRITE BODY ***************************/ if ( bHTMLTable ) WriteBodyHTMLTable( hStmt ); else if ( cDelimiter == 0 ) nRows = WriteBodyNormal( hStmt ); else WriteBodyDelimited( hStmt, cDelimiter ); } /**************************** * WRITE FOOTER ***************************/ if ( bHTMLTable ) WriteFooterHTMLTable( hStmt ); else if ( cDelimiter == 0 ) UWriteFooterNormal( hStmt, szSepLine, nRows ); } while ( SQL_SUCCEEDED( SQLMoreResults( hStmt ))); /**************************** * CLEANUP ***************************/ SQLFreeStmt( hStmt, SQL_DROP ); return 1; } /**************************** * ExecuteHelp - create a statement, execute the SQL, and get rid of the statement * - show results as per request; bHTMLTable has precedence over other options ***************************/ static int ExecuteHelp( SQLHDBC hDbc, char *szSQL, char cDelimiter, int bColumnNames, int bHTMLTable ) { char szTable[250] = ""; SQLHSTMT hStmt; SQLTCHAR szSepLine[32001]; SQLLEN nRows = 0; szSepLine[ 0 ] = 0; /**************************** * EXECUTE SQL ***************************/ if ( SQLAllocStmt( hDbc, &hStmt ) != SQL_SUCCESS ) { if ( bVerbose ) DumpODBCLog( hEnv, hDbc, 0 ); fprintf( stderr, "[ISQL]ERROR: Could not SQLAllocStmt\n" ); return 0; } if ( iniElement( szSQL, ' ', '\0', 1, szTable, sizeof(szTable) ) == INI_SUCCESS ) { SQLWCHAR tname[ 1024 ]; ansi_to_unicode( szTable, tname ); /* COLUMNS */ if ( SQLColumns( hStmt, NULL, 0, NULL, 0, tname, SQL_NTS, NULL, 0 ) != SQL_SUCCESS ) { if ( bVerbose ) DumpODBCLog( hEnv, hDbc, hStmt ); fprintf( stderr, "[ISQL]ERROR: Could not SQLColumns\n" ); SQLFreeStmt( hStmt, SQL_DROP ); return 0; } } else { /* TABLES */ if ( SQLTables( hStmt, NULL, 0, NULL, 0, NULL, 0, NULL, 0 ) != SQL_SUCCESS ) { if ( bVerbose ) DumpODBCLog( hEnv, hDbc, hStmt ); fprintf( stderr, "[ISQL]ERROR: Could not SQLTables\n" ); SQLFreeStmt( hStmt, SQL_DROP ); return 0; } } /**************************** * WRITE HEADER ***************************/ if ( bHTMLTable ) WriteHeaderHTMLTable( hStmt ); else if ( cDelimiter == 0 ) UWriteHeaderNormal( hStmt, szSepLine ); else if ( cDelimiter && bColumnNames ) WriteHeaderDelimited( hStmt, cDelimiter ); /**************************** * WRITE BODY ***************************/ if ( bHTMLTable ) WriteBodyHTMLTable( hStmt ); else if ( cDelimiter == 0 ) nRows = WriteBodyNormal( hStmt ); else WriteBodyDelimited( hStmt, cDelimiter ); /**************************** * WRITE FOOTER ***************************/ if ( bHTMLTable ) WriteFooterHTMLTable( hStmt ); else if ( cDelimiter == 0 ) UWriteFooterNormal( hStmt, szSepLine, nRows ); /**************************** * CLEANUP ***************************/ SQLFreeStmt( hStmt, SQL_DROP ); return 1; } /**************************** * CloseDatabase - cleanup in prep for exiting the program ***************************/ int CloseDatabase( SQLHENV hEnv, SQLHDBC hDbc ) { SQLDisconnect( hDbc ); SQLFreeConnect( hDbc ); SQLFreeEnv( hEnv ); return 1; } /**************************** * WRITE HTML ***************************/ static void WriteHeaderHTMLTable( SQLHSTMT hStmt ) { SQLINTEGER nCol = 0; SQLSMALLINT nColumns = 0; SQLTCHAR szColumnName[MAX_DATA_WIDTH+1]; szColumnName[ 0 ] = 0; printf( "<table BORDER>\n" ); printf( "<tr BGCOLOR=#000099>\n" ); if ( SQLNumResultCols( hStmt, &nColumns ) != SQL_SUCCESS ) nColumns = -1; for ( nCol = 1; nCol <= nColumns; nCol++ ) { SQLColAttribute( hStmt, nCol, SQL_DESC_LABEL, szColumnName, sizeof(szColumnName), NULL, NULL ); printf( "<td>\n" ); printf( "<font face=Arial,Helvetica><font color=#FFFFFF>\n" ); printf( "%s\n", uc_to_ascii( szColumnName )); printf( "</font></font>\n" ); printf( "</td>\n" ); } printf( "</tr>\n" ); } static void WriteBodyHTMLTable( SQLHSTMT hStmt ) { SQLINTEGER nCol = 0; SQLSMALLINT nColumns = 0; SQLLEN nIndicator = 0; SQLTCHAR szColumnValue[MAX_DATA_WIDTH+1]; SQLRETURN nReturn = 0; SQLRETURN ret; szColumnValue[ 0 ] = 0; if ( SQLNumResultCols( hStmt, &nColumns ) != SQL_SUCCESS ) nColumns = -1; while ( (ret = SQLFetch( hStmt )) == SQL_SUCCESS ) /* ROWS */ { printf( "<tr>\n" ); for ( nCol = 1; nCol <= nColumns; nCol++ ) /* COLS */ { printf( "<td>\n" ); printf( "<font face=Arial,Helvetica>\n" ); nReturn = SQLGetData( hStmt, nCol, SQL_C_WCHAR, (SQLPOINTER)szColumnValue, sizeof(szColumnValue), &nIndicator ); if ( nReturn == SQL_SUCCESS && nIndicator != SQL_NULL_DATA ) { uc_to_ascii( szColumnValue ); fputs((char*) szColumnValue, stdout ); } else if ( nReturn == SQL_ERROR ) { ret = SQL_ERROR; break; } else printf( "%s\n", "" ); printf( "</font>\n" ); printf( "</td>\n" ); } if (ret != SQL_SUCCESS) break; printf( "</tr>\n" ); } } static void WriteFooterHTMLTable( SQLHSTMT hStmt ) { printf( "</table>\n" ); } /**************************** * WRITE DELIMITED * - this output can be used by the ODBC Text File driver * - last column no longer has a delimit char (it is implicit)... * this is consistent with odbctxt ***************************/ static void WriteHeaderDelimited( SQLHSTMT hStmt, char cDelimiter ) { SQLINTEGER nCol = 0; SQLSMALLINT nColumns = 0; SQLTCHAR szColumnName[MAX_DATA_WIDTH+1]; szColumnName[ 0 ] = 0; if ( SQLNumResultCols( hStmt, &nColumns ) != SQL_SUCCESS ) nColumns = -1; for ( nCol = 1; nCol <= nColumns; nCol++ ) { SQLColAttribute( hStmt, nCol, SQL_DESC_LABEL, szColumnName, sizeof(szColumnName), NULL, NULL ); fputs((char*) uc_to_ascii( szColumnName ), stdout ); if ( nCol < nColumns ) putchar( cDelimiter ); } putchar( '\n' ); } static void WriteBodyDelimited( SQLHSTMT hStmt, char cDelimiter ) { SQLINTEGER nCol = 0; SQLSMALLINT nColumns = 0; SQLLEN nIndicator = 0; SQLTCHAR szColumnValue[MAX_DATA_WIDTH+1]; SQLRETURN nReturn = 0; SQLRETURN ret; szColumnValue[ 0 ] = 0; if ( SQLNumResultCols( hStmt, &nColumns ) != SQL_SUCCESS ) nColumns = -1; /* ROWS */ while (( ret = SQLFetch( hStmt )) == SQL_SUCCESS ) { /* COLS */ for ( nCol = 1; nCol <= nColumns; nCol++ ) { nReturn = SQLGetData( hStmt, nCol, SQL_C_WCHAR, (SQLPOINTER)szColumnValue, sizeof(szColumnValue), &nIndicator ); if ( nReturn == SQL_SUCCESS && nIndicator != SQL_NULL_DATA ) { uc_to_ascii( szColumnValue ); fputs((char*) szColumnValue, stdout ); if ( nCol < nColumns ) putchar( cDelimiter ); } else if ( nReturn == SQL_ERROR ) { ret = SQL_ERROR; break; } else { if ( nCol < nColumns ) putchar( cDelimiter ); } } if (ret != SQL_SUCCESS) break; printf( "\n" ); } if ( ret == SQL_ERROR ) { if ( bVerbose ) DumpODBCLog( 0, 0, hStmt ); } } /**************************** * WRITE NORMAL ***************************/ void UWriteHeaderNormal( SQLHSTMT hStmt, SQLTCHAR *szSepLine ) { SQLINTEGER nCol = 0; SQLSMALLINT nColumns = 0; SQLULEN nMaxLength = 10; SQLTCHAR szColumn[MAX_DATA_WIDTH+20]; SQLTCHAR szColumnName[MAX_DATA_WIDTH+1]; SQLTCHAR szHdrLine[32001]; szColumn[ 0 ] = 0; szColumnName[ 0 ] = 0; szHdrLine[ 0 ] = 0; if ( SQLNumResultCols( hStmt, &nColumns ) != SQL_SUCCESS ) nColumns = -1; for ( nCol = 1; nCol <= nColumns; nCol++ ) { SQLColAttribute( hStmt, nCol, SQL_DESC_DISPLAY_SIZE, NULL, 0, NULL, (SQLLEN*)&nMaxLength ); SQLColAttribute( hStmt, nCol, SQL_DESC_LABEL, szColumnName, sizeof(szColumnName), NULL, NULL ); if ( nMaxLength > MAX_DATA_WIDTH ) nMaxLength = MAX_DATA_WIDTH; uc_to_ascii( szColumnName ); /* SEP */ memset( szColumn, '\0', sizeof(szColumn) ); memset( szColumn, '-', max( nMaxLength, strlen((char*)szColumnName) ) + 1 ); strcat((char*) szSepLine, "+" ); strcat((char*) szSepLine,(char*) szColumn ); /* HDR */ sprintf((char*) szColumn, "| %-*s", (int)max( nMaxLength, strlen((char*)szColumnName) ), (char*)szColumnName ); strcat((char*) szHdrLine,(char*) szColumn ); } strcat((char*) szSepLine, "+\n" ); strcat((char*) szHdrLine, "|\n" ); puts((char*) szSepLine ); puts((char*) szHdrLine ); puts((char*) szSepLine ); } static SQLLEN WriteBodyNormal( SQLHSTMT hStmt ) { SQLINTEGER nCol = 0; SQLSMALLINT nColumns = 0; SQLLEN nIndicator = 0; SQLTCHAR szColumn[MAX_DATA_WIDTH+20]; SQLTCHAR szColumnValue[MAX_DATA_WIDTH+1]; SQLTCHAR szColumnName[MAX_DATA_WIDTH+1]; SQLULEN nMaxLength = 10; SQLRETURN nReturn = 0; SQLRETURN ret; SQLLEN nRows = 0; szColumn[ 0 ] = 0; szColumnValue[ 0 ] = 0; szColumnName[ 0 ] = 0; if ( SQLNumResultCols( hStmt, &nColumns ) != SQL_SUCCESS ) nColumns = -1; /* ROWS */ while (( ret = SQLFetch( hStmt )) == SQL_SUCCESS ) { /* COLS */ for ( nCol = 1; nCol <= nColumns; nCol++ ) { SQLColAttribute( hStmt, nCol, SQL_DESC_LABEL, szColumnName, sizeof(szColumnName), NULL, NULL ); SQLColAttribute( hStmt, nCol, SQL_DESC_DISPLAY_SIZE, NULL, 0, NULL, (SQLLEN*)&nMaxLength ); uc_to_ascii( szColumnName ); if ( nMaxLength > MAX_DATA_WIDTH ) nMaxLength = MAX_DATA_WIDTH; nReturn = SQLGetData( hStmt, nCol, SQL_C_WCHAR, (SQLPOINTER)szColumnValue, sizeof(szColumnValue), &nIndicator ); szColumnValue[MAX_DATA_WIDTH] = '\0'; uc_to_ascii( szColumnValue ); if ( nReturn == SQL_SUCCESS && nIndicator != SQL_NULL_DATA ) { if ( strlen((char*)szColumnValue) < max( nMaxLength, strlen((char*)szColumnName ))) { int i; size_t maxlen=max( nMaxLength, strlen((char*)szColumnName )); strcpy((char*) szColumn, "| " ); strcat((char*) szColumn, (char*) szColumnValue ); for ( i = strlen((char*) szColumnValue ); i < maxlen; i ++ ) { strcat((char*) szColumn, " " ); } } else { strcpy((char*) szColumn, "| " ); strcat((char*) szColumn, (char*) szColumnValue ); } } else if ( nReturn == SQL_ERROR ) { ret = SQL_ERROR; break; } else { sprintf((char*) szColumn, "| %-*s", (int)max( nMaxLength, strlen((char*) szColumnName) ), "" ); } fputs((char*) szColumn, stdout ); } if (ret != SQL_SUCCESS) break; printf( "|\n" ); nRows++; } if ( ret == SQL_ERROR ) { if ( bVerbose ) DumpODBCLog( 0, 0, hStmt ); } return nRows; } void UWriteFooterNormal( SQLHSTMT hStmt, SQLTCHAR *szSepLine, SQLLEN nRows ) { SQLLEN nRowsAffected = -1; puts( (char*)szSepLine ); SQLRowCount( hStmt, &nRowsAffected ); printf( "SQLRowCount returns %ld\n", nRowsAffected ); if ( nRows ) { printf( "%ld rows fetched\n", nRows ); } } static int DumpODBCLog( SQLHENV hEnv, SQLHDBC hDbc, SQLHSTMT hStmt ) { SQLTCHAR szError[501]; SQLTCHAR szSqlState[10]; SQLINTEGER nNativeError; SQLSMALLINT nErrorMsg; if ( hStmt ) { while ( SQLError( hEnv, hDbc, hStmt, szSqlState, &nNativeError, szError, 500, &nErrorMsg ) == SQL_SUCCESS ) { printf( "%s\n", uc_to_ascii( szError )); } } if ( hDbc ) { while ( SQLError( hEnv, hDbc, 0, szSqlState, &nNativeError, szError, 500, &nErrorMsg ) == SQL_SUCCESS ) { printf( "%s\n", uc_to_ascii( szError )); } } if ( hEnv ) { while ( SQLError( hEnv, 0, 0, szSqlState, &nNativeError, szError, 500, &nErrorMsg ) == SQL_SUCCESS ) { printf( "%s\n", uc_to_ascii( szError )); } } return 1; }
./CrossVul/dataset_final_sorted/CWE-119/c/good_634_5
crossvul-cpp_data_good_4781_1
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % TTTTT IIIII FFFFF FFFFF % % T I F F % % T I FFF FFF % % T I F F % % T IIIII F F % % % % % % Read/Write TIFF Image Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-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/color.h" #include "magick/color-private.h" #include "magick/colormap.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/constitute.h" #include "magick/draw.h" #include "magick/enhance.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/geometry.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/log.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/module.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/option.h" #include "magick/pixel-accessor.h" #include "magick/pixel-private.h" #include "magick/profile.h" #include "magick/property.h" #include "magick/quantum.h" #include "magick/quantum-private.h" #include "magick/resize.h" #include "magick/resource_.h" #include "magick/semaphore.h" #include "magick/splay-tree.h" #include "magick/static.h" #include "magick/statistic.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/thread_.h" #include "magick/token.h" #include "magick/utility.h" #if defined(MAGICKCORE_TIFF_DELEGATE) # if defined(MAGICKCORE_HAVE_TIFFCONF_H) # include "tiffconf.h" # endif # include "tiff.h" # include "tiffio.h" # if !defined(COMPRESSION_ADOBE_DEFLATE) # define COMPRESSION_ADOBE_DEFLATE 8 # endif # if !defined(PREDICTOR_HORIZONTAL) # define PREDICTOR_HORIZONTAL 2 # endif # if !defined(TIFFTAG_COPYRIGHT) # define TIFFTAG_COPYRIGHT 33432 # endif # if !defined(TIFFTAG_OPIIMAGEID) # define TIFFTAG_OPIIMAGEID 32781 # endif #include "psd-private.h" /* Typedef declarations. */ typedef enum { ReadSingleSampleMethod, ReadRGBAMethod, ReadCMYKAMethod, ReadYCCKMethod, ReadStripMethod, ReadTileMethod, ReadGenericMethod } TIFFMethodType; #if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY) typedef struct _ExifInfo { unsigned int tag, type, variable_length; const char *property; } ExifInfo; static const ExifInfo exif_info[] = { { EXIFTAG_EXPOSURETIME, TIFF_RATIONAL, 0, "exif:ExposureTime" }, { EXIFTAG_FNUMBER, TIFF_RATIONAL, 0, "exif:FNumber" }, { EXIFTAG_EXPOSUREPROGRAM, TIFF_SHORT, 0, "exif:ExposureProgram" }, { EXIFTAG_SPECTRALSENSITIVITY, TIFF_ASCII, 0, "exif:SpectralSensitivity" }, { EXIFTAG_ISOSPEEDRATINGS, TIFF_SHORT, 1, "exif:ISOSpeedRatings" }, { EXIFTAG_OECF, TIFF_NOTYPE, 0, "exif:OptoelectricConversionFactor" }, { EXIFTAG_EXIFVERSION, TIFF_NOTYPE, 0, "exif:ExifVersion" }, { EXIFTAG_DATETIMEORIGINAL, TIFF_ASCII, 0, "exif:DateTimeOriginal" }, { EXIFTAG_DATETIMEDIGITIZED, TIFF_ASCII, 0, "exif:DateTimeDigitized" }, { EXIFTAG_COMPONENTSCONFIGURATION, TIFF_NOTYPE, 0, "exif:ComponentsConfiguration" }, { EXIFTAG_COMPRESSEDBITSPERPIXEL, TIFF_RATIONAL, 0, "exif:CompressedBitsPerPixel" }, { EXIFTAG_SHUTTERSPEEDVALUE, TIFF_SRATIONAL, 0, "exif:ShutterSpeedValue" }, { EXIFTAG_APERTUREVALUE, TIFF_RATIONAL, 0, "exif:ApertureValue" }, { EXIFTAG_BRIGHTNESSVALUE, TIFF_SRATIONAL, 0, "exif:BrightnessValue" }, { EXIFTAG_EXPOSUREBIASVALUE, TIFF_SRATIONAL, 0, "exif:ExposureBiasValue" }, { EXIFTAG_MAXAPERTUREVALUE, TIFF_RATIONAL, 0, "exif:MaxApertureValue" }, { EXIFTAG_SUBJECTDISTANCE, TIFF_RATIONAL, 0, "exif:SubjectDistance" }, { EXIFTAG_METERINGMODE, TIFF_SHORT, 0, "exif:MeteringMode" }, { EXIFTAG_LIGHTSOURCE, TIFF_SHORT, 0, "exif:LightSource" }, { EXIFTAG_FLASH, TIFF_SHORT, 0, "exif:Flash" }, { EXIFTAG_FOCALLENGTH, TIFF_RATIONAL, 0, "exif:FocalLength" }, { EXIFTAG_SUBJECTAREA, TIFF_NOTYPE, 0, "exif:SubjectArea" }, { EXIFTAG_MAKERNOTE, TIFF_NOTYPE, 0, "exif:MakerNote" }, { EXIFTAG_USERCOMMENT, TIFF_NOTYPE, 0, "exif:UserComment" }, { EXIFTAG_SUBSECTIME, TIFF_ASCII, 0, "exif:SubSecTime" }, { EXIFTAG_SUBSECTIMEORIGINAL, TIFF_ASCII, 0, "exif:SubSecTimeOriginal" }, { EXIFTAG_SUBSECTIMEDIGITIZED, TIFF_ASCII, 0, "exif:SubSecTimeDigitized" }, { EXIFTAG_FLASHPIXVERSION, TIFF_NOTYPE, 0, "exif:FlashpixVersion" }, { EXIFTAG_PIXELXDIMENSION, TIFF_LONG, 0, "exif:PixelXDimension" }, { EXIFTAG_PIXELYDIMENSION, TIFF_LONG, 0, "exif:PixelYDimension" }, { EXIFTAG_RELATEDSOUNDFILE, TIFF_ASCII, 0, "exif:RelatedSoundFile" }, { EXIFTAG_FLASHENERGY, TIFF_RATIONAL, 0, "exif:FlashEnergy" }, { EXIFTAG_SPATIALFREQUENCYRESPONSE, TIFF_NOTYPE, 0, "exif:SpatialFrequencyResponse" }, { EXIFTAG_FOCALPLANEXRESOLUTION, TIFF_RATIONAL, 0, "exif:FocalPlaneXResolution" }, { EXIFTAG_FOCALPLANEYRESOLUTION, TIFF_RATIONAL, 0, "exif:FocalPlaneYResolution" }, { EXIFTAG_FOCALPLANERESOLUTIONUNIT, TIFF_SHORT, 0, "exif:FocalPlaneResolutionUnit" }, { EXIFTAG_SUBJECTLOCATION, TIFF_SHORT, 0, "exif:SubjectLocation" }, { EXIFTAG_EXPOSUREINDEX, TIFF_RATIONAL, 0, "exif:ExposureIndex" }, { EXIFTAG_SENSINGMETHOD, TIFF_SHORT, 0, "exif:SensingMethod" }, { EXIFTAG_FILESOURCE, TIFF_NOTYPE, 0, "exif:FileSource" }, { EXIFTAG_SCENETYPE, TIFF_NOTYPE, 0, "exif:SceneType" }, { EXIFTAG_CFAPATTERN, TIFF_NOTYPE, 0, "exif:CFAPattern" }, { EXIFTAG_CUSTOMRENDERED, TIFF_SHORT, 0, "exif:CustomRendered" }, { EXIFTAG_EXPOSUREMODE, TIFF_SHORT, 0, "exif:ExposureMode" }, { EXIFTAG_WHITEBALANCE, TIFF_SHORT, 0, "exif:WhiteBalance" }, { EXIFTAG_DIGITALZOOMRATIO, TIFF_RATIONAL, 0, "exif:DigitalZoomRatio" }, { EXIFTAG_FOCALLENGTHIN35MMFILM, TIFF_SHORT, 0, "exif:FocalLengthIn35mmFilm" }, { EXIFTAG_SCENECAPTURETYPE, TIFF_SHORT, 0, "exif:SceneCaptureType" }, { EXIFTAG_GAINCONTROL, TIFF_RATIONAL, 0, "exif:GainControl" }, { EXIFTAG_CONTRAST, TIFF_SHORT, 0, "exif:Contrast" }, { EXIFTAG_SATURATION, TIFF_SHORT, 0, "exif:Saturation" }, { EXIFTAG_SHARPNESS, TIFF_SHORT, 0, "exif:Sharpness" }, { EXIFTAG_DEVICESETTINGDESCRIPTION, TIFF_NOTYPE, 0, "exif:DeviceSettingDescription" }, { EXIFTAG_SUBJECTDISTANCERANGE, TIFF_SHORT, 0, "exif:SubjectDistanceRange" }, { EXIFTAG_IMAGEUNIQUEID, TIFF_ASCII, 0, "exif:ImageUniqueID" }, { 0, 0, 0, (char *) NULL } }; #endif #endif /* MAGICKCORE_TIFF_DELEGATE */ /* Global declarations. */ static MagickThreadKey tiff_exception; static SemaphoreInfo *tiff_semaphore = (SemaphoreInfo *) NULL; static TIFFErrorHandler error_handler, warning_handler; static volatile MagickBooleanType instantiate_key = MagickFalse; /* Forward declarations. */ #if defined(MAGICKCORE_TIFF_DELEGATE) static Image * ReadTIFFImage(const ImageInfo *,ExceptionInfo *); static MagickBooleanType WriteGROUP4Image(const ImageInfo *,Image *), WritePTIFImage(const ImageInfo *,Image *), WriteTIFFImage(const ImageInfo *,Image *); #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s T I F F % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsTIFF() returns MagickTrue if the image format type, identified by the % magick string, is TIFF. % % The format of the IsTIFF method is: % % MagickBooleanType IsTIFF(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsTIFF(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (memcmp(magick,"\115\115\000\052",4) == 0) return(MagickTrue); if (memcmp(magick,"\111\111\052\000",4) == 0) return(MagickTrue); #if defined(TIFF_VERSION_BIG) if (length < 8) return(MagickFalse); if (memcmp(magick,"\115\115\000\053\000\010\000\000",8) == 0) return(MagickTrue); if (memcmp(magick,"\111\111\053\000\010\000\000\000",8) == 0) return(MagickTrue); #endif return(MagickFalse); } #if defined(MAGICKCORE_TIFF_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d G R O U P 4 I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadGROUP4Image() reads a raw CCITT Group 4 image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadGROUP4Image method is: % % Image *ReadGROUP4Image(const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static inline size_t WriteLSBLong(FILE *file,const size_t value) { unsigned char buffer[4]; buffer[0]=(unsigned char) value; buffer[1]=(unsigned char) (value >> 8); buffer[2]=(unsigned char) (value >> 16); buffer[3]=(unsigned char) (value >> 24); return(fwrite(buffer,1,4,file)); } static Image *ReadGROUP4Image(const ImageInfo *image_info, ExceptionInfo *exception) { char filename[MaxTextExtent]; FILE *file; Image *image; ImageInfo *read_info; int c, unique_file; MagickBooleanType status; size_t length; ssize_t offset, strip_offset; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == 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); } /* Write raw CCITT Group 4 wrapped as a TIFF image file. */ file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); if (unique_file != -1) file=fdopen(unique_file,"wb"); if ((unique_file == -1) || (file == (FILE *) NULL)) ThrowImageException(FileOpenError,"UnableToCreateTemporaryFile"); length=fwrite("\111\111\052\000\010\000\000\000\016\000",1,10,file); length=fwrite("\376\000\003\000\001\000\000\000\000\000\000\000",1,12,file); length=fwrite("\000\001\004\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,image->columns); length=fwrite("\001\001\004\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,image->rows); length=fwrite("\002\001\003\000\001\000\000\000\001\000\000\000",1,12,file); length=fwrite("\003\001\003\000\001\000\000\000\004\000\000\000",1,12,file); length=fwrite("\006\001\003\000\001\000\000\000\000\000\000\000",1,12,file); length=fwrite("\021\001\003\000\001\000\000\000",1,8,file); strip_offset=10+(12*14)+4+8; length=WriteLSBLong(file,(size_t) strip_offset); length=fwrite("\022\001\003\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,(size_t) image_info->orientation); length=fwrite("\025\001\003\000\001\000\000\000\001\000\000\000",1,12,file); length=fwrite("\026\001\004\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,image->rows); length=fwrite("\027\001\004\000\001\000\000\000\000\000\000\000",1,12,file); offset=(ssize_t) ftell(file)-4; length=fwrite("\032\001\005\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,(size_t) (strip_offset-8)); length=fwrite("\033\001\005\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,(size_t) (strip_offset-8)); length=fwrite("\050\001\003\000\001\000\000\000\002\000\000\000",1,12,file); length=fwrite("\000\000\000\000",1,4,file); length=WriteLSBLong(file,(size_t) (image->x_resolution+0.5)); length=WriteLSBLong(file,1); for (length=0; (c=ReadBlobByte(image)) != EOF; length++) (void) fputc(c,file); offset=(ssize_t) fseek(file,(ssize_t) offset,SEEK_SET); length=WriteLSBLong(file,(unsigned int) length); (void) fclose(file); (void) CloseBlob(image); image=DestroyImage(image); /* Read TIFF image. */ read_info=CloneImageInfo((ImageInfo *) NULL); (void) FormatLocaleString(read_info->filename,MaxTextExtent,"%s",filename); image=ReadTIFFImage(read_info,exception); read_info=DestroyImageInfo(read_info); if (image != (Image *) NULL) { (void) CopyMagickString(image->filename,image_info->filename, MaxTextExtent); (void) CopyMagickString(image->magick_filename,image_info->filename, MaxTextExtent); (void) CopyMagickString(image->magick,"GROUP4",MaxTextExtent); } (void) RelinquishUniqueFileResource(filename); return(image); } #endif #if defined(MAGICKCORE_TIFF_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d T I F F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadTIFFImage() reads a Tagged image file and returns it. It allocates the % memory necessary for the new Image structure and returns a pointer to the % new image. % % The format of the ReadTIFFImage method is: % % Image *ReadTIFFImage(const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static inline unsigned char ClampYCC(double value) { value=255.0-value; if (value < 0.0) return((unsigned char)0); if (value > 255.0) return((unsigned char)255); return((unsigned char)(value)); } static MagickBooleanType DecodeLabImage(Image *image,ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; ssize_t y; status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double a, b; a=QuantumScale*GetPixela(q)+0.5; if (a > 1.0) a-=1.0; b=QuantumScale*GetPixelb(q)+0.5; if (b > 1.0) b-=1.0; SetPixela(q,QuantumRange*a); SetPixelb(q,QuantumRange*b); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status); } static MagickBooleanType ReadProfile(Image *image,const char *name, const unsigned char *datum,ssize_t length) { MagickBooleanType status; StringInfo *profile; if (length < 4) return(MagickFalse); profile=BlobToStringInfo(datum,(size_t) length); if (profile == (StringInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=SetImageProfile(image,name,profile); profile=DestroyStringInfo(profile); if (status == MagickFalse) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); return(MagickTrue); } #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static int TIFFCloseBlob(thandle_t image) { (void) CloseBlob((Image *) image); return(0); } static void TIFFErrors(const char *module,const char *format,va_list error) { char message[MaxTextExtent]; ExceptionInfo *exception; #if defined(MAGICKCORE_HAVE_VSNPRINTF) (void) vsnprintf(message,MaxTextExtent,format,error); #else (void) vsprintf(message,format,error); #endif (void) ConcatenateMagickString(message,".",MaxTextExtent); exception=(ExceptionInfo *) GetMagickThreadValue(tiff_exception); if (exception != (ExceptionInfo *) NULL) (void) ThrowMagickException(exception,GetMagickModule(),CoderError,message, "`%s'",module); } static toff_t TIFFGetBlobSize(thandle_t image) { return((toff_t) GetBlobSize((Image *) image)); } static void TIFFGetProfiles(TIFF *tiff,Image *image,MagickBooleanType ping) { uint32 length; unsigned char *profile; length=0; if (ping == MagickFalse) { #if defined(TIFFTAG_ICCPROFILE) if ((TIFFGetField(tiff,TIFFTAG_ICCPROFILE,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) (void) ReadProfile(image,"icc",profile,(ssize_t) length); #endif #if defined(TIFFTAG_PHOTOSHOP) if ((TIFFGetField(tiff,TIFFTAG_PHOTOSHOP,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) (void) ReadProfile(image,"8bim",profile,(ssize_t) length); #endif #if defined(TIFFTAG_RICHTIFFIPTC) if ((TIFFGetField(tiff,TIFFTAG_RICHTIFFIPTC,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) { if (TIFFIsByteSwapped(tiff) != 0) TIFFSwabArrayOfLong((uint32 *) profile,(size_t) length); (void) ReadProfile(image,"iptc",profile,4L*length); } #endif #if defined(TIFFTAG_XMLPACKET) if ((TIFFGetField(tiff,TIFFTAG_XMLPACKET,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) (void) ReadProfile(image,"xmp",profile,(ssize_t) length); #endif if ((TIFFGetField(tiff,34118,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) (void) ReadProfile(image,"tiff:34118",profile,(ssize_t) length); } if ((TIFFGetField(tiff,37724,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) (void) ReadProfile(image,"tiff:37724",profile,(ssize_t) length); } static void TIFFGetProperties(TIFF *tiff,Image *image) { char message[MaxTextExtent], *text; uint32 count, length, type; unsigned long *tietz; if (TIFFGetField(tiff,TIFFTAG_ARTIST,&text) == 1) (void) SetImageProperty(image,"tiff:artist",text); if (TIFFGetField(tiff,TIFFTAG_COPYRIGHT,&text) == 1) (void) SetImageProperty(image,"tiff:copyright",text); if (TIFFGetField(tiff,TIFFTAG_DATETIME,&text) == 1) (void) SetImageProperty(image,"tiff:timestamp",text); if (TIFFGetField(tiff,TIFFTAG_DOCUMENTNAME,&text) == 1) (void) SetImageProperty(image,"tiff:document",text); if (TIFFGetField(tiff,TIFFTAG_HOSTCOMPUTER,&text) == 1) (void) SetImageProperty(image,"tiff:hostcomputer",text); if (TIFFGetField(tiff,TIFFTAG_IMAGEDESCRIPTION,&text) == 1) (void) SetImageProperty(image,"comment",text); if (TIFFGetField(tiff,TIFFTAG_MAKE,&text) == 1) (void) SetImageProperty(image,"tiff:make",text); if (TIFFGetField(tiff,TIFFTAG_MODEL,&text) == 1) (void) SetImageProperty(image,"tiff:model",text); if (TIFFGetField(tiff,TIFFTAG_OPIIMAGEID,&count,&text) == 1) { if (count >= MaxTextExtent) count=MaxTextExtent-1; (void) CopyMagickString(message,text,count+1); (void) SetImageProperty(image,"tiff:image-id",message); } if (TIFFGetField(tiff,TIFFTAG_PAGENAME,&text) == 1) (void) SetImageProperty(image,"label",text); if (TIFFGetField(tiff,TIFFTAG_SOFTWARE,&text) == 1) (void) SetImageProperty(image,"tiff:software",text); if (TIFFGetField(tiff,33423,&count,&text) == 1) { if (count >= MaxTextExtent) count=MaxTextExtent-1; (void) CopyMagickString(message,text,count+1); (void) SetImageProperty(image,"tiff:kodak-33423",message); } if (TIFFGetField(tiff,36867,&count,&text) == 1) { if (count >= MaxTextExtent) count=MaxTextExtent-1; (void) CopyMagickString(message,text,count+1); (void) SetImageProperty(image,"tiff:kodak-36867",message); } if (TIFFGetField(tiff,TIFFTAG_SUBFILETYPE,&type) == 1) switch (type) { case 0x01: { (void) SetImageProperty(image,"tiff:subfiletype","REDUCEDIMAGE"); break; } case 0x02: { (void) SetImageProperty(image,"tiff:subfiletype","PAGE"); break; } case 0x04: { (void) SetImageProperty(image,"tiff:subfiletype","MASK"); break; } default: break; } if (TIFFGetField(tiff,37706,&length,&tietz) == 1) { (void) FormatLocaleString(message,MaxTextExtent,"%lu",tietz[0]); (void) SetImageProperty(image,"tiff:tietz_offset",message); } } static void TIFFGetEXIFProperties(TIFF *tiff,Image *image) { #if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY) char value[MaxTextExtent]; register ssize_t i; tdir_t directory; #if defined(TIFF_VERSION_BIG) uint64 #else uint32 #endif offset; void *sans; /* Read EXIF properties. */ offset=0; if (TIFFGetField(tiff,TIFFTAG_EXIFIFD,&offset) != 1) return; directory=TIFFCurrentDirectory(tiff); if (TIFFReadEXIFDirectory(tiff,offset) != 1) { TIFFSetDirectory(tiff,directory); return; } sans=NULL; for (i=0; exif_info[i].tag != 0; i++) { *value='\0'; switch (exif_info[i].type) { case TIFF_ASCII: { char *ascii; ascii=(char *) NULL; if ((TIFFGetField(tiff,exif_info[i].tag,&ascii,&sans,&sans) == 1) && (ascii != (char *) NULL) && (*ascii != '\0')) (void) CopyMagickString(value,ascii,MaxTextExtent); break; } case TIFF_SHORT: { if (exif_info[i].variable_length == 0) { uint16 shorty; shorty=0; if (TIFFGetField(tiff,exif_info[i].tag,&shorty,&sans,&sans) == 1) (void) FormatLocaleString(value,MaxTextExtent,"%d",shorty); } else { int tiff_status; uint16 *shorty; uint16 shorty_num; tiff_status=TIFFGetField(tiff,exif_info[i].tag,&shorty_num,&shorty, &sans,&sans); if (tiff_status == 1) (void) FormatLocaleString(value,MaxTextExtent,"%d", shorty_num != 0 ? shorty[0] : 0); } break; } case TIFF_LONG: { uint32 longy; longy=0; if (TIFFGetField(tiff,exif_info[i].tag,&longy,&sans,&sans) == 1) (void) FormatLocaleString(value,MaxTextExtent,"%d",longy); break; } #if defined(TIFF_VERSION_BIG) case TIFF_LONG8: { uint64 long8y; long8y=0; if (TIFFGetField(tiff,exif_info[i].tag,&long8y,&sans,&sans) == 1) (void) FormatLocaleString(value,MaxTextExtent,"%.20g",(double) ((MagickOffsetType) long8y)); break; } #endif case TIFF_RATIONAL: case TIFF_SRATIONAL: case TIFF_FLOAT: { float floaty; floaty=0.0; if (TIFFGetField(tiff,exif_info[i].tag,&floaty,&sans,&sans) == 1) (void) FormatLocaleString(value,MaxTextExtent,"%g",(double) floaty); break; } case TIFF_DOUBLE: { double doubley; doubley=0.0; if (TIFFGetField(tiff,exif_info[i].tag,&doubley,&sans,&sans) == 1) (void) FormatLocaleString(value,MaxTextExtent,"%g",doubley); break; } default: break; } if (*value != '\0') (void) SetImageProperty(image,exif_info[i].property,value); } TIFFSetDirectory(tiff,directory); #else (void) tiff; (void) image; #endif } static int TIFFMapBlob(thandle_t image,tdata_t *base,toff_t *size) { *base=(tdata_t *) GetBlobStreamData((Image *) image); if (*base != (tdata_t *) NULL) *size=(toff_t) GetBlobSize((Image *) image); if (*base != (tdata_t *) NULL) return(1); return(0); } static tsize_t TIFFReadBlob(thandle_t image,tdata_t data,tsize_t size) { tsize_t count; count=(tsize_t) ReadBlob((Image *) image,(size_t) size, (unsigned char *) data); return(count); } static int32 TIFFReadPixels(TIFF *tiff,size_t bits_per_sample, tsample_t sample,ssize_t row,tdata_t scanline) { int32 status; (void) bits_per_sample; status=TIFFReadScanline(tiff,scanline,(uint32) row,sample); return(status); } static toff_t TIFFSeekBlob(thandle_t image,toff_t offset,int whence) { return((toff_t) SeekBlob((Image *) image,(MagickOffsetType) offset,whence)); } static void TIFFUnmapBlob(thandle_t image,tdata_t base,toff_t size) { (void) image; (void) base; (void) size; } static void TIFFWarnings(const char *module,const char *format,va_list warning) { char message[MaxTextExtent]; ExceptionInfo *exception; #if defined(MAGICKCORE_HAVE_VSNPRINTF) (void) vsnprintf(message,MaxTextExtent,format,warning); #else (void) vsprintf(message,format,warning); #endif (void) ConcatenateMagickString(message,".",MaxTextExtent); exception=(ExceptionInfo *) GetMagickThreadValue(tiff_exception); if (exception != (ExceptionInfo *) NULL) (void) ThrowMagickException(exception,GetMagickModule(),CoderWarning, message,"`%s'",module); } static tsize_t TIFFWriteBlob(thandle_t image,tdata_t data,tsize_t size) { tsize_t count; count=(tsize_t) WriteBlob((Image *) image,(size_t) size, (unsigned char *) data); return(count); } static TIFFMethodType GetJPEGMethod(Image* image,TIFF *tiff,uint16 photometric, uint16 bits_per_sample,uint16 samples_per_pixel) { #define BUFFER_SIZE 2048 MagickOffsetType position, offset; register size_t i; TIFFMethodType method; #if defined(TIFF_VERSION_BIG) uint64 #else uint32 #endif **value; unsigned char buffer[BUFFER_SIZE+32]; unsigned short length; /* only support 8 bit for now */ if ((photometric != PHOTOMETRIC_SEPARATED) || (bits_per_sample != 8) || (samples_per_pixel != 4)) return(ReadGenericMethod); /* Search for Adobe APP14 JPEG Marker */ if (!TIFFGetField(tiff,TIFFTAG_STRIPOFFSETS,&value)) return(ReadRGBAMethod); position=TellBlob(image); offset=(MagickOffsetType) (value[0]); if (SeekBlob(image,offset,SEEK_SET) != offset) return(ReadRGBAMethod); method=ReadRGBAMethod; if (ReadBlob(image,BUFFER_SIZE,buffer) == BUFFER_SIZE) { for (i=0; i < BUFFER_SIZE; i++) { while (i < BUFFER_SIZE) { if (buffer[i++] == 255) break; } while (i < BUFFER_SIZE) { if (buffer[++i] != 255) break; } if (buffer[i++] == 216) /* JPEG_MARKER_SOI */ continue; length=(unsigned short) (((unsigned int) (buffer[i] << 8) | (unsigned int) buffer[i+1]) & 0xffff); if (i+(size_t) length >= BUFFER_SIZE) break; if (buffer[i-1] == 238) /* JPEG_MARKER_APP0+14 */ { if (length != 14) break; /* 0 == CMYK, 1 == YCbCr, 2 = YCCK */ if (buffer[i+13] == 2) method=ReadYCCKMethod; break; } i+=(size_t) length; } } (void) SeekBlob(image,position,SEEK_SET); return(method); } static void TIFFReadPhotoshopLayers(Image* image,const ImageInfo *image_info, ExceptionInfo *exception) { const char *option; const StringInfo *layer_info; Image *layers; PSDInfo info; register ssize_t i; if (GetImageListLength(image) != 1) return; if ((image_info->number_scenes == 1) && (image_info->scene == 0)) return; option=GetImageOption(image_info,"tiff:ignore-layers"); if (option != (const char * ) NULL) return; layer_info=GetImageProfile(image,"tiff:37724"); if (layer_info == (const StringInfo *) NULL) return; for (i=0; i < (ssize_t) layer_info->length-8; i++) { if (LocaleNCompare((const char *) (layer_info->datum+i), image->endian == MSBEndian ? "8BIM" : "MIB8",4) != 0) continue; i+=4; if ((LocaleNCompare((const char *) (layer_info->datum+i), image->endian == MSBEndian ? "Layr" : "ryaL",4) == 0) || (LocaleNCompare((const char *) (layer_info->datum+i), image->endian == MSBEndian ? "LMsk" : "ksML",4) == 0) || (LocaleNCompare((const char *) (layer_info->datum+i), image->endian == MSBEndian ? "Lr16" : "61rL",4) == 0) || (LocaleNCompare((const char *) (layer_info->datum+i), image->endian == MSBEndian ? "Lr32" : "23rL",4) == 0)) break; } i+=4; if (i >= (ssize_t) (layer_info->length-8)) return; layers=CloneImage(image,image->columns,image->rows,MagickTrue,exception); (void) DeleteImageProfile(layers,"tiff:37724"); AttachBlob(layers->blob,layer_info->datum,layer_info->length); SeekBlob(layers,(MagickOffsetType) i,SEEK_SET); info.version=1; info.columns=layers->columns; info.rows=layers->rows; /* Setting the mode to a value that won't change the colorspace */ info.mode=10; if (IsGrayImage(image,&image->exception) != MagickFalse) info.channels=(image->matte != MagickFalse ? 2UL : 1UL); else if (image->storage_class == PseudoClass) info.channels=(image->matte != MagickFalse ? 2UL : 1UL); else { if (image->colorspace != CMYKColorspace) info.channels=(image->matte != MagickFalse ? 4UL : 3UL); else info.channels=(image->matte != MagickFalse ? 5UL : 4UL); } (void) ReadPSDLayers(layers,image_info,&info,MagickFalse,exception); InheritException(exception,&layers->exception); DeleteImageFromList(&layers); if (layers != (Image *) NULL) { SetImageArtifact(image,"tiff:has-layers","true"); AppendImageToList(&image,layers); while (layers != (Image *) NULL) { SetImageArtifact(layers,"tiff:has-layers","true"); DetachBlob(layers->blob); layers=GetNextImageInList(layers); } } } #if defined(__cplusplus) || defined(c_plusplus) } #endif static Image *ReadTIFFImage(const ImageInfo *image_info, ExceptionInfo *exception) { const char *option; float *chromaticity, x_position, y_position, x_resolution, y_resolution; Image *image; int tiff_status; MagickBooleanType status; MagickSizeType number_pixels; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; size_t pad; ssize_t y; TIFF *tiff; TIFFMethodType method; uint16 compress_tag, bits_per_sample, endian, extra_samples, interlace, max_sample_value, min_sample_value, orientation, pages, photometric, *sample_info, sample_format, samples_per_pixel, units, value; uint32 height, rows_per_strip, width; unsigned char *pixels; /* Open image. */ 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); } (void) SetMagickThreadValue(tiff_exception,exception); tiff=TIFFClientOpen(image->filename,"rb",(thandle_t) image,TIFFReadBlob, TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob, TIFFUnmapBlob); if (tiff == (TIFF *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } if (image_info->number_scenes != 0) { /* Generate blank images for subimage specification (e.g. image.tif[4]. We need to check the number of directores because it is possible that the subimage(s) are stored in the photoshop profile. */ if (image_info->scene < (size_t)TIFFNumberOfDirectories(tiff)) { for (i=0; i < (ssize_t) image_info->scene; i++) { status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse; if (status == MagickFalse) { TIFFClose(tiff); image=DestroyImageList(image); return((Image *) NULL); } AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { TIFFClose(tiff); image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); } } } do { DisableMSCWarning(4127) if (0 && (image_info->verbose != MagickFalse)) TIFFPrintDirectory(tiff,stdout,MagickFalse); RestoreMSCWarning if ((TIFFGetField(tiff,TIFFTAG_IMAGEWIDTH,&width) != 1) || (TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&height) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_COMPRESSION,&compress_tag) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_PLANARCONFIG,&interlace) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,&samples_per_pixel) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,&bits_per_sample) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLEFORMAT,&sample_format) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_MINSAMPLEVALUE,&min_sample_value) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_MAXSAMPLEVALUE,&max_sample_value) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_PHOTOMETRIC,&photometric) != 1)) { TIFFClose(tiff); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (sample_format == SAMPLEFORMAT_IEEEFP) (void) SetImageProperty(image,"quantum:format","floating-point"); switch (photometric) { case PHOTOMETRIC_MINISBLACK: { (void) SetImageProperty(image,"tiff:photometric","min-is-black"); break; } case PHOTOMETRIC_MINISWHITE: { (void) SetImageProperty(image,"tiff:photometric","min-is-white"); break; } case PHOTOMETRIC_PALETTE: { (void) SetImageProperty(image,"tiff:photometric","palette"); break; } case PHOTOMETRIC_RGB: { (void) SetImageProperty(image,"tiff:photometric","RGB"); break; } case PHOTOMETRIC_CIELAB: { (void) SetImageProperty(image,"tiff:photometric","CIELAB"); break; } case PHOTOMETRIC_LOGL: { (void) SetImageProperty(image,"tiff:photometric","CIE Log2(L)"); break; } case PHOTOMETRIC_LOGLUV: { (void) SetImageProperty(image,"tiff:photometric","LOGLUV"); break; } #if defined(PHOTOMETRIC_MASK) case PHOTOMETRIC_MASK: { (void) SetImageProperty(image,"tiff:photometric","MASK"); break; } #endif case PHOTOMETRIC_SEPARATED: { (void) SetImageProperty(image,"tiff:photometric","separated"); break; } case PHOTOMETRIC_YCBCR: { (void) SetImageProperty(image,"tiff:photometric","YCBCR"); break; } default: { (void) SetImageProperty(image,"tiff:photometric","unknown"); break; } } if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Geometry: %ux%u", (unsigned int) width,(unsigned int) height); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Interlace: %u", interlace); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Bits per sample: %u",bits_per_sample); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Min sample value: %u",min_sample_value); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Max sample value: %u",max_sample_value); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Photometric " "interpretation: %s",GetImageProperty(image,"tiff:photometric")); } image->columns=(size_t) width; image->rows=(size_t) height; image->depth=(size_t) bits_per_sample; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Image depth: %.20g", (double) image->depth); image->endian=MSBEndian; if (endian == FILLORDER_LSB2MSB) image->endian=LSBEndian; #if defined(MAGICKCORE_HAVE_TIFFISBIGENDIAN) if (TIFFIsBigEndian(tiff) == 0) { (void) SetImageProperty(image,"tiff:endian","lsb"); image->endian=LSBEndian; } else { (void) SetImageProperty(image,"tiff:endian","msb"); image->endian=MSBEndian; } #endif if ((photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) SetImageColorspace(image,GRAYColorspace); if (photometric == PHOTOMETRIC_SEPARATED) SetImageColorspace(image,CMYKColorspace); if (photometric == PHOTOMETRIC_CIELAB) SetImageColorspace(image,LabColorspace); TIFFGetProfiles(tiff,image,image_info->ping); TIFFGetProperties(tiff,image); option=GetImageOption(image_info,"tiff:exif-properties"); if ((option == (const char *) NULL) || (IsMagickTrue(option) != MagickFalse)) TIFFGetEXIFProperties(tiff,image); if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XRESOLUTION,&x_resolution) == 1) && (TIFFGetFieldDefaulted(tiff,TIFFTAG_YRESOLUTION,&y_resolution) == 1)) { image->x_resolution=x_resolution; image->y_resolution=y_resolution; } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_RESOLUTIONUNIT,&units) == 1) { if (units == RESUNIT_INCH) image->units=PixelsPerInchResolution; if (units == RESUNIT_CENTIMETER) image->units=PixelsPerCentimeterResolution; } if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XPOSITION,&x_position) == 1) && (TIFFGetFieldDefaulted(tiff,TIFFTAG_YPOSITION,&y_position) == 1)) { image->page.x=(ssize_t) ceil(x_position*image->x_resolution-0.5); image->page.y=(ssize_t) ceil(y_position*image->y_resolution-0.5); } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_ORIENTATION,&orientation) == 1) image->orientation=(OrientationType) orientation; if (TIFFGetField(tiff,TIFFTAG_WHITEPOINT,&chromaticity) == 1) { if (chromaticity != (float *) NULL) { image->chromaticity.white_point.x=chromaticity[0]; image->chromaticity.white_point.y=chromaticity[1]; } } if (TIFFGetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,&chromaticity) == 1) { if (chromaticity != (float *) NULL) { image->chromaticity.red_primary.x=chromaticity[0]; image->chromaticity.red_primary.y=chromaticity[1]; image->chromaticity.green_primary.x=chromaticity[2]; image->chromaticity.green_primary.y=chromaticity[3]; image->chromaticity.blue_primary.x=chromaticity[4]; image->chromaticity.blue_primary.y=chromaticity[5]; } } #if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919) if ((compress_tag != COMPRESSION_NONE) && (TIFFIsCODECConfigured(compress_tag) == 0)) { TIFFClose(tiff); ThrowReaderException(CoderError,"CompressNotSupported"); } #endif switch (compress_tag) { case COMPRESSION_NONE: image->compression=NoCompression; break; case COMPRESSION_CCITTFAX3: image->compression=FaxCompression; break; case COMPRESSION_CCITTFAX4: image->compression=Group4Compression; break; case COMPRESSION_JPEG: { image->compression=JPEGCompression; #if defined(JPEG_SUPPORT) { char sampling_factor[MaxTextExtent]; int tiff_status; uint16 horizontal, vertical; tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_YCBCRSUBSAMPLING, &horizontal,&vertical); if (tiff_status == 1) { (void) FormatLocaleString(sampling_factor,MaxTextExtent,"%dx%d", horizontal,vertical); (void) SetImageProperty(image,"jpeg:sampling-factor", sampling_factor); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Sampling Factors: %s",sampling_factor); } } #endif break; } case COMPRESSION_OJPEG: image->compression=JPEGCompression; break; #if defined(COMPRESSION_LZMA) case COMPRESSION_LZMA: image->compression=LZMACompression; break; #endif case COMPRESSION_LZW: image->compression=LZWCompression; break; case COMPRESSION_DEFLATE: image->compression=ZipCompression; break; case COMPRESSION_ADOBE_DEFLATE: image->compression=ZipCompression; break; default: image->compression=RLECompression; break; } /* Allocate memory for the image and pixel buffer. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } if (sample_format == SAMPLEFORMAT_UINT) status=SetQuantumFormat(image,quantum_info,UnsignedQuantumFormat); if (sample_format == SAMPLEFORMAT_INT) status=SetQuantumFormat(image,quantum_info,SignedQuantumFormat); if (sample_format == SAMPLEFORMAT_IEEEFP) status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) { TIFFClose(tiff); quantum_info=DestroyQuantumInfo(quantum_info); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } status=MagickTrue; switch (photometric) { case PHOTOMETRIC_MINISBLACK: { quantum_info->min_is_white=MagickFalse; break; } case PHOTOMETRIC_MINISWHITE: { quantum_info->min_is_white=MagickTrue; break; } default: break; } tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_EXTRASAMPLES,&extra_samples, &sample_info); if (tiff_status == 1) { (void) SetImageProperty(image,"tiff:alpha","unspecified"); if (extra_samples == 0) { if ((samples_per_pixel == 4) && (photometric == PHOTOMETRIC_RGB)) image->matte=MagickTrue; } else for (i=0; i < extra_samples; i++) { image->matte=MagickTrue; if (sample_info[i] == EXTRASAMPLE_ASSOCALPHA) { SetQuantumAlphaType(quantum_info,DisassociatedQuantumAlpha); (void) SetImageProperty(image,"tiff:alpha","associated"); } else if (sample_info[i] == EXTRASAMPLE_UNASSALPHA) (void) SetImageProperty(image,"tiff:alpha","unassociated"); } } if ((photometric == PHOTOMETRIC_PALETTE) && (pow(2.0,1.0*bits_per_sample) <= MaxColormapSize)) { size_t colors; colors=(size_t) GetQuantumRange(bits_per_sample)+1; if (AcquireImageColormap(image,colors) == MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_PAGENUMBER,&value,&pages) == 1) image->scene=value; if (image->storage_class == PseudoClass) { int tiff_status; size_t range; uint16 *blue_colormap, *green_colormap, *red_colormap; /* Initialize colormap. */ tiff_status=TIFFGetField(tiff,TIFFTAG_COLORMAP,&red_colormap, &green_colormap,&blue_colormap); if (tiff_status == 1) { if ((red_colormap != (uint16 *) NULL) && (green_colormap != (uint16 *) NULL) && (blue_colormap != (uint16 *) NULL)) { range=255; /* might be old style 8-bit colormap */ for (i=0; i < (ssize_t) image->colors; i++) if ((red_colormap[i] >= 256) || (green_colormap[i] >= 256) || (blue_colormap[i] >= 256)) { range=65535; break; } for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=ClampToQuantum(((double) QuantumRange*red_colormap[i])/range); image->colormap[i].green=ClampToQuantum(((double) QuantumRange*green_colormap[i])/range); image->colormap[i].blue=ClampToQuantum(((double) QuantumRange*blue_colormap[i])/range); } } } if (image->matte == MagickFalse) image->depth=GetImageDepth(image,exception); } if (image_info->ping != MagickFalse) { if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) { quantum_info=DestroyQuantumInfo(quantum_info); break; } goto next_tiff_frame; } method=ReadGenericMethod; if (TIFFGetField(tiff,TIFFTAG_ROWSPERSTRIP,&rows_per_strip) == 1) { char value[MaxTextExtent]; method=ReadStripMethod; (void) FormatLocaleString(value,MaxTextExtent,"%u",(unsigned int) rows_per_strip); (void) SetImageProperty(image,"tiff:rows-per-strip",value); } if ((samples_per_pixel >= 2) && (interlace == PLANARCONFIG_CONTIG)) method=ReadRGBAMethod; if ((samples_per_pixel >= 2) && (interlace == PLANARCONFIG_SEPARATE)) method=ReadCMYKAMethod; if ((photometric != PHOTOMETRIC_RGB) && (photometric != PHOTOMETRIC_CIELAB) && (photometric != PHOTOMETRIC_SEPARATED)) method=ReadGenericMethod; if (image->storage_class == PseudoClass) method=ReadSingleSampleMethod; if ((photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) method=ReadSingleSampleMethod; if ((photometric != PHOTOMETRIC_SEPARATED) && (interlace == PLANARCONFIG_SEPARATE) && (bits_per_sample < 64)) method=ReadGenericMethod; if (image->compression == JPEGCompression) method=GetJPEGMethod(image,tiff,photometric,bits_per_sample, samples_per_pixel); if (compress_tag == COMPRESSION_JBIG) method=ReadStripMethod; if (TIFFIsTiled(tiff) != MagickFalse) method=ReadTileMethod; quantum_info->endian=LSBEndian; quantum_type=RGBQuantum; pixels=GetQuantumPixels(quantum_info); switch (method) { case ReadSingleSampleMethod: { /* Convert TIFF image to PseudoClass MIFF image. */ quantum_type=IndexQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0); if (image->matte != MagickFalse) { if (image->storage_class != PseudoClass) { quantum_type=samples_per_pixel == 1 ? AlphaQuantum : GrayAlphaQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0); } else { quantum_type=IndexAlphaQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0); } } else if (image->storage_class != PseudoClass) { quantum_type=GrayQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0); } status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3)); if (status == MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { int status; register PixelPacket *magick_restrict q; status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadRGBAMethod: { /* Convert TIFF image to DirectClass MIFF image. */ pad=(size_t) MagickMax((size_t) samples_per_pixel-3,0); quantum_type=RGBQuantum; if (image->matte != MagickFalse) { quantum_type=RGBAQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0); } if (image->colorspace == CMYKColorspace) { pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0); quantum_type=CMYKQuantum; if (image->matte != MagickFalse) { quantum_type=CMYKAQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-5,0); } } status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3)); if (status == MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { int status; register PixelPacket *magick_restrict q; status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadCMYKAMethod: { /* Convert TIFF image to DirectClass MIFF image. */ for (i=0; i < (ssize_t) samples_per_pixel; i++) { for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; int status; status=TIFFReadPixels(tiff,bits_per_sample,(tsample_t) i,y,(char *) pixels); if (status == -1) break; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; if (image->colorspace != CMYKColorspace) switch (i) { case 0: quantum_type=RedQuantum; break; case 1: quantum_type=GreenQuantum; break; case 2: quantum_type=BlueQuantum; break; case 3: quantum_type=AlphaQuantum; break; default: quantum_type=UndefinedQuantum; break; } else switch (i) { case 0: quantum_type=CyanQuantum; break; case 1: quantum_type=MagentaQuantum; break; case 2: quantum_type=YellowQuantum; break; case 3: quantum_type=BlackQuantum; break; case 4: quantum_type=AlphaQuantum; break; default: quantum_type=UndefinedQuantum; break; } (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadYCCKMethod: { pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { int status; register IndexPacket *indexes; register PixelPacket *magick_restrict q; register ssize_t x; unsigned char *p; status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); p=pixels; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelCyan(q,ScaleCharToQuantum(ClampYCC((double) *p+ (1.402*(double) *(p+2))-179.456))); SetPixelMagenta(q,ScaleCharToQuantum(ClampYCC((double) *p- (0.34414*(double) *(p+1))-(0.71414*(double ) *(p+2))+ 135.45984))); SetPixelYellow(q,ScaleCharToQuantum(ClampYCC((double) *p+ (1.772*(double) *(p+1))-226.816))); SetPixelBlack(indexes+x,ScaleCharToQuantum((unsigned char)*(p+3))); q++; p+=4; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadStripMethod: { register uint32 *p; /* Convert stripped TIFF image to DirectClass MIFF image. */ i=0; p=(uint32 *) NULL; for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register PixelPacket *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; if (i == 0) { if (TIFFReadRGBAStrip(tiff,(tstrip_t) y,(uint32 *) pixels) == 0) break; i=(ssize_t) MagickMin((ssize_t) rows_per_strip,(ssize_t) image->rows-y); } i--; p=((uint32 *) pixels)+image->columns*i; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) (TIFFGetR(*p)))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) (TIFFGetG(*p)))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) (TIFFGetB(*p)))); if (image->matte != MagickFalse) SetPixelOpacity(q,ScaleCharToQuantum((unsigned char) (TIFFGetA(*p)))); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadTileMethod: { register uint32 *p; uint32 *tile_pixels, columns, rows; /* Convert tiled TIFF image to DirectClass MIFF image. */ if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) != 1) || (TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) != 1)) { TIFFClose(tiff); ThrowReaderException(CoderError,"ImageIsNotTiled"); } (void) SetImageStorageClass(image,DirectClass); number_pixels=(MagickSizeType) columns*rows; if ((number_pixels*sizeof(uint32)) != (MagickSizeType) ((size_t) (number_pixels*sizeof(uint32)))) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } tile_pixels=(uint32 *) AcquireQuantumMemory(number_pixels, sizeof(*tile_pixels)); if (tile_pixels == (uint32 *) NULL) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } for (y=0; y < (ssize_t) image->rows; y+=rows) { PixelPacket *tile; register ssize_t x; register PixelPacket *magick_restrict q; size_t columns_remaining, rows_remaining; rows_remaining=image->rows-y; if ((ssize_t) (y+rows) < (ssize_t) image->rows) rows_remaining=rows; tile=QueueAuthenticPixels(image,0,y,image->columns,rows_remaining, exception); if (tile == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x+=columns) { size_t column, row; if (TIFFReadRGBATile(tiff,(uint32) x,(uint32) y,tile_pixels) == 0) break; columns_remaining=image->columns-x; if ((ssize_t) (x+columns) < (ssize_t) image->columns) columns_remaining=columns; p=tile_pixels+(rows-rows_remaining)*columns; q=tile+(image->columns*(rows_remaining-1)+x); for (row=rows_remaining; row > 0; row--) { if (image->matte != MagickFalse) for (column=columns_remaining; column > 0; column--) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) TIFFGetR(*p))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) TIFFGetG(*p))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) TIFFGetB(*p))); SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) TIFFGetA(*p))); q++; p++; } else for (column=columns_remaining; column > 0; column--) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) TIFFGetR(*p))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) TIFFGetG(*p))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) TIFFGetB(*p))); q++; p++; } p+=columns-columns_remaining; q-=(image->columns+columns_remaining); } } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } tile_pixels=(uint32 *) RelinquishMagickMemory(tile_pixels); break; } case ReadGenericMethod: default: { MemoryInfo *pixel_info; register uint32 *p; uint32 *pixels; /* Convert TIFF image to DirectClass MIFF image. */ number_pixels=(MagickSizeType) image->columns*image->rows; if ((number_pixels*sizeof(uint32)) != (MagickSizeType) ((size_t) (number_pixels*sizeof(uint32)))) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixel_info=AcquireVirtualMemory(image->columns,image->rows* sizeof(uint32)); if (pixel_info == (MemoryInfo *) NULL) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=(uint32 *) GetVirtualMemoryBlob(pixel_info); (void) TIFFReadRGBAImage(tiff,(uint32) image->columns,(uint32) image->rows,(uint32 *) pixels,0); /* Convert image to DirectClass pixel packets. */ p=pixels+number_pixels-1; for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register PixelPacket *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; q+=image->columns-1; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) TIFFGetR(*p))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) TIFFGetG(*p))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) TIFFGetB(*p))); if (image->matte != MagickFalse) SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) TIFFGetA(*p))); p--; q--; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } pixel_info=RelinquishVirtualMemory(pixel_info); break; } } SetQuantumImageType(image,quantum_type); next_tiff_frame: quantum_info=DestroyQuantumInfo(quantum_info); if (photometric == PHOTOMETRIC_CIELAB) DecodeLabImage(image,exception); if ((photometric == PHOTOMETRIC_LOGL) || (photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) { image->type=GrayscaleType; if (bits_per_sample == 1) image->type=BilevelType; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse; if (status != MagickFalse) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,image->scene-1, image->scene); if (status == MagickFalse) break; } } while (status != MagickFalse); TIFFClose(tiff); TIFFReadPhotoshopLayers(image,image_info,exception); if (image_info->number_scenes != 0) { if (image_info->scene >= GetImageListLength(image)) { /* Subimage was not found in the Photoshop layer */ image = DestroyImageList(image); return((Image *)NULL); } } return(GetFirstImageInList(image)); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r T I F F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterTIFFImage() adds properties for the TIFF image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterTIFFImage method is: % % size_t RegisterTIFFImage(void) % */ #if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER) static TIFFExtendProc tag_extender = (TIFFExtendProc) NULL; static void TIFFIgnoreTags(TIFF *tiff) { char *q; const char *p, *tags; Image *image; register ssize_t i; size_t count; TIFFFieldInfo *ignore; if (TIFFGetReadProc(tiff) != TIFFReadBlob) return; image=(Image *)TIFFClientdata(tiff); tags=GetImageArtifact(image,"tiff:ignore-tags"); if (tags == (const char *) NULL) return; count=0; p=tags; while (*p != '\0') { while ((isspace((int) ((unsigned char) *p)) != 0)) p++; (void) strtol(p,&q,10); if (p == q) return; p=q; count++; while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) p++; } if (count == 0) return; i=0; p=tags; ignore=(TIFFFieldInfo *) AcquireQuantumMemory(count,sizeof(*ignore)); /* This also sets field_bit to 0 (FIELD_IGNORE) */ ResetMagickMemory(ignore,0,count*sizeof(*ignore)); while (*p != '\0') { while ((isspace((int) ((unsigned char) *p)) != 0)) p++; ignore[i].field_tag=(ttag_t) strtol(p,&q,10); p=q; i++; while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) p++; } (void) TIFFMergeFieldInfo(tiff,ignore,(uint32) count); ignore=(TIFFFieldInfo *) RelinquishMagickMemory(ignore); } static void TIFFTagExtender(TIFF *tiff) { static const TIFFFieldInfo TIFFExtensions[] = { { 37724, -3, -3, TIFF_UNDEFINED, FIELD_CUSTOM, 1, 1, (char *) "PhotoshopLayerData" }, { 34118, -3, -3, TIFF_UNDEFINED, FIELD_CUSTOM, 1, 1, (char *) "Microscope" } }; TIFFMergeFieldInfo(tiff,TIFFExtensions,sizeof(TIFFExtensions)/ sizeof(*TIFFExtensions)); if (tag_extender != (TIFFExtendProc) NULL) (*tag_extender)(tiff); TIFFIgnoreTags(tiff); } #endif ModuleExport size_t RegisterTIFFImage(void) { #define TIFFDescription "Tagged Image File Format" char version[MaxTextExtent]; MagickInfo *entry; if (tiff_semaphore == (SemaphoreInfo *) NULL) ActivateSemaphoreInfo(&tiff_semaphore); LockSemaphoreInfo(tiff_semaphore); if (instantiate_key == MagickFalse) { if (CreateMagickThreadKey(&tiff_exception,NULL) == MagickFalse) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); error_handler=TIFFSetErrorHandler(TIFFErrors); warning_handler=TIFFSetWarningHandler(TIFFWarnings); #if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER) if (tag_extender == (TIFFExtendProc) NULL) tag_extender=TIFFSetTagExtender(TIFFTagExtender); #endif instantiate_key=MagickTrue; } UnlockSemaphoreInfo(tiff_semaphore); *version='\0'; #if defined(TIFF_VERSION) (void) FormatLocaleString(version,MaxTextExtent,"%d",TIFF_VERSION); #endif #if defined(MAGICKCORE_TIFF_DELEGATE) { const char *p; register ssize_t i; p=TIFFGetVersion(); for (i=0; (i < (MaxTextExtent-1)) && (*p != 0) && (*p != '\n'); i++) version[i]=(*p++); version[i]='\0'; } #endif entry=SetMagickInfo("GROUP4"); #if defined(MAGICKCORE_TIFF_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadGROUP4Image; entry->encoder=(EncodeImageHandler *) WriteGROUP4Image; #endif entry->raw=MagickTrue; entry->endian_support=MagickTrue; entry->adjoin=MagickFalse; entry->format_type=ImplicitFormatType; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Raw CCITT Group4"); entry->mime_type=ConstantString("image/tiff"); entry->module=ConstantString("TIFF"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PTIF"); #if defined(MAGICKCORE_TIFF_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadTIFFImage; entry->encoder=(EncodeImageHandler *) WritePTIFImage; #endif entry->endian_support=MagickTrue; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Pyramid encoded TIFF"); entry->mime_type=ConstantString("image/tiff"); entry->module=ConstantString("TIFF"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("TIF"); #if defined(MAGICKCORE_TIFF_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadTIFFImage; entry->encoder=(EncodeImageHandler *) WriteTIFFImage; #endif entry->endian_support=MagickTrue; entry->seekable_stream=MagickTrue; entry->stealth=MagickTrue; entry->description=ConstantString(TIFFDescription); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/tiff"); entry->module=ConstantString("TIFF"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("TIFF"); #if defined(MAGICKCORE_TIFF_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadTIFFImage; entry->encoder=(EncodeImageHandler *) WriteTIFFImage; #endif entry->magick=(IsImageFormatHandler *) IsTIFF; entry->endian_support=MagickTrue; entry->seekable_stream=MagickTrue; entry->description=ConstantString(TIFFDescription); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/tiff"); entry->module=ConstantString("TIFF"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("TIFF64"); #if defined(TIFF_VERSION_BIG) entry->decoder=(DecodeImageHandler *) ReadTIFFImage; entry->encoder=(EncodeImageHandler *) WriteTIFFImage; #endif entry->adjoin=MagickFalse; entry->endian_support=MagickTrue; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Tagged Image File Format (64-bit)"); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/tiff"); entry->module=ConstantString("TIFF"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r T I F F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterTIFFImage() removes format registrations made by the TIFF module % from the list of supported formats. % % The format of the UnregisterTIFFImage method is: % % UnregisterTIFFImage(void) % */ ModuleExport void UnregisterTIFFImage(void) { (void) UnregisterMagickInfo("TIFF64"); (void) UnregisterMagickInfo("TIFF"); (void) UnregisterMagickInfo("TIF"); (void) UnregisterMagickInfo("PTIF"); if (tiff_semaphore == (SemaphoreInfo *) NULL) ActivateSemaphoreInfo(&tiff_semaphore); LockSemaphoreInfo(tiff_semaphore); if (instantiate_key != MagickFalse) { if (DeleteMagickThreadKey(tiff_exception) == MagickFalse) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); #if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER) if (tag_extender == (TIFFExtendProc) NULL) (void) TIFFSetTagExtender(tag_extender); #endif (void) TIFFSetWarningHandler(warning_handler); (void) TIFFSetErrorHandler(error_handler); instantiate_key=MagickFalse; } UnlockSemaphoreInfo(tiff_semaphore); DestroySemaphoreInfo(&tiff_semaphore); } #if defined(MAGICKCORE_TIFF_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e G R O U P 4 I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteGROUP4Image() writes an image in the raw CCITT Group 4 image format. % % The format of the WriteGROUP4Image method is: % % MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info, % Image *image) % % A description of each parameter follows: % % o image_info: the image info. % % o image: The image. % */ static MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info, Image *image) { char filename[MaxTextExtent]; FILE *file; Image *huffman_image; ImageInfo *write_info; int unique_file; MagickBooleanType status; register ssize_t i; ssize_t count; TIFF *tiff; toff_t *byte_count, strip_size; unsigned char *buffer; /* Write image as CCITT Group4 TIFF image to a temporary file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == 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); huffman_image=CloneImage(image,0,0,MagickTrue,&image->exception); if (huffman_image == (Image *) NULL) { (void) CloseBlob(image); return(MagickFalse); } huffman_image->endian=MSBEndian; file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); if (unique_file != -1) file=fdopen(unique_file,"wb"); if ((unique_file == -1) || (file == (FILE *) NULL)) { ThrowFileException(&image->exception,FileOpenError, "UnableToCreateTemporaryFile",filename); return(MagickFalse); } (void) FormatLocaleString(huffman_image->filename,MaxTextExtent,"tiff:%s", filename); (void) SetImageType(huffman_image,BilevelType); write_info=CloneImageInfo((ImageInfo *) NULL); SetImageInfoFile(write_info,file); (void) SetImageType(image,BilevelType); (void) SetImageDepth(image,1); write_info->compression=Group4Compression; write_info->type=BilevelType; (void) SetImageOption(write_info,"quantum:polarity","min-is-white"); status=WriteTIFFImage(write_info,huffman_image); (void) fflush(file); write_info=DestroyImageInfo(write_info); if (status == MagickFalse) { InheritException(&image->exception,&huffman_image->exception); huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); return(MagickFalse); } tiff=TIFFOpen(filename,"rb"); if (tiff == (TIFF *) NULL) { huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); ThrowFileException(&image->exception,FileOpenError,"UnableToOpenFile", image_info->filename); return(MagickFalse); } /* Allocate raw strip buffer. */ if (TIFFGetField(tiff,TIFFTAG_STRIPBYTECOUNTS,&byte_count) != 1) { TIFFClose(tiff); huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); return(MagickFalse); } strip_size=byte_count[0]; for (i=1; i < (ssize_t) TIFFNumberOfStrips(tiff); i++) if (byte_count[i] > strip_size) strip_size=byte_count[i]; buffer=(unsigned char *) AcquireQuantumMemory((size_t) strip_size, sizeof(*buffer)); if (buffer == (unsigned char *) NULL) { TIFFClose(tiff); huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image_info->filename); } /* Compress runlength encoded to 2D Huffman pixels. */ for (i=0; i < (ssize_t) TIFFNumberOfStrips(tiff); i++) { count=(ssize_t) TIFFReadRawStrip(tiff,(uint32) i,buffer,strip_size); if (WriteBlob(image,(size_t) count,buffer) != count) status=MagickFalse; } buffer=(unsigned char *) RelinquishMagickMemory(buffer); TIFFClose(tiff); huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); (void) CloseBlob(image); return(status); } #endif #if defined(MAGICKCORE_TIFF_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P T I F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePTIFImage() writes an image in the pyrimid-encoded Tagged image file % format. % % The format of the WritePTIFImage method is: % % MagickBooleanType WritePTIFImage(const ImageInfo *image_info, % Image *image) % % A description of each parameter follows: % % o image_info: the image info. % % o image: The image. % */ static MagickBooleanType WritePTIFImage(const ImageInfo *image_info, Image *image) { ExceptionInfo *exception; Image *images, *next, *pyramid_image; ImageInfo *write_info; MagickBooleanType status; PointInfo resolution; size_t columns, rows; /* Create pyramid-encoded TIFF image. */ exception=(&image->exception); images=NewImageList(); for (next=image; next != (Image *) NULL; next=GetNextImageInList(next)) { Image *clone_image; clone_image=CloneImage(next,0,0,MagickFalse,exception); if (clone_image == (Image *) NULL) break; clone_image->previous=NewImageList(); clone_image->next=NewImageList(); (void) SetImageProperty(clone_image,"tiff:subfiletype","none"); AppendImageToList(&images,clone_image); columns=next->columns; rows=next->rows; resolution.x=next->x_resolution; resolution.y=next->y_resolution; while ((columns > 64) && (rows > 64)) { columns/=2; rows/=2; resolution.x/=2.0; resolution.y/=2.0; pyramid_image=ResizeImage(next,columns,rows,image->filter,image->blur, exception); if (pyramid_image == (Image *) NULL) break; pyramid_image->x_resolution=resolution.x; pyramid_image->y_resolution=resolution.y; (void) SetImageProperty(pyramid_image,"tiff:subfiletype","REDUCEDIMAGE"); AppendImageToList(&images,pyramid_image); } } /* Write pyramid-encoded TIFF image. */ write_info=CloneImageInfo(image_info); write_info->adjoin=MagickTrue; status=WriteTIFFImage(write_info,GetFirstImageInList(images)); images=DestroyImageList(images); write_info=DestroyImageInfo(write_info); return(status); } #endif #if defined(MAGICKCORE_TIFF_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % W r i t e T I F F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteTIFFImage() writes an image in the Tagged image file format. % % The format of the WriteTIFFImage method is: % % MagickBooleanType WriteTIFFImage(const ImageInfo *image_info, % Image *image) % % A description of each parameter follows: % % o image_info: the image info. % % o image: The image. % */ typedef struct _TIFFInfo { RectangleInfo tile_geometry; unsigned char *scanline, *scanlines, *pixels; } TIFFInfo; static void DestroyTIFFInfo(TIFFInfo *tiff_info) { assert(tiff_info != (TIFFInfo *) NULL); if (tiff_info->scanlines != (unsigned char *) NULL) tiff_info->scanlines=(unsigned char *) RelinquishMagickMemory( tiff_info->scanlines); if (tiff_info->pixels != (unsigned char *) NULL) tiff_info->pixels=(unsigned char *) RelinquishMagickMemory( tiff_info->pixels); } static MagickBooleanType EncodeLabImage(Image *image,ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; ssize_t y; status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double a, b; a=QuantumScale*GetPixela(q)-0.5; if (a < 0.0) a+=1.0; b=QuantumScale*GetPixelb(q)-0.5; if (b < 0.0) b+=1.0; SetPixela(q,QuantumRange*a); SetPixelb(q,QuantumRange*b); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status); } static MagickBooleanType GetTIFFInfo(const ImageInfo *image_info,TIFF *tiff, TIFFInfo *tiff_info) { const char *option; MagickStatusType flags; uint32 tile_columns, tile_rows; assert(tiff_info != (TIFFInfo *) NULL); (void) ResetMagickMemory(tiff_info,0,sizeof(*tiff_info)); option=GetImageOption(image_info,"tiff:tile-geometry"); if (option == (const char *) NULL) return(MagickTrue); flags=ParseAbsoluteGeometry(option,&tiff_info->tile_geometry); if ((flags & HeightValue) == 0) tiff_info->tile_geometry.height=tiff_info->tile_geometry.width; tile_columns=(uint32) tiff_info->tile_geometry.width; tile_rows=(uint32) tiff_info->tile_geometry.height; TIFFDefaultTileSize(tiff,&tile_columns,&tile_rows); (void) TIFFSetField(tiff,TIFFTAG_TILEWIDTH,tile_columns); (void) TIFFSetField(tiff,TIFFTAG_TILELENGTH,tile_rows); tiff_info->tile_geometry.width=tile_columns; tiff_info->tile_geometry.height=tile_rows; tiff_info->scanlines=(unsigned char *) AcquireQuantumMemory((size_t) tile_rows*TIFFScanlineSize(tiff),sizeof(*tiff_info->scanlines)); tiff_info->pixels=(unsigned char *) AcquireQuantumMemory((size_t) tile_rows*TIFFTileSize(tiff),sizeof(*tiff_info->scanlines)); if ((tiff_info->scanlines == (unsigned char *) NULL) || (tiff_info->pixels == (unsigned char *) NULL)) { DestroyTIFFInfo(tiff_info); return(MagickFalse); } return(MagickTrue); } static int32 TIFFWritePixels(TIFF *tiff,TIFFInfo *tiff_info,ssize_t row, tsample_t sample,Image *image) { int32 status; register ssize_t i; register unsigned char *p, *q; size_t number_tiles, tile_width; ssize_t bytes_per_pixel, j, k, l; if (TIFFIsTiled(tiff) == 0) return(TIFFWriteScanline(tiff,tiff_info->scanline,(uint32) row,sample)); /* Fill scanlines to tile height. */ i=(ssize_t) (row % tiff_info->tile_geometry.height)*TIFFScanlineSize(tiff); (void) CopyMagickMemory(tiff_info->scanlines+i,(char *) tiff_info->scanline, (size_t) TIFFScanlineSize(tiff)); if (((size_t) (row % tiff_info->tile_geometry.height) != (tiff_info->tile_geometry.height-1)) && (row != (ssize_t) (image->rows-1))) return(0); /* Write tile to TIFF image. */ status=0; bytes_per_pixel=TIFFTileSize(tiff)/(ssize_t) (tiff_info->tile_geometry.height* tiff_info->tile_geometry.width); number_tiles=(image->columns+tiff_info->tile_geometry.width)/ tiff_info->tile_geometry.width; for (i=0; i < (ssize_t) number_tiles; i++) { tile_width=(i == (ssize_t) (number_tiles-1)) ? image->columns-(i* tiff_info->tile_geometry.width) : tiff_info->tile_geometry.width; for (j=0; j < (ssize_t) ((row % tiff_info->tile_geometry.height)+1); j++) for (k=0; k < (ssize_t) tile_width; k++) { if (bytes_per_pixel == 0) { p=tiff_info->scanlines+(j*TIFFScanlineSize(tiff)+(i* tiff_info->tile_geometry.width+k)/8); q=tiff_info->pixels+(j*TIFFTileRowSize(tiff)+k/8); *q++=(*p++); continue; } p=tiff_info->scanlines+(j*TIFFScanlineSize(tiff)+(i* tiff_info->tile_geometry.width+k)*bytes_per_pixel); q=tiff_info->pixels+(j*TIFFTileRowSize(tiff)+k*bytes_per_pixel); for (l=0; l < bytes_per_pixel; l++) *q++=(*p++); } if ((i*tiff_info->tile_geometry.width) != image->columns) status=TIFFWriteTile(tiff,tiff_info->pixels,(uint32) (i* tiff_info->tile_geometry.width),(uint32) ((row/ tiff_info->tile_geometry.height)*tiff_info->tile_geometry.height),0, sample); if (status < 0) break; } return(status); } static void TIFFSetProfiles(TIFF *tiff,Image *image) { const char *name; const StringInfo *profile; if (image->profiles == (void *) NULL) return; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (GetStringInfoLength(profile) == 0) { name=GetNextImageProfile(image); continue; } #if defined(TIFFTAG_XMLPACKET) if (LocaleCompare(name,"xmp") == 0) (void) TIFFSetField(tiff,TIFFTAG_XMLPACKET,(uint32) GetStringInfoLength( profile),GetStringInfoDatum(profile)); #endif #if defined(TIFFTAG_ICCPROFILE) if (LocaleCompare(name,"icc") == 0) (void) TIFFSetField(tiff,TIFFTAG_ICCPROFILE,(uint32) GetStringInfoLength( profile),GetStringInfoDatum(profile)); #endif if (LocaleCompare(name,"iptc") == 0) { size_t length; StringInfo *iptc_profile; iptc_profile=CloneStringInfo(profile); length=GetStringInfoLength(profile)+4-(GetStringInfoLength(profile) & 0x03); SetStringInfoLength(iptc_profile,length); if (TIFFIsByteSwapped(tiff)) TIFFSwabArrayOfLong((uint32 *) GetStringInfoDatum(iptc_profile), (unsigned long) (length/4)); (void) TIFFSetField(tiff,TIFFTAG_RICHTIFFIPTC,(uint32) GetStringInfoLength(iptc_profile)/4,GetStringInfoDatum(iptc_profile)); iptc_profile=DestroyStringInfo(iptc_profile); } #if defined(TIFFTAG_PHOTOSHOP) if (LocaleCompare(name,"8bim") == 0) (void) TIFFSetField(tiff,TIFFTAG_PHOTOSHOP,(uint32) GetStringInfoLength(profile),GetStringInfoDatum(profile)); #endif if (LocaleCompare(name,"tiff:37724") == 0) (void) TIFFSetField(tiff,37724,(uint32) GetStringInfoLength(profile), GetStringInfoDatum(profile)); if (LocaleCompare(name,"tiff:34118") == 0) (void) TIFFSetField(tiff,34118,(uint32) GetStringInfoLength(profile), GetStringInfoDatum(profile)); name=GetNextImageProfile(image); } } static void TIFFSetProperties(TIFF *tiff,const ImageInfo *image_info, Image *image) { const char *value; value=GetImageArtifact(image,"tiff:document"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_DOCUMENTNAME,value); value=GetImageArtifact(image,"tiff:hostcomputer"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_HOSTCOMPUTER,value); value=GetImageArtifact(image,"tiff:artist"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_ARTIST,value); value=GetImageArtifact(image,"tiff:timestamp"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_DATETIME,value); value=GetImageArtifact(image,"tiff:make"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_MAKE,value); value=GetImageArtifact(image,"tiff:model"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_MODEL,value); value=GetImageArtifact(image,"tiff:software"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_SOFTWARE,value); value=GetImageArtifact(image,"tiff:copyright"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_COPYRIGHT,value); value=GetImageArtifact(image,"kodak-33423"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,33423,value); value=GetImageArtifact(image,"kodak-36867"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,36867,value); value=GetImageProperty(image,"label"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_PAGENAME,value); value=GetImageProperty(image,"comment"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_IMAGEDESCRIPTION,value); value=GetImageArtifact(image,"tiff:subfiletype"); if (value != (const char *) NULL) { if (LocaleCompare(value,"REDUCEDIMAGE") == 0) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE); else if (LocaleCompare(value,"PAGE") == 0) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE); else if (LocaleCompare(value,"MASK") == 0) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_MASK); } else { uint16 page, pages; page=(uint16) image->scene; pages=(uint16) GetImageListLength(image); if ((image_info->adjoin != MagickFalse) && (pages > 1)) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE); (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages); } } static void TIFFSetEXIFProperties(TIFF *tiff,Image *image) { #if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY) const char *value; register ssize_t i; uint32 offset; /* Write EXIF properties. */ offset=0; (void) TIFFSetField(tiff,TIFFTAG_SUBIFD,1,&offset); for (i=0; exif_info[i].tag != 0; i++) { value=GetImageProperty(image,exif_info[i].property); if (value == (const char *) NULL) continue; switch (exif_info[i].type) { case TIFF_ASCII: { (void) TIFFSetField(tiff,exif_info[i].tag,value); break; } case TIFF_SHORT: { uint16 field; field=(uint16) StringToLong(value); (void) TIFFSetField(tiff,exif_info[i].tag,field); break; } case TIFF_LONG: { uint16 field; field=(uint16) StringToLong(value); (void) TIFFSetField(tiff,exif_info[i].tag,field); break; } case TIFF_RATIONAL: case TIFF_SRATIONAL: { float field; field=StringToDouble(value,(char **) NULL); (void) TIFFSetField(tiff,exif_info[i].tag,field); break; } default: break; } } /* (void) TIFFSetField(tiff,TIFFTAG_EXIFIFD,offset); */ #else (void) tiff; (void) image; #endif } static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info, Image *image) { #if !defined(TIFFDefaultStripSize) #define TIFFDefaultStripSize(tiff,request) (8192UL/TIFFScanlineSize(tiff)) #endif const char *mode, *option; CompressionType compression; EndianType endian_type; MagickBooleanType debug, status; MagickOffsetType scene; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; ssize_t y; TIFF *tiff; TIFFInfo tiff_info; uint16 bits_per_sample, compress_tag, endian, photometric; uint32 rows_per_strip; unsigned char *pixels; /* Open TIFF file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); (void) SetMagickThreadValue(tiff_exception,&image->exception); endian_type=UndefinedEndian; option=GetImageOption(image_info,"tiff:endian"); if (option != (const char *) NULL) { if (LocaleNCompare(option,"msb",3) == 0) endian_type=MSBEndian; if (LocaleNCompare(option,"lsb",3) == 0) endian_type=LSBEndian;; } switch (endian_type) { case LSBEndian: mode="wl"; break; case MSBEndian: mode="wb"; break; default: mode="w"; break; } #if defined(TIFF_VERSION_BIG) if (LocaleCompare(image_info->magick,"TIFF64") == 0) switch (endian_type) { case LSBEndian: mode="wl8"; break; case MSBEndian: mode="wb8"; break; default: mode="w8"; break; } #endif tiff=TIFFClientOpen(image->filename,mode,(thandle_t) image,TIFFReadBlob, TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob, TIFFUnmapBlob); if (tiff == (TIFF *) NULL) return(MagickFalse); scene=0; debug=IsEventLogging(); (void) debug; do { /* Initialize TIFF fields. */ if ((image_info->type != UndefinedType) && (image_info->type != OptimizeType)) (void) SetImageType(image,image_info->type); compression=UndefinedCompression; if (image->compression != JPEGCompression) compression=image->compression; if (image_info->compression != UndefinedCompression) compression=image_info->compression; switch (compression) { case FaxCompression: case Group4Compression: { (void) SetImageType(image,BilevelType); (void) SetImageDepth(image,1); break; } case JPEGCompression: { (void) SetImageStorageClass(image,DirectClass); (void) SetImageDepth(image,8); break; } default: break; } quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if ((image->storage_class != PseudoClass) && (image->depth >= 32) && (quantum_info->format == UndefinedQuantumFormat) && (IsHighDynamicRangeImage(image,&image->exception) != MagickFalse)) { status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } if ((LocaleCompare(image_info->magick,"PTIF") == 0) && (GetPreviousImageInList(image) != (Image *) NULL)) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE); if ((image->columns != (uint32) image->columns) || (image->rows != (uint32) image->rows)) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); (void) TIFFSetField(tiff,TIFFTAG_IMAGELENGTH,(uint32) image->rows); (void) TIFFSetField(tiff,TIFFTAG_IMAGEWIDTH,(uint32) image->columns); switch (compression) { case FaxCompression: { compress_tag=COMPRESSION_CCITTFAX3; SetQuantumMinIsWhite(quantum_info,MagickTrue); break; } case Group4Compression: { compress_tag=COMPRESSION_CCITTFAX4; SetQuantumMinIsWhite(quantum_info,MagickTrue); break; } #if defined(COMPRESSION_JBIG) case JBIG1Compression: { compress_tag=COMPRESSION_JBIG; break; } #endif case JPEGCompression: { compress_tag=COMPRESSION_JPEG; break; } #if defined(COMPRESSION_LZMA) case LZMACompression: { compress_tag=COMPRESSION_LZMA; break; } #endif case LZWCompression: { compress_tag=COMPRESSION_LZW; break; } case RLECompression: { compress_tag=COMPRESSION_PACKBITS; break; } case ZipCompression: { compress_tag=COMPRESSION_ADOBE_DEFLATE; break; } case NoCompression: default: { compress_tag=COMPRESSION_NONE; break; } } #if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919) if ((compress_tag != COMPRESSION_NONE) && (TIFFIsCODECConfigured(compress_tag) == 0)) { (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"CompressionNotSupported","`%s'",CommandOptionToMnemonic( MagickCompressOptions,(ssize_t) compression)); compress_tag=COMPRESSION_NONE; } #else switch (compress_tag) { #if defined(CCITT_SUPPORT) case COMPRESSION_CCITTFAX3: case COMPRESSION_CCITTFAX4: #endif #if defined(YCBCR_SUPPORT) && defined(JPEG_SUPPORT) case COMPRESSION_JPEG: #endif #if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA) case COMPRESSION_LZMA: #endif #if defined(LZW_SUPPORT) case COMPRESSION_LZW: #endif #if defined(PACKBITS_SUPPORT) case COMPRESSION_PACKBITS: #endif #if defined(ZIP_SUPPORT) case COMPRESSION_ADOBE_DEFLATE: #endif case COMPRESSION_NONE: break; default: { (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"CompressionNotSupported","`%s'",CommandOptionToMnemonic( MagickCompressOptions,(ssize_t) compression)); compress_tag=COMPRESSION_NONE; break; } } #endif if (image->colorspace == CMYKColorspace) { photometric=PHOTOMETRIC_SEPARATED; (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,4); (void) TIFFSetField(tiff,TIFFTAG_INKSET,INKSET_CMYK); } else { /* Full color TIFF raster. */ if (image->colorspace == LabColorspace) { photometric=PHOTOMETRIC_CIELAB; EncodeLabImage(image,&image->exception); } else if (image->colorspace == YCbCrColorspace) { photometric=PHOTOMETRIC_YCBCR; (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,1,1); (void) SetImageStorageClass(image,DirectClass); (void) SetImageDepth(image,8); } else photometric=PHOTOMETRIC_RGB; (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,3); if ((image_info->type != TrueColorType) && (image_info->type != TrueColorMatteType)) { if ((image_info->type != PaletteType) && (SetImageGray(image,&image->exception) != MagickFalse)) { photometric=(uint16) (quantum_info->min_is_white != MagickFalse ? PHOTOMETRIC_MINISWHITE : PHOTOMETRIC_MINISBLACK); (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1); if ((image->depth == 1) && (image->matte == MagickFalse)) SetImageMonochrome(image,&image->exception); } else if (image->storage_class == PseudoClass) { size_t depth; /* Colormapped TIFF raster. */ (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1); photometric=PHOTOMETRIC_PALETTE; depth=1; while ((GetQuantumRange(depth)+1) < image->colors) depth<<=1; status=SetQuantumDepth(image,quantum_info,depth); if (status == MagickFalse) ThrowWriterException(ResourceLimitError, "MemoryAllocationFailed"); } } } (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian); if ((compress_tag == COMPRESSION_CCITTFAX3) && (photometric != PHOTOMETRIC_MINISWHITE)) { compress_tag=COMPRESSION_NONE; endian=FILLORDER_MSB2LSB; } else if ((compress_tag == COMPRESSION_CCITTFAX4) && (photometric != PHOTOMETRIC_MINISWHITE)) { compress_tag=COMPRESSION_NONE; endian=FILLORDER_MSB2LSB; } option=GetImageOption(image_info,"tiff:fill-order"); if (option != (const char *) NULL) { if (LocaleNCompare(option,"msb",3) == 0) endian=FILLORDER_MSB2LSB; if (LocaleNCompare(option,"lsb",3) == 0) endian=FILLORDER_LSB2MSB; } (void) TIFFSetField(tiff,TIFFTAG_COMPRESSION,compress_tag); (void) TIFFSetField(tiff,TIFFTAG_FILLORDER,endian); (void) TIFFSetField(tiff,TIFFTAG_BITSPERSAMPLE,quantum_info->depth); if (image->matte != MagickFalse) { uint16 extra_samples, sample_info[1], samples_per_pixel; /* TIFF has a matte channel. */ extra_samples=1; sample_info[0]=EXTRASAMPLE_UNASSALPHA; option=GetImageOption(image_info,"tiff:alpha"); if (option != (const char *) NULL) { if (LocaleCompare(option,"associated") == 0) sample_info[0]=EXTRASAMPLE_ASSOCALPHA; else if (LocaleCompare(option,"unspecified") == 0) sample_info[0]=EXTRASAMPLE_UNSPECIFIED; } (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL, &samples_per_pixel); (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,samples_per_pixel+1); (void) TIFFSetField(tiff,TIFFTAG_EXTRASAMPLES,extra_samples, &sample_info); if (sample_info[0] == EXTRASAMPLE_ASSOCALPHA) SetQuantumAlphaType(quantum_info,AssociatedQuantumAlpha); } (void) TIFFSetField(tiff,TIFFTAG_PHOTOMETRIC,photometric); switch (quantum_info->format) { case FloatingPointQuantumFormat: { (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_IEEEFP); (void) TIFFSetField(tiff,TIFFTAG_SMINSAMPLEVALUE,quantum_info->minimum); (void) TIFFSetField(tiff,TIFFTAG_SMAXSAMPLEVALUE,quantum_info->maximum); break; } case SignedQuantumFormat: { (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_INT); break; } case UnsignedQuantumFormat: { (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_UINT); break; } default: break; } (void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,ORIENTATION_TOPLEFT); (void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_CONTIG); if (photometric == PHOTOMETRIC_RGB) if ((image_info->interlace == PlaneInterlace) || (image_info->interlace == PartitionInterlace)) (void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_SEPARATE); rows_per_strip=TIFFDefaultStripSize(tiff,0); option=GetImageOption(image_info,"tiff:rows-per-strip"); if (option != (const char *) NULL) rows_per_strip=(size_t) strtol(option,(char **) NULL,10); switch (compress_tag) { case COMPRESSION_JPEG: { #if defined(JPEG_SUPPORT) const char *sampling_factor; GeometryInfo geometry_info; MagickStatusType flags; rows_per_strip+=(16-(rows_per_strip % 16)); if (image_info->quality != UndefinedCompressionQuality) (void) TIFFSetField(tiff,TIFFTAG_JPEGQUALITY,image_info->quality); (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RAW); if (IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) { const char *value; (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RGB); sampling_factor=(const char *) NULL; value=GetImageProperty(image,"jpeg:sampling-factor"); if (value != (char *) NULL) { sampling_factor=value; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Input sampling-factors=%s",sampling_factor); } if (image_info->sampling_factor != (char *) NULL) sampling_factor=image_info->sampling_factor; if (sampling_factor != (const char *) NULL) { flags=ParseGeometry(sampling_factor,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=geometry_info.rho; if (image->colorspace == YCbCrColorspace) (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,(uint16) geometry_info.rho,(uint16) geometry_info.sigma); } } (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (bits_per_sample == 12) (void) TIFFSetField(tiff,TIFFTAG_JPEGTABLESMODE,JPEGTABLESMODE_QUANT); #endif break; } case COMPRESSION_ADOBE_DEFLATE: { rows_per_strip=(uint32) image->rows; (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL); (void) TIFFSetField(tiff,TIFFTAG_ZIPQUALITY,(long) ( image_info->quality == UndefinedCompressionQuality ? 7 : MagickMin((ssize_t) image_info->quality/10,9))); break; } case COMPRESSION_CCITTFAX3: { /* Byte-aligned EOL. */ rows_per_strip=(uint32) image->rows; (void) TIFFSetField(tiff,TIFFTAG_GROUP3OPTIONS,4); break; } case COMPRESSION_CCITTFAX4: { rows_per_strip=(uint32) image->rows; break; } #if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA) case COMPRESSION_LZMA: { if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL); (void) TIFFSetField(tiff,TIFFTAG_LZMAPRESET,(long) ( image_info->quality == UndefinedCompressionQuality ? 7 : MagickMin((ssize_t) image_info->quality/10,9))); break; } #endif case COMPRESSION_LZW: { (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL); break; } default: break; } if (rows_per_strip < 1) rows_per_strip=1; if ((image->rows/rows_per_strip) >= (1UL << 15)) rows_per_strip=(uint32) (image->rows >> 15); (void) TIFFSetField(tiff,TIFFTAG_ROWSPERSTRIP,rows_per_strip); if ((image->x_resolution != 0.0) && (image->y_resolution != 0.0)) { unsigned short units; /* Set image resolution. */ units=RESUNIT_NONE; if (image->units == PixelsPerInchResolution) units=RESUNIT_INCH; if (image->units == PixelsPerCentimeterResolution) units=RESUNIT_CENTIMETER; (void) TIFFSetField(tiff,TIFFTAG_RESOLUTIONUNIT,(uint16) units); (void) TIFFSetField(tiff,TIFFTAG_XRESOLUTION,image->x_resolution); (void) TIFFSetField(tiff,TIFFTAG_YRESOLUTION,image->y_resolution); if ((image->page.x < 0) || (image->page.y < 0)) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"TIFF: negative image positions unsupported","%s", image->filename); if ((image->page.x > 0) && (image->x_resolution > 0.0)) { /* Set horizontal image position. */ (void) TIFFSetField(tiff,TIFFTAG_XPOSITION,(float) image->page.x/ image->x_resolution); } if ((image->page.y > 0) && (image->y_resolution > 0.0)) { /* Set vertical image position. */ (void) TIFFSetField(tiff,TIFFTAG_YPOSITION,(float) image->page.y/ image->y_resolution); } } if (image->chromaticity.white_point.x != 0.0) { float chromaticity[6]; /* Set image chromaticity. */ chromaticity[0]=(float) image->chromaticity.red_primary.x; chromaticity[1]=(float) image->chromaticity.red_primary.y; chromaticity[2]=(float) image->chromaticity.green_primary.x; chromaticity[3]=(float) image->chromaticity.green_primary.y; chromaticity[4]=(float) image->chromaticity.blue_primary.x; chromaticity[5]=(float) image->chromaticity.blue_primary.y; (void) TIFFSetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,chromaticity); chromaticity[0]=(float) image->chromaticity.white_point.x; chromaticity[1]=(float) image->chromaticity.white_point.y; (void) TIFFSetField(tiff,TIFFTAG_WHITEPOINT,chromaticity); } if ((LocaleCompare(image_info->magick,"PTIF") != 0) && (image_info->adjoin != MagickFalse) && (GetImageListLength(image) > 1)) { (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE); if (image->scene != 0) (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,(uint16) image->scene, GetImageListLength(image)); } if (image->orientation != UndefinedOrientation) (void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,(uint16) image->orientation); (void) TIFFSetProfiles(tiff,image); { uint16 page, pages; page=(uint16) scene; pages=(uint16) GetImageListLength(image); if ((LocaleCompare(image_info->magick,"PTIF") != 0) && (image_info->adjoin != MagickFalse) && (pages > 1)) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE); (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages); } (void) TIFFSetProperties(tiff,image_info,image); DisableMSCWarning(4127) if (0) RestoreMSCWarning (void) TIFFSetEXIFProperties(tiff,image); /* Write image scanlines. */ if (GetTIFFInfo(image_info,tiff,&tiff_info) == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); quantum_info->endian=LSBEndian; pixels=GetQuantumPixels(quantum_info); tiff_info.scanline=GetQuantumPixels(quantum_info); switch (photometric) { case PHOTOMETRIC_CIELAB: case PHOTOMETRIC_YCBCR: case PHOTOMETRIC_RGB: { /* RGB TIFF image. */ switch (image_info->interlace) { case NoInterlace: default: { quantum_type=RGBQuantum; if (image->matte != MagickFalse) quantum_type=RGBAQuantum; for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,quantum_type,pixels,&image->exception); if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } break; } case PlaneInterlace: case PartitionInterlace: { /* Plane interlacing: RRRRRR...GGGGGG...BBBBBB... */ for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RedQuantum,pixels,&image->exception); if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,100,400); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GreenQuantum,pixels,&image->exception); if (TIFFWritePixels(tiff,&tiff_info,y,1,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,200,400); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,BlueQuantum,pixels,&image->exception); if (TIFFWritePixels(tiff,&tiff_info,y,2,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,300,400); if (status == MagickFalse) break; } if (image->matte != MagickFalse) for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,AlphaQuantum,pixels,&image->exception); if (TIFFWritePixels(tiff,&tiff_info,y,3,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,400,400); if (status == MagickFalse) break; } break; } } break; } case PHOTOMETRIC_SEPARATED: { /* CMYK TIFF image. */ quantum_type=CMYKQuantum; if (image->matte != MagickFalse) quantum_type=CMYKAQuantum; if (image->colorspace != CMYKColorspace) (void) TransformImageColorspace(image,CMYKColorspace); for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,quantum_type,pixels,&image->exception); if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case PHOTOMETRIC_PALETTE: { uint16 *blue, *green, *red; /* Colormapped TIFF image. */ red=(uint16 *) AcquireQuantumMemory(65536,sizeof(*red)); green=(uint16 *) AcquireQuantumMemory(65536,sizeof(*green)); blue=(uint16 *) AcquireQuantumMemory(65536,sizeof(*blue)); if ((red == (uint16 *) NULL) || (green == (uint16 *) NULL) || (blue == (uint16 *) NULL)) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize TIFF colormap. */ (void) ResetMagickMemory(red,0,65536*sizeof(*red)); (void) ResetMagickMemory(green,0,65536*sizeof(*green)); (void) ResetMagickMemory(blue,0,65536*sizeof(*blue)); for (i=0; i < (ssize_t) image->colors; i++) { red[i]=ScaleQuantumToShort(image->colormap[i].red); green[i]=ScaleQuantumToShort(image->colormap[i].green); blue[i]=ScaleQuantumToShort(image->colormap[i].blue); } (void) TIFFSetField(tiff,TIFFTAG_COLORMAP,red,green,blue); red=(uint16 *) RelinquishMagickMemory(red); green=(uint16 *) RelinquishMagickMemory(green); blue=(uint16 *) RelinquishMagickMemory(blue); } default: { /* Convert PseudoClass packets to contiguous grayscale scanlines. */ quantum_type=IndexQuantum; if (image->matte != MagickFalse) { if (photometric != PHOTOMETRIC_PALETTE) quantum_type=GrayAlphaQuantum; else quantum_type=IndexAlphaQuantum; } else if (photometric != PHOTOMETRIC_PALETTE) quantum_type=GrayQuantum; for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,quantum_type,pixels,&image->exception); if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } } quantum_info=DestroyQuantumInfo(quantum_info); if (image->colorspace == LabColorspace) DecodeLabImage(image,&image->exception); DestroyTIFFInfo(&tiff_info); DisableMSCWarning(4127) if (0 && (image_info->verbose != MagickFalse)) RestoreMSCWarning TIFFPrintDirectory(tiff,stdout,MagickFalse); (void) TIFFWriteDirectory(tiff); image=SyncNextImageInList(image); if (image == (Image *) NULL) break; status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); TIFFClose(tiff); return(MagickTrue); } #endif
./CrossVul/dataset_final_sorted/CWE-119/c/good_4781_1
crossvul-cpp_data_bad_5359_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % TTTTT IIIII FFFFF FFFFF % % T I F F % % T I FFF FFF % % T I F F % % T IIIII F F % % % % % % Read/Write TIFF Image Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ #ifdef __VMS #define JPEG_SUPPORT 1 #endif /* 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/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colormap.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/geometry.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/memory-private.h" #include "MagickCore/module.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/pixel-private.h" #include "MagickCore/property.h" #include "MagickCore/quantum.h" #include "MagickCore/quantum-private.h" #include "MagickCore/profile.h" #include "MagickCore/resize.h" #include "MagickCore/resource_.h" #include "MagickCore/semaphore.h" #include "MagickCore/splay-tree.h" #include "MagickCore/static.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread_.h" #include "MagickCore/token.h" #include "MagickCore/utility.h" #if defined(MAGICKCORE_TIFF_DELEGATE) # if defined(MAGICKCORE_HAVE_TIFFCONF_H) # include "tiffconf.h" # endif # include "tiff.h" # include "tiffio.h" # if !defined(COMPRESSION_ADOBE_DEFLATE) # define COMPRESSION_ADOBE_DEFLATE 8 # endif # if !defined(PREDICTOR_HORIZONTAL) # define PREDICTOR_HORIZONTAL 2 # endif # if !defined(TIFFTAG_COPYRIGHT) # define TIFFTAG_COPYRIGHT 33432 # endif # if !defined(TIFFTAG_OPIIMAGEID) # define TIFFTAG_OPIIMAGEID 32781 # endif #include "psd-private.h" /* Typedef declarations. */ typedef enum { ReadSingleSampleMethod, ReadRGBAMethod, ReadCMYKAMethod, ReadYCCKMethod, ReadStripMethod, ReadTileMethod, ReadGenericMethod } TIFFMethodType; #if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY) typedef struct _ExifInfo { unsigned int tag, type, variable_length; const char *property; } ExifInfo; static const ExifInfo exif_info[] = { { EXIFTAG_EXPOSURETIME, TIFF_RATIONAL, 0, "exif:ExposureTime" }, { EXIFTAG_FNUMBER, TIFF_RATIONAL, 0, "exif:FNumber" }, { EXIFTAG_EXPOSUREPROGRAM, TIFF_SHORT, 0, "exif:ExposureProgram" }, { EXIFTAG_SPECTRALSENSITIVITY, TIFF_ASCII, 0, "exif:SpectralSensitivity" }, { EXIFTAG_ISOSPEEDRATINGS, TIFF_SHORT, 1, "exif:ISOSpeedRatings" }, { EXIFTAG_OECF, TIFF_NOTYPE, 0, "exif:OptoelectricConversionFactor" }, { EXIFTAG_EXIFVERSION, TIFF_NOTYPE, 0, "exif:ExifVersion" }, { EXIFTAG_DATETIMEORIGINAL, TIFF_ASCII, 0, "exif:DateTimeOriginal" }, { EXIFTAG_DATETIMEDIGITIZED, TIFF_ASCII, 0, "exif:DateTimeDigitized" }, { EXIFTAG_COMPONENTSCONFIGURATION, TIFF_NOTYPE, 0, "exif:ComponentsConfiguration" }, { EXIFTAG_COMPRESSEDBITSPERPIXEL, TIFF_RATIONAL, 0, "exif:CompressedBitsPerPixel" }, { EXIFTAG_SHUTTERSPEEDVALUE, TIFF_SRATIONAL, 0, "exif:ShutterSpeedValue" }, { EXIFTAG_APERTUREVALUE, TIFF_RATIONAL, 0, "exif:ApertureValue" }, { EXIFTAG_BRIGHTNESSVALUE, TIFF_SRATIONAL, 0, "exif:BrightnessValue" }, { EXIFTAG_EXPOSUREBIASVALUE, TIFF_SRATIONAL, 0, "exif:ExposureBiasValue" }, { EXIFTAG_MAXAPERTUREVALUE, TIFF_RATIONAL, 0, "exif:MaxApertureValue" }, { EXIFTAG_SUBJECTDISTANCE, TIFF_RATIONAL, 0, "exif:SubjectDistance" }, { EXIFTAG_METERINGMODE, TIFF_SHORT, 0, "exif:MeteringMode" }, { EXIFTAG_LIGHTSOURCE, TIFF_SHORT, 0, "exif:LightSource" }, { EXIFTAG_FLASH, TIFF_SHORT, 0, "exif:Flash" }, { EXIFTAG_FOCALLENGTH, TIFF_RATIONAL, 0, "exif:FocalLength" }, { EXIFTAG_SUBJECTAREA, TIFF_NOTYPE, 0, "exif:SubjectArea" }, { EXIFTAG_MAKERNOTE, TIFF_NOTYPE, 0, "exif:MakerNote" }, { EXIFTAG_USERCOMMENT, TIFF_NOTYPE, 0, "exif:UserComment" }, { EXIFTAG_SUBSECTIME, TIFF_ASCII, 0, "exif:SubSecTime" }, { EXIFTAG_SUBSECTIMEORIGINAL, TIFF_ASCII, 0, "exif:SubSecTimeOriginal" }, { EXIFTAG_SUBSECTIMEDIGITIZED, TIFF_ASCII, 0, "exif:SubSecTimeDigitized" }, { EXIFTAG_FLASHPIXVERSION, TIFF_NOTYPE, 0, "exif:FlashpixVersion" }, { EXIFTAG_PIXELXDIMENSION, TIFF_LONG, 0, "exif:PixelXDimension" }, { EXIFTAG_PIXELYDIMENSION, TIFF_LONG, 0, "exif:PixelYDimension" }, { EXIFTAG_RELATEDSOUNDFILE, TIFF_ASCII, 0, "exif:RelatedSoundFile" }, { EXIFTAG_FLASHENERGY, TIFF_RATIONAL, 0, "exif:FlashEnergy" }, { EXIFTAG_SPATIALFREQUENCYRESPONSE, TIFF_NOTYPE, 0, "exif:SpatialFrequencyResponse" }, { EXIFTAG_FOCALPLANEXRESOLUTION, TIFF_RATIONAL, 0, "exif:FocalPlaneXResolution" }, { EXIFTAG_FOCALPLANEYRESOLUTION, TIFF_RATIONAL, 0, "exif:FocalPlaneYResolution" }, { EXIFTAG_FOCALPLANERESOLUTIONUNIT, TIFF_SHORT, 0, "exif:FocalPlaneResolutionUnit" }, { EXIFTAG_SUBJECTLOCATION, TIFF_SHORT, 0, "exif:SubjectLocation" }, { EXIFTAG_EXPOSUREINDEX, TIFF_RATIONAL, 0, "exif:ExposureIndex" }, { EXIFTAG_SENSINGMETHOD, TIFF_SHORT, 0, "exif:SensingMethod" }, { EXIFTAG_FILESOURCE, TIFF_NOTYPE, 0, "exif:FileSource" }, { EXIFTAG_SCENETYPE, TIFF_NOTYPE, 0, "exif:SceneType" }, { EXIFTAG_CFAPATTERN, TIFF_NOTYPE, 0, "exif:CFAPattern" }, { EXIFTAG_CUSTOMRENDERED, TIFF_SHORT, 0, "exif:CustomRendered" }, { EXIFTAG_EXPOSUREMODE, TIFF_SHORT, 0, "exif:ExposureMode" }, { EXIFTAG_WHITEBALANCE, TIFF_SHORT, 0, "exif:WhiteBalance" }, { EXIFTAG_DIGITALZOOMRATIO, TIFF_RATIONAL, 0, "exif:DigitalZoomRatio" }, { EXIFTAG_FOCALLENGTHIN35MMFILM, TIFF_SHORT, 0, "exif:FocalLengthIn35mmFilm" }, { EXIFTAG_SCENECAPTURETYPE, TIFF_SHORT, 0, "exif:SceneCaptureType" }, { EXIFTAG_GAINCONTROL, TIFF_RATIONAL, 0, "exif:GainControl" }, { EXIFTAG_CONTRAST, TIFF_SHORT, 0, "exif:Contrast" }, { EXIFTAG_SATURATION, TIFF_SHORT, 0, "exif:Saturation" }, { EXIFTAG_SHARPNESS, TIFF_SHORT, 0, "exif:Sharpness" }, { EXIFTAG_DEVICESETTINGDESCRIPTION, TIFF_NOTYPE, 0, "exif:DeviceSettingDescription" }, { EXIFTAG_SUBJECTDISTANCERANGE, TIFF_SHORT, 0, "exif:SubjectDistanceRange" }, { EXIFTAG_IMAGEUNIQUEID, TIFF_ASCII, 0, "exif:ImageUniqueID" }, { 0, 0, 0, (char *) NULL } }; #endif #endif /* MAGICKCORE_TIFF_DELEGATE */ /* Global declarations. */ static MagickThreadKey tiff_exception; static SemaphoreInfo *tiff_semaphore = (SemaphoreInfo *) NULL; static TIFFErrorHandler error_handler, warning_handler; static volatile MagickBooleanType instantiate_key = MagickFalse; /* Forward declarations. */ #if defined(MAGICKCORE_TIFF_DELEGATE) static Image * ReadTIFFImage(const ImageInfo *,ExceptionInfo *); static MagickBooleanType WriteGROUP4Image(const ImageInfo *,Image *,ExceptionInfo *), WritePTIFImage(const ImageInfo *,Image *,ExceptionInfo *), WriteTIFFImage(const ImageInfo *,Image *,ExceptionInfo *); #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s T I F F % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsTIFF() returns MagickTrue if the image format type, identified by the % magick string, is TIFF. % % The format of the IsTIFF method is: % % MagickBooleanType IsTIFF(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsTIFF(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (memcmp(magick,"\115\115\000\052",4) == 0) return(MagickTrue); if (memcmp(magick,"\111\111\052\000",4) == 0) return(MagickTrue); #if defined(TIFF_VERSION_BIG) if (length < 8) return(MagickFalse); if (memcmp(magick,"\115\115\000\053\000\010\000\000",8) == 0) return(MagickTrue); if (memcmp(magick,"\111\111\053\000\010\000\000\000",8) == 0) return(MagickTrue); #endif return(MagickFalse); } #if defined(MAGICKCORE_TIFF_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d G R O U P 4 I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadGROUP4Image() reads a raw CCITT Group 4 image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadGROUP4Image method is: % % Image *ReadGROUP4Image(const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static inline size_t WriteLSBLong(FILE *file,const size_t value) { unsigned char buffer[4]; buffer[0]=(unsigned char) value; buffer[1]=(unsigned char) (value >> 8); buffer[2]=(unsigned char) (value >> 16); buffer[3]=(unsigned char) (value >> 24); return(fwrite(buffer,1,4,file)); } static Image *ReadGROUP4Image(const ImageInfo *image_info, ExceptionInfo *exception) { char filename[MagickPathExtent]; FILE *file; Image *image; ImageInfo *read_info; int c, unique_file; MagickBooleanType status; size_t length; ssize_t offset, strip_offset; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Write raw CCITT Group 4 wrapped as a TIFF image file. */ file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); if (unique_file != -1) file=fdopen(unique_file,"wb"); if ((unique_file == -1) || (file == (FILE *) NULL)) ThrowImageException(FileOpenError,"UnableToCreateTemporaryFile"); length=fwrite("\111\111\052\000\010\000\000\000\016\000",1,10,file); length=fwrite("\376\000\003\000\001\000\000\000\000\000\000\000",1,12,file); length=fwrite("\000\001\004\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,image->columns); length=fwrite("\001\001\004\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,image->rows); length=fwrite("\002\001\003\000\001\000\000\000\001\000\000\000",1,12,file); length=fwrite("\003\001\003\000\001\000\000\000\004\000\000\000",1,12,file); length=fwrite("\006\001\003\000\001\000\000\000\000\000\000\000",1,12,file); length=fwrite("\021\001\003\000\001\000\000\000",1,8,file); strip_offset=10+(12*14)+4+8; length=WriteLSBLong(file,(size_t) strip_offset); length=fwrite("\022\001\003\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,(size_t) image_info->orientation); length=fwrite("\025\001\003\000\001\000\000\000\001\000\000\000",1,12,file); length=fwrite("\026\001\004\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,image->rows); length=fwrite("\027\001\004\000\001\000\000\000\000\000\000\000",1,12,file); offset=(ssize_t) ftell(file)-4; length=fwrite("\032\001\005\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,(size_t) (strip_offset-8)); length=fwrite("\033\001\005\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,(size_t) (strip_offset-8)); length=fwrite("\050\001\003\000\001\000\000\000\002\000\000\000",1,12,file); length=fwrite("\000\000\000\000",1,4,file); length=WriteLSBLong(file,(long) image->resolution.x); length=WriteLSBLong(file,1); status=MagickTrue; for (length=0; (c=ReadBlobByte(image)) != EOF; length++) if (fputc(c,file) != c) status=MagickFalse; offset=(ssize_t) fseek(file,(ssize_t) offset,SEEK_SET); length=WriteLSBLong(file,(unsigned int) length); (void) fclose(file); (void) CloseBlob(image); image=DestroyImage(image); /* Read TIFF image. */ read_info=CloneImageInfo((ImageInfo *) NULL); (void) FormatLocaleString(read_info->filename,MagickPathExtent,"%s",filename); image=ReadTIFFImage(read_info,exception); read_info=DestroyImageInfo(read_info); if (image != (Image *) NULL) { (void) CopyMagickString(image->filename,image_info->filename, MagickPathExtent); (void) CopyMagickString(image->magick_filename,image_info->filename, MagickPathExtent); (void) CopyMagickString(image->magick,"GROUP4",MagickPathExtent); } (void) RelinquishUniqueFileResource(filename); if (status == MagickFalse) image=DestroyImage(image); return(image); } #endif #if defined(MAGICKCORE_TIFF_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d T I F F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadTIFFImage() reads a Tagged image file and returns it. It allocates the % memory necessary for the new Image structure and returns a pointer to the % new image. % % The format of the ReadTIFFImage method is: % % Image *ReadTIFFImage(const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static inline unsigned char ClampYCC(double value) { value=255.0-value; if (value < 0.0) return((unsigned char)0); if (value > 255.0) return((unsigned char)255); return((unsigned char)(value)); } static MagickBooleanType DecodeLabImage(Image *image,ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; ssize_t y; status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double a, b; a=QuantumScale*GetPixela(image,q)+0.5; if (a > 1.0) a-=1.0; b=QuantumScale*GetPixelb(image,q)+0.5; if (b > 1.0) b-=1.0; SetPixela(image,QuantumRange*a,q); SetPixelb(image,QuantumRange*b,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status); } static MagickBooleanType ReadProfile(Image *image,const char *name, const unsigned char *datum,ssize_t length,ExceptionInfo *exception) { MagickBooleanType status; StringInfo *profile; if (length < 4) return(MagickFalse); profile=BlobToStringInfo(datum,(size_t) length); if (profile == (StringInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=SetImageProfile(image,name,profile,exception); profile=DestroyStringInfo(profile); if (status == MagickFalse) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); return(MagickTrue); } #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static int TIFFCloseBlob(thandle_t image) { (void) CloseBlob((Image *) image); return(0); } static void TIFFErrors(const char *module,const char *format,va_list error) { char message[MagickPathExtent]; ExceptionInfo *exception; #if defined(MAGICKCORE_HAVE_VSNPRINTF) (void) vsnprintf(message,MagickPathExtent,format,error); #else (void) vsprintf(message,format,error); #endif (void) ConcatenateMagickString(message,".",MagickPathExtent); exception=(ExceptionInfo *) GetMagickThreadValue(tiff_exception); if (exception != (ExceptionInfo *) NULL) (void) ThrowMagickException(exception,GetMagickModule(),CoderError,message, "`%s'",module); } static toff_t TIFFGetBlobSize(thandle_t image) { return((toff_t) GetBlobSize((Image *) image)); } static void TIFFGetProfiles(TIFF *tiff,Image *image,MagickBooleanType ping, ExceptionInfo *exception) { uint32 length; unsigned char *profile; length=0; if (ping == MagickFalse) { #if defined(TIFFTAG_ICCPROFILE) if ((TIFFGetField(tiff,TIFFTAG_ICCPROFILE,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) (void) ReadProfile(image,"icc",profile,(ssize_t) length,exception); #endif #if defined(TIFFTAG_PHOTOSHOP) if ((TIFFGetField(tiff,TIFFTAG_PHOTOSHOP,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) (void) ReadProfile(image,"8bim",profile,(ssize_t) length,exception); #endif #if defined(TIFFTAG_RICHTIFFIPTC) if ((TIFFGetField(tiff,TIFFTAG_RICHTIFFIPTC,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) { if (TIFFIsByteSwapped(tiff) != 0) TIFFSwabArrayOfLong((uint32 *) profile,(size_t) length); (void) ReadProfile(image,"iptc",profile,4L*length,exception); } #endif #if defined(TIFFTAG_XMLPACKET) if ((TIFFGetField(tiff,TIFFTAG_XMLPACKET,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) (void) ReadProfile(image,"xmp",profile,(ssize_t) length,exception); #endif if ((TIFFGetField(tiff,34118,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) (void) ReadProfile(image,"tiff:34118",profile,(ssize_t) length, exception); } if ((TIFFGetField(tiff,37724,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) (void) ReadProfile(image,"tiff:37724",profile,(ssize_t) length,exception); } static void TIFFGetProperties(TIFF *tiff,Image *image,ExceptionInfo *exception) { char message[MagickPathExtent], *text; uint32 count, length, type; unsigned long *tietz; if (TIFFGetField(tiff,TIFFTAG_ARTIST,&text) == 1) (void) SetImageProperty(image,"tiff:artist",text,exception); if (TIFFGetField(tiff,TIFFTAG_COPYRIGHT,&text) == 1) (void) SetImageProperty(image,"tiff:copyright",text,exception); if (TIFFGetField(tiff,TIFFTAG_DATETIME,&text) == 1) (void) SetImageProperty(image,"tiff:timestamp",text,exception); if (TIFFGetField(tiff,TIFFTAG_DOCUMENTNAME,&text) == 1) (void) SetImageProperty(image,"tiff:document",text,exception); if (TIFFGetField(tiff,TIFFTAG_HOSTCOMPUTER,&text) == 1) (void) SetImageProperty(image,"tiff:hostcomputer",text,exception); if (TIFFGetField(tiff,TIFFTAG_IMAGEDESCRIPTION,&text) == 1) (void) SetImageProperty(image,"comment",text,exception); if (TIFFGetField(tiff,TIFFTAG_MAKE,&text) == 1) (void) SetImageProperty(image,"tiff:make",text,exception); if (TIFFGetField(tiff,TIFFTAG_MODEL,&text) == 1) (void) SetImageProperty(image,"tiff:model",text,exception); if (TIFFGetField(tiff,TIFFTAG_OPIIMAGEID,&count,&text) == 1) { if (count >= MagickPathExtent) count=MagickPathExtent-1; (void) CopyMagickString(message,text,count+1); (void) SetImageProperty(image,"tiff:image-id",message,exception); } if (TIFFGetField(tiff,TIFFTAG_PAGENAME,&text) == 1) (void) SetImageProperty(image,"label",text,exception); if (TIFFGetField(tiff,TIFFTAG_SOFTWARE,&text) == 1) (void) SetImageProperty(image,"tiff:software",text,exception); if (TIFFGetField(tiff,33423,&count,&text) == 1) { if (count >= MagickPathExtent) count=MagickPathExtent-1; (void) CopyMagickString(message,text,count+1); (void) SetImageProperty(image,"tiff:kodak-33423",message,exception); } if (TIFFGetField(tiff,36867,&count,&text) == 1) { if (count >= MagickPathExtent) count=MagickPathExtent-1; (void) CopyMagickString(message,text,count+1); (void) SetImageProperty(image,"tiff:kodak-36867",message,exception); } if (TIFFGetField(tiff,TIFFTAG_SUBFILETYPE,&type) == 1) switch (type) { case 0x01: { (void) SetImageProperty(image,"tiff:subfiletype","REDUCEDIMAGE", exception); break; } case 0x02: { (void) SetImageProperty(image,"tiff:subfiletype","PAGE",exception); break; } case 0x04: { (void) SetImageProperty(image,"tiff:subfiletype","MASK",exception); break; } default: break; } if (TIFFGetField(tiff,37706,&length,&tietz) == 1) { (void) FormatLocaleString(message,MagickPathExtent,"%lu",tietz[0]); (void) SetImageProperty(image,"tiff:tietz_offset",message,exception); } } static void TIFFGetEXIFProperties(TIFF *tiff,Image *image, ExceptionInfo *exception) { #if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY) char value[MagickPathExtent]; register ssize_t i; tdir_t directory; #if defined(TIFF_VERSION_BIG) uint64 #else uint32 #endif offset; void *sans; /* Read EXIF properties. */ offset=0; if (TIFFGetField(tiff,TIFFTAG_EXIFIFD,&offset) != 1) return; directory=TIFFCurrentDirectory(tiff); if (TIFFReadEXIFDirectory(tiff,offset) != 1) { TIFFSetDirectory(tiff,directory); return; } sans=NULL; for (i=0; exif_info[i].tag != 0; i++) { *value='\0'; switch (exif_info[i].type) { case TIFF_ASCII: { char *ascii; ascii=(char *) NULL; if ((TIFFGetField(tiff,exif_info[i].tag,&ascii,&sans,&sans) == 1) && (ascii != (char *) NULL) && (*ascii != '\0')) (void) CopyMagickString(value,ascii,MagickPathExtent); break; } case TIFF_SHORT: { if (exif_info[i].variable_length == 0) { uint16 shorty; shorty=0; if (TIFFGetField(tiff,exif_info[i].tag,&shorty,&sans,&sans) == 1) (void) FormatLocaleString(value,MagickPathExtent,"%d",shorty); } else { int tiff_status; uint16 *shorty; uint16 shorty_num; tiff_status=TIFFGetField(tiff,exif_info[i].tag,&shorty_num,&shorty, &sans,&sans); if (tiff_status == 1) (void) FormatLocaleString(value,MagickPathExtent,"%d", shorty_num != 0 ? shorty[0] : 0); } break; } case TIFF_LONG: { uint32 longy; longy=0; if (TIFFGetField(tiff,exif_info[i].tag,&longy,&sans,&sans) == 1) (void) FormatLocaleString(value,MagickPathExtent,"%d",longy); break; } #if defined(TIFF_VERSION_BIG) case TIFF_LONG8: { uint64 long8y; long8y=0; if (TIFFGetField(tiff,exif_info[i].tag,&long8y,&sans,&sans) == 1) (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) ((MagickOffsetType) long8y)); break; } #endif case TIFF_RATIONAL: case TIFF_SRATIONAL: case TIFF_FLOAT: { float floaty; floaty=0.0; if (TIFFGetField(tiff,exif_info[i].tag,&floaty,&sans,&sans) == 1) (void) FormatLocaleString(value,MagickPathExtent,"%g",(double) floaty); break; } case TIFF_DOUBLE: { double doubley; doubley=0.0; if (TIFFGetField(tiff,exif_info[i].tag,&doubley,&sans,&sans) == 1) (void) FormatLocaleString(value,MagickPathExtent,"%g",doubley); break; } default: break; } if (*value != '\0') (void) SetImageProperty(image,exif_info[i].property,value,exception); } TIFFSetDirectory(tiff,directory); #else (void) tiff; (void) image; #endif } static int TIFFMapBlob(thandle_t image,tdata_t *base,toff_t *size) { *base=(tdata_t *) GetBlobStreamData((Image *) image); if (*base != (tdata_t *) NULL) *size=(toff_t) GetBlobSize((Image *) image); if (*base != (tdata_t *) NULL) return(1); return(0); } static tsize_t TIFFReadBlob(thandle_t image,tdata_t data,tsize_t size) { tsize_t count; count=(tsize_t) ReadBlob((Image *) image,(size_t) size, (unsigned char *) data); return(count); } static int32 TIFFReadPixels(TIFF *tiff,size_t bits_per_sample, tsample_t sample,ssize_t row,tdata_t scanline) { int32 status; (void) bits_per_sample; status=TIFFReadScanline(tiff,scanline,(uint32) row,sample); return(status); } static toff_t TIFFSeekBlob(thandle_t image,toff_t offset,int whence) { return((toff_t) SeekBlob((Image *) image,(MagickOffsetType) offset,whence)); } static void TIFFUnmapBlob(thandle_t image,tdata_t base,toff_t size) { (void) image; (void) base; (void) size; } static void TIFFWarnings(const char *module,const char *format,va_list warning) { char message[MagickPathExtent]; ExceptionInfo *exception; #if defined(MAGICKCORE_HAVE_VSNPRINTF) (void) vsnprintf(message,MagickPathExtent,format,warning); #else (void) vsprintf(message,format,warning); #endif (void) ConcatenateMagickString(message,".",MagickPathExtent); exception=(ExceptionInfo *) GetMagickThreadValue(tiff_exception); if (exception != (ExceptionInfo *) NULL) (void) ThrowMagickException(exception,GetMagickModule(),CoderWarning, message,"`%s'",module); } static tsize_t TIFFWriteBlob(thandle_t image,tdata_t data,tsize_t size) { tsize_t count; count=(tsize_t) WriteBlob((Image *) image,(size_t) size, (unsigned char *) data); return(count); } static TIFFMethodType GetJPEGMethod(Image* image,TIFF *tiff,uint16 photometric, uint16 bits_per_sample,uint16 samples_per_pixel) { #define BUFFER_SIZE 2048 MagickOffsetType position, offset; register size_t i; TIFFMethodType method; #if defined(TIFF_VERSION_BIG) uint64 #else uint32 #endif **value; unsigned char buffer[BUFFER_SIZE+32]; unsigned short length; /* only support 8 bit for now */ if ((photometric != PHOTOMETRIC_SEPARATED) || (bits_per_sample != 8) || (samples_per_pixel != 4)) return(ReadGenericMethod); /* Search for Adobe APP14 JPEG Marker */ if (!TIFFGetField(tiff,TIFFTAG_STRIPOFFSETS,&value)) return(ReadRGBAMethod); position=TellBlob(image); offset=(MagickOffsetType) (value[0]); if (SeekBlob(image,offset,SEEK_SET) != offset) return(ReadRGBAMethod); method=ReadRGBAMethod; if (ReadBlob(image,BUFFER_SIZE,buffer) == BUFFER_SIZE) { for (i=0; i < BUFFER_SIZE; i++) { while (i < BUFFER_SIZE) { if (buffer[i++] == 255) break; } while (i < BUFFER_SIZE) { if (buffer[++i] != 255) break; } if (buffer[i++] == 216) /* JPEG_MARKER_SOI */ continue; length=(unsigned short) (((unsigned int) (buffer[i] << 8) | (unsigned int) buffer[i+1]) & 0xffff); if (i+(size_t) length >= BUFFER_SIZE) break; if (buffer[i-1] == 238) /* JPEG_MARKER_APP0+14 */ { if (length != 14) break; /* 0 == CMYK, 1 == YCbCr, 2 = YCCK */ if (buffer[i+13] == 2) method=ReadYCCKMethod; break; } i+=(size_t) length; } } (void) SeekBlob(image,position,SEEK_SET); return(method); } static void TIFFReadPhotoshopLayers(Image* image,const ImageInfo *image_info, ExceptionInfo *exception) { const char *option; const StringInfo *layer_info; Image *layers; PSDInfo info; register ssize_t i; if (GetImageListLength(image) != 1) return; if ((image_info->number_scenes == 1) && (image_info->scene == 0)) return; option=GetImageOption(image_info,"tiff:ignore-layers"); if (option != (const char * ) NULL) return; layer_info=GetImageProfile(image,"tiff:37724"); if (layer_info == (const StringInfo *) NULL) return; for (i=0; i < (ssize_t) layer_info->length-8; i++) { if (LocaleNCompare((const char *) (layer_info->datum+i), image->endian == MSBEndian ? "8BIM" : "MIB8",4) != 0) continue; i+=4; if ((LocaleNCompare((const char *) (layer_info->datum+i), image->endian == MSBEndian ? "Layr" : "ryaL",4) == 0) || (LocaleNCompare((const char *) (layer_info->datum+i), image->endian == MSBEndian ? "LMsk" : "ksML",4) == 0) || (LocaleNCompare((const char *) (layer_info->datum+i), image->endian == MSBEndian ? "Lr16" : "61rL",4) == 0) || (LocaleNCompare((const char *) (layer_info->datum+i), image->endian == MSBEndian ? "Lr32" : "23rL",4) == 0)) break; } i+=4; if (i >= (ssize_t) (layer_info->length-8)) return; layers=CloneImage(image,image->columns,image->rows,MagickTrue,exception); (void) DeleteImageProfile(layers,"tiff:37724"); AttachBlob(layers->blob,layer_info->datum,layer_info->length); SeekBlob(layers,(MagickOffsetType) i,SEEK_SET); info.version=1; info.columns=layers->columns; info.rows=layers->rows; info.channels=(unsigned short) layers->number_channels; /* Setting the mode to a value that won't change the colorspace */ info.mode=10; ReadPSDLayers(layers,image_info,&info,MagickFalse,exception); DeleteImageFromList(&layers); if (layers != (Image *) NULL) { SetImageArtifact(image,"tiff:has-layers","true"); AppendImageToList(&image,layers); while (layers != (Image *) NULL) { SetImageArtifact(layers,"tiff:has-layers","true"); DetachBlob(layers->blob); layers=GetNextImageInList(layers); } } } #if defined(__cplusplus) || defined(c_plusplus) } #endif static Image *ReadTIFFImage(const ImageInfo *image_info, ExceptionInfo *exception) { const char *option; float *chromaticity, x_position, y_position, x_resolution, y_resolution; Image *image; int tiff_status; MagickBooleanType status; MagickSizeType number_pixels; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; size_t pad; ssize_t y; TIFF *tiff; TIFFMethodType method; uint16 compress_tag, bits_per_sample, endian, extra_samples, interlace, max_sample_value, min_sample_value, orientation, pages, photometric, *sample_info, sample_format, samples_per_pixel, units, value; uint32 height, rows_per_strip, width; unsigned char *pixels; /* Open image. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } (void) SetMagickThreadValue(tiff_exception,exception); tiff=TIFFClientOpen(image->filename,"rb",(thandle_t) image,TIFFReadBlob, TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob, TIFFUnmapBlob); if (tiff == (TIFF *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } if (image_info->number_scenes != 0) { /* Generate blank images for subimage specification (e.g. image.tif[4]. We need to check the number of directores because it is possible that the subimage(s) are stored in the photoshop profile. */ if (image_info->scene < (size_t) TIFFNumberOfDirectories(tiff)) { for (i=0; i < (ssize_t) image_info->scene; i++) { status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse; if (status == MagickFalse) { TIFFClose(tiff); image=DestroyImageList(image); return((Image *) NULL); } AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { TIFFClose(tiff); image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); } } } do { DisableMSCWarning(4127) if (0 && (image_info->verbose != MagickFalse)) TIFFPrintDirectory(tiff,stdout,MagickFalse); RestoreMSCWarning if ((TIFFGetField(tiff,TIFFTAG_IMAGEWIDTH,&width) != 1) || (TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&height) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_COMPRESSION,&compress_tag) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_PLANARCONFIG,&interlace) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,&samples_per_pixel) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,&bits_per_sample) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLEFORMAT,&sample_format) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_MINSAMPLEVALUE,&min_sample_value) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_MAXSAMPLEVALUE,&max_sample_value) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_PHOTOMETRIC,&photometric) != 1)) { TIFFClose(tiff); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (sample_format == SAMPLEFORMAT_IEEEFP) (void) SetImageProperty(image,"quantum:format","floating-point", exception); switch (photometric) { case PHOTOMETRIC_MINISBLACK: { (void) SetImageProperty(image,"tiff:photometric","min-is-black", exception); break; } case PHOTOMETRIC_MINISWHITE: { (void) SetImageProperty(image,"tiff:photometric","min-is-white", exception); break; } case PHOTOMETRIC_PALETTE: { (void) SetImageProperty(image,"tiff:photometric","palette",exception); break; } case PHOTOMETRIC_RGB: { (void) SetImageProperty(image,"tiff:photometric","RGB",exception); break; } case PHOTOMETRIC_CIELAB: { (void) SetImageProperty(image,"tiff:photometric","CIELAB",exception); break; } case PHOTOMETRIC_LOGL: { (void) SetImageProperty(image,"tiff:photometric","CIE Log2(L)", exception); break; } case PHOTOMETRIC_LOGLUV: { (void) SetImageProperty(image,"tiff:photometric","LOGLUV",exception); break; } #if defined(PHOTOMETRIC_MASK) case PHOTOMETRIC_MASK: { (void) SetImageProperty(image,"tiff:photometric","MASK",exception); break; } #endif case PHOTOMETRIC_SEPARATED: { (void) SetImageProperty(image,"tiff:photometric","separated",exception); break; } case PHOTOMETRIC_YCBCR: { (void) SetImageProperty(image,"tiff:photometric","YCBCR",exception); break; } default: { (void) SetImageProperty(image,"tiff:photometric","unknown",exception); break; } } if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Geometry: %ux%u", (unsigned int) width,(unsigned int) height); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Interlace: %u", interlace); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Bits per sample: %u",bits_per_sample); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Min sample value: %u",min_sample_value); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Max sample value: %u",max_sample_value); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Photometric " "interpretation: %s",GetImageProperty(image,"tiff:photometric", exception)); } image->columns=(size_t) width; image->rows=(size_t) height; image->depth=(size_t) bits_per_sample; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Image depth: %.20g", (double) image->depth); image->endian=MSBEndian; if (endian == FILLORDER_LSB2MSB) image->endian=LSBEndian; #if defined(MAGICKCORE_HAVE_TIFFISBIGENDIAN) if (TIFFIsBigEndian(tiff) == 0) { (void) SetImageProperty(image,"tiff:endian","lsb",exception); image->endian=LSBEndian; } else { (void) SetImageProperty(image,"tiff:endian","msb",exception); image->endian=MSBEndian; } #endif if ((photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) SetImageColorspace(image,GRAYColorspace,exception); if (photometric == PHOTOMETRIC_SEPARATED) SetImageColorspace(image,CMYKColorspace,exception); if (photometric == PHOTOMETRIC_CIELAB) SetImageColorspace(image,LabColorspace,exception); TIFFGetProfiles(tiff,image,image_info->ping,exception); TIFFGetProperties(tiff,image,exception); option=GetImageOption(image_info,"tiff:exif-properties"); if (IsStringFalse(option) == MagickFalse) /* enabled by default */ TIFFGetEXIFProperties(tiff,image,exception); (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL, &samples_per_pixel); if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XRESOLUTION,&x_resolution) == 1) && (TIFFGetFieldDefaulted(tiff,TIFFTAG_YRESOLUTION,&y_resolution) == 1)) { image->resolution.x=x_resolution; image->resolution.y=y_resolution; } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_RESOLUTIONUNIT,&units) == 1) { if (units == RESUNIT_INCH) image->units=PixelsPerInchResolution; if (units == RESUNIT_CENTIMETER) image->units=PixelsPerCentimeterResolution; } if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XPOSITION,&x_position) == 1) && (TIFFGetFieldDefaulted(tiff,TIFFTAG_YPOSITION,&y_position) == 1)) { image->page.x=(ssize_t) ceil(x_position*image->resolution.x-0.5); image->page.y=(ssize_t) ceil(y_position*image->resolution.y-0.5); } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_ORIENTATION,&orientation) == 1) image->orientation=(OrientationType) orientation; if (TIFFGetField(tiff,TIFFTAG_WHITEPOINT,&chromaticity) == 1) { if (chromaticity != (float *) NULL) { image->chromaticity.white_point.x=chromaticity[0]; image->chromaticity.white_point.y=chromaticity[1]; } } if (TIFFGetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,&chromaticity) == 1) { if (chromaticity != (float *) NULL) { image->chromaticity.red_primary.x=chromaticity[0]; image->chromaticity.red_primary.y=chromaticity[1]; image->chromaticity.green_primary.x=chromaticity[2]; image->chromaticity.green_primary.y=chromaticity[3]; image->chromaticity.blue_primary.x=chromaticity[4]; image->chromaticity.blue_primary.y=chromaticity[5]; } } #if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919) if ((compress_tag != COMPRESSION_NONE) && (TIFFIsCODECConfigured(compress_tag) == 0)) { TIFFClose(tiff); ThrowReaderException(CoderError,"CompressNotSupported"); } #endif switch (compress_tag) { case COMPRESSION_NONE: image->compression=NoCompression; break; case COMPRESSION_CCITTFAX3: image->compression=FaxCompression; break; case COMPRESSION_CCITTFAX4: image->compression=Group4Compression; break; case COMPRESSION_JPEG: { image->compression=JPEGCompression; #if defined(JPEG_SUPPORT) { char sampling_factor[MagickPathExtent]; int tiff_status; uint16 horizontal, vertical; tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_YCBCRSUBSAMPLING, &horizontal,&vertical); if (tiff_status == 1) { (void) FormatLocaleString(sampling_factor,MagickPathExtent, "%dx%d",horizontal,vertical); (void) SetImageProperty(image,"jpeg:sampling-factor", sampling_factor,exception); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Sampling Factors: %s",sampling_factor); } } #endif break; } case COMPRESSION_OJPEG: image->compression=JPEGCompression; break; #if defined(COMPRESSION_LZMA) case COMPRESSION_LZMA: image->compression=LZMACompression; break; #endif case COMPRESSION_LZW: image->compression=LZWCompression; break; case COMPRESSION_DEFLATE: image->compression=ZipCompression; break; case COMPRESSION_ADOBE_DEFLATE: image->compression=ZipCompression; break; default: image->compression=RLECompression; break; } /* Allocate memory for the image and pixel buffer. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } if (sample_format == SAMPLEFORMAT_UINT) status=SetQuantumFormat(image,quantum_info,UnsignedQuantumFormat); if (sample_format == SAMPLEFORMAT_INT) status=SetQuantumFormat(image,quantum_info,SignedQuantumFormat); if (sample_format == SAMPLEFORMAT_IEEEFP) status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) { TIFFClose(tiff); quantum_info=DestroyQuantumInfo(quantum_info); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } status=MagickTrue; switch (photometric) { case PHOTOMETRIC_MINISBLACK: { quantum_info->min_is_white=MagickFalse; break; } case PHOTOMETRIC_MINISWHITE: { quantum_info->min_is_white=MagickTrue; break; } default: break; } tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_EXTRASAMPLES,&extra_samples, &sample_info); if (tiff_status == 1) { (void) SetImageProperty(image,"tiff:alpha","unspecified",exception); if (extra_samples == 0) { if ((samples_per_pixel == 4) && (photometric == PHOTOMETRIC_RGB)) image->alpha_trait=BlendPixelTrait; } else for (i=0; i < extra_samples; i++) { image->alpha_trait=BlendPixelTrait; if (sample_info[i] == EXTRASAMPLE_ASSOCALPHA) { SetQuantumAlphaType(quantum_info,DisassociatedQuantumAlpha); (void) SetImageProperty(image,"tiff:alpha","associated", exception); } else if (sample_info[i] == EXTRASAMPLE_UNASSALPHA) (void) SetImageProperty(image,"tiff:alpha","unassociated", exception); } } if ((photometric == PHOTOMETRIC_PALETTE) && (pow(2.0,1.0*bits_per_sample) <= MaxColormapSize)) { size_t colors; colors=(size_t) GetQuantumRange(bits_per_sample)+1; if (AcquireImageColormap(image,colors,exception) == MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } } value=(unsigned short) image->scene; if (TIFFGetFieldDefaulted(tiff,TIFFTAG_PAGENUMBER,&value,&pages) == 1) image->scene=value; if (image->storage_class == PseudoClass) { int tiff_status; size_t range; uint16 *blue_colormap, *green_colormap, *red_colormap; /* Initialize colormap. */ tiff_status=TIFFGetField(tiff,TIFFTAG_COLORMAP,&red_colormap, &green_colormap,&blue_colormap); if (tiff_status == 1) { if ((red_colormap != (uint16 *) NULL) && (green_colormap != (uint16 *) NULL) && (blue_colormap != (uint16 *) NULL)) { range=255; /* might be old style 8-bit colormap */ for (i=0; i < (ssize_t) image->colors; i++) if ((red_colormap[i] >= 256) || (green_colormap[i] >= 256) || (blue_colormap[i] >= 256)) { range=65535; break; } for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=ClampToQuantum(((double) QuantumRange*red_colormap[i])/range); image->colormap[i].green=ClampToQuantum(((double) QuantumRange*green_colormap[i])/range); image->colormap[i].blue=ClampToQuantum(((double) QuantumRange*blue_colormap[i])/range); } } } if (image->alpha_trait == UndefinedPixelTrait) image->depth=GetImageDepth(image,exception); } if (image_info->ping != MagickFalse) { if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) { quantum_info=DestroyQuantumInfo(quantum_info); break; } goto next_tiff_frame; } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); method=ReadGenericMethod; if (TIFFGetField(tiff,TIFFTAG_ROWSPERSTRIP,&rows_per_strip) == 1) { char value[MagickPathExtent]; method=ReadStripMethod; (void) FormatLocaleString(value,MagickPathExtent,"%u", (unsigned int) rows_per_strip); (void) SetImageProperty(image,"tiff:rows-per-strip",value,exception); } if ((samples_per_pixel >= 2) && (interlace == PLANARCONFIG_CONTIG)) method=ReadRGBAMethod; if ((samples_per_pixel >= 2) && (interlace == PLANARCONFIG_SEPARATE)) method=ReadCMYKAMethod; if ((photometric != PHOTOMETRIC_RGB) && (photometric != PHOTOMETRIC_CIELAB) && (photometric != PHOTOMETRIC_SEPARATED)) method=ReadGenericMethod; if (image->storage_class == PseudoClass) method=ReadSingleSampleMethod; if ((photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) method=ReadSingleSampleMethod; if ((photometric != PHOTOMETRIC_SEPARATED) && (interlace == PLANARCONFIG_SEPARATE) && (bits_per_sample < 64)) method=ReadGenericMethod; if (image->compression == JPEGCompression) method=GetJPEGMethod(image,tiff,photometric,bits_per_sample, samples_per_pixel); if (compress_tag == COMPRESSION_JBIG) method=ReadStripMethod; if (TIFFIsTiled(tiff) != MagickFalse) method=ReadTileMethod; quantum_info->endian=LSBEndian; quantum_type=RGBQuantum; pixels=(unsigned char *) GetQuantumPixels(quantum_info); switch (method) { case ReadSingleSampleMethod: { /* Convert TIFF image to PseudoClass MIFF image. */ quantum_type=IndexQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0); if (image->alpha_trait != UndefinedPixelTrait) { if (image->storage_class != PseudoClass) { quantum_type=samples_per_pixel == 1 ? AlphaQuantum : GrayAlphaQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0); } else { quantum_type=IndexAlphaQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0); } } else if (image->storage_class != PseudoClass) { quantum_type=GrayQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0); } status=SetQuantumPad(image,quantum_info,pad*pow(2,ceil(log( bits_per_sample)/log(2)))); if (status == MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=(unsigned char *) GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { int status; register Quantum *magick_restrict q; status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadRGBAMethod: { /* Convert TIFF image to DirectClass MIFF image. */ pad=(size_t) MagickMax((size_t) samples_per_pixel-3,0); quantum_type=RGBQuantum; if (image->alpha_trait != UndefinedPixelTrait) { quantum_type=RGBAQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0); } if (image->colorspace == CMYKColorspace) { pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0); quantum_type=CMYKQuantum; if (image->alpha_trait != UndefinedPixelTrait) { quantum_type=CMYKAQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-5,0); } } status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3)); if (status == MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=(unsigned char *) GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { int status; register Quantum *magick_restrict q; status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadCMYKAMethod: { /* Convert TIFF image to DirectClass MIFF image. */ for (i=0; i < (ssize_t) samples_per_pixel; i++) { for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; int status; status=TIFFReadPixels(tiff,bits_per_sample,(tsample_t) i,y,(char *) pixels); if (status == -1) break; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; if (image->colorspace != CMYKColorspace) switch (i) { case 0: quantum_type=RedQuantum; break; case 1: quantum_type=GreenQuantum; break; case 2: quantum_type=BlueQuantum; break; case 3: quantum_type=AlphaQuantum; break; default: quantum_type=UndefinedQuantum; break; } else switch (i) { case 0: quantum_type=CyanQuantum; break; case 1: quantum_type=MagentaQuantum; break; case 2: quantum_type=YellowQuantum; break; case 3: quantum_type=BlackQuantum; break; case 4: quantum_type=AlphaQuantum; break; default: quantum_type=UndefinedQuantum; break; } (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadYCCKMethod: { pixels=(unsigned char *) GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { int status; register Quantum *magick_restrict q; register ssize_t x; unsigned char *p; status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; p=pixels; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelCyan(image,ScaleCharToQuantum(ClampYCC((double) *p+ (1.402*(double) *(p+2))-179.456)),q); SetPixelMagenta(image,ScaleCharToQuantum(ClampYCC((double) *p- (0.34414*(double) *(p+1))-(0.71414*(double ) *(p+2))+ 135.45984)),q); SetPixelYellow(image,ScaleCharToQuantum(ClampYCC((double) *p+ (1.772*(double) *(p+1))-226.816)),q); SetPixelBlack(image,ScaleCharToQuantum((unsigned char) *(p+3)),q); q+=GetPixelChannels(image); p+=4; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadStripMethod: { register uint32 *p; /* Convert stripped TIFF image to DirectClass MIFF image. */ i=0; p=(uint32 *) NULL; for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; if (i == 0) { if (TIFFReadRGBAStrip(tiff,(tstrip_t) y,(uint32 *) pixels) == 0) break; i=(ssize_t) MagickMin((ssize_t) rows_per_strip,(ssize_t) image->rows-y); } i--; p=((uint32 *) pixels)+image->columns*i; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleCharToQuantum((unsigned char) (TIFFGetR(*p))),q); SetPixelGreen(image,ScaleCharToQuantum((unsigned char) (TIFFGetG(*p))),q); SetPixelBlue(image,ScaleCharToQuantum((unsigned char) (TIFFGetB(*p))),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ScaleCharToQuantum((unsigned char) (TIFFGetA(*p))),q); p++; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadTileMethod: { register uint32 *p; uint32 *tile_pixels, columns, rows; /* Convert tiled TIFF image to DirectClass MIFF image. */ if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) != 1) || (TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) != 1)) { TIFFClose(tiff); ThrowReaderException(CoderError,"ImageIsNotTiled"); } (void) SetImageStorageClass(image,DirectClass,exception); number_pixels=(MagickSizeType) columns*rows; if (HeapOverflowSanityCheck(rows,sizeof(*tile_pixels)) != MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } tile_pixels=(uint32 *) AcquireQuantumMemory(columns,rows* sizeof(*tile_pixels)); if (tile_pixels == (uint32 *) NULL) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } for (y=0; y < (ssize_t) image->rows; y+=rows) { register ssize_t x; register Quantum *magick_restrict q, *magick_restrict tile; size_t columns_remaining, rows_remaining; rows_remaining=image->rows-y; if ((ssize_t) (y+rows) < (ssize_t) image->rows) rows_remaining=rows; tile=QueueAuthenticPixels(image,0,y,image->columns,rows_remaining, exception); if (tile == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x+=columns) { size_t column, row; if (TIFFReadRGBATile(tiff,(uint32) x,(uint32) y,tile_pixels) == 0) break; columns_remaining=image->columns-x; if ((ssize_t) (x+columns) < (ssize_t) image->columns) columns_remaining=columns; p=tile_pixels+(rows-rows_remaining)*columns; q=tile+GetPixelChannels(image)*(image->columns*(rows_remaining-1)+ x); for (row=rows_remaining; row > 0; row--) { if (image->alpha_trait != UndefinedPixelTrait) for (column=columns_remaining; column > 0; column--) { SetPixelRed(image,ScaleCharToQuantum((unsigned char) TIFFGetR(*p)),q); SetPixelGreen(image,ScaleCharToQuantum((unsigned char) TIFFGetG(*p)),q); SetPixelBlue(image,ScaleCharToQuantum((unsigned char) TIFFGetB(*p)),q); SetPixelAlpha(image,ScaleCharToQuantum((unsigned char) TIFFGetA(*p)),q); p++; q+=GetPixelChannels(image); } else for (column=columns_remaining; column > 0; column--) { SetPixelRed(image,ScaleCharToQuantum((unsigned char) TIFFGetR(*p)),q); SetPixelGreen(image,ScaleCharToQuantum((unsigned char) TIFFGetG(*p)),q); SetPixelBlue(image,ScaleCharToQuantum((unsigned char) TIFFGetB(*p)),q); p++; q+=GetPixelChannels(image); } p+=columns-columns_remaining; q-=GetPixelChannels(image)*(image->columns+columns_remaining); } } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } tile_pixels=(uint32 *) RelinquishMagickMemory(tile_pixels); break; } case ReadGenericMethod: default: { MemoryInfo *pixel_info; register uint32 *p; uint32 *pixels; /* Convert TIFF image to DirectClass MIFF image. */ number_pixels=(MagickSizeType) image->columns*image->rows; if (HeapOverflowSanityCheck(image->rows,sizeof(*pixels)) != MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixel_info=AcquireVirtualMemory(image->columns,image->rows* sizeof(uint32)); if (pixel_info == (MemoryInfo *) NULL) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=(uint32 *) GetVirtualMemoryBlob(pixel_info); (void) TIFFReadRGBAImage(tiff,(uint32) image->columns,(uint32) image->rows,(uint32 *) pixels,0); /* Convert image to DirectClass pixel packets. */ p=pixels+number_pixels-1; for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; q+=GetPixelChannels(image)*(image->columns-1); for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleCharToQuantum((unsigned char) TIFFGetR(*p)),q); SetPixelGreen(image,ScaleCharToQuantum((unsigned char) TIFFGetG(*p)),q); SetPixelBlue(image,ScaleCharToQuantum((unsigned char) TIFFGetB(*p)),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ScaleCharToQuantum((unsigned char) TIFFGetA(*p)),q); p--; q-=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } pixel_info=RelinquishVirtualMemory(pixel_info); break; } } SetQuantumImageType(image,quantum_type); next_tiff_frame: quantum_info=DestroyQuantumInfo(quantum_info); if (photometric == PHOTOMETRIC_CIELAB) DecodeLabImage(image,exception); if ((photometric == PHOTOMETRIC_LOGL) || (photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) { image->type=GrayscaleType; if (bits_per_sample == 1) image->type=BilevelType; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse; if (status != MagickFalse) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,image->scene-1, image->scene); if (status == MagickFalse) break; } } while (status != MagickFalse); TIFFClose(tiff); TIFFReadPhotoshopLayers(image,image_info,exception); if (image_info->number_scenes != 0) { if (image_info->scene >= GetImageListLength(image)) { /* Subimage was not found in the Photoshop layer */ image=DestroyImageList(image); return((Image *)NULL); } } return(GetFirstImageInList(image)); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r T I F F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterTIFFImage() adds properties for the TIFF image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterTIFFImage method is: % % size_t RegisterTIFFImage(void) % */ #if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER) static TIFFExtendProc tag_extender = (TIFFExtendProc) NULL; static void TIFFIgnoreTags(TIFF *tiff) { char *q; const char *p, *tags; Image *image; register ssize_t i; size_t count; TIFFFieldInfo *ignore; if (TIFFGetReadProc(tiff) != TIFFReadBlob) return; image=(Image *)TIFFClientdata(tiff); tags=GetImageArtifact(image,"tiff:ignore-tags"); if (tags == (const char *) NULL) return; count=0; p=tags; while (*p != '\0') { while ((isspace((int) ((unsigned char) *p)) != 0)) p++; (void) strtol(p,&q,10); if (p == q) return; p=q; count++; while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) p++; } if (count == 0) return; i=0; p=tags; ignore=(TIFFFieldInfo *) AcquireQuantumMemory(count,sizeof(*ignore)); /* This also sets field_bit to 0 (FIELD_IGNORE) */ ResetMagickMemory(ignore,0,count*sizeof(*ignore)); while (*p != '\0') { while ((isspace((int) ((unsigned char) *p)) != 0)) p++; ignore[i].field_tag=(ttag_t) strtol(p,&q,10); p=q; i++; while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) p++; } (void) TIFFMergeFieldInfo(tiff,ignore,(uint32) count); ignore=(TIFFFieldInfo *) RelinquishMagickMemory(ignore); } static void TIFFTagExtender(TIFF *tiff) { static const TIFFFieldInfo TIFFExtensions[] = { { 37724, -3, -3, TIFF_UNDEFINED, FIELD_CUSTOM, 1, 1, (char *) "PhotoshopLayerData" }, { 34118, -3, -3, TIFF_UNDEFINED, FIELD_CUSTOM, 1, 1, (char *) "Microscope" } }; TIFFMergeFieldInfo(tiff,TIFFExtensions,sizeof(TIFFExtensions)/ sizeof(*TIFFExtensions)); if (tag_extender != (TIFFExtendProc) NULL) (*tag_extender)(tiff); TIFFIgnoreTags(tiff); } #endif ModuleExport size_t RegisterTIFFImage(void) { #define TIFFDescription "Tagged Image File Format" char version[MagickPathExtent]; MagickInfo *entry; if (tiff_semaphore == (SemaphoreInfo *) NULL) ActivateSemaphoreInfo(&tiff_semaphore); LockSemaphoreInfo(tiff_semaphore); if (instantiate_key == MagickFalse) { if (CreateMagickThreadKey(&tiff_exception,NULL) == MagickFalse) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); error_handler=TIFFSetErrorHandler(TIFFErrors); warning_handler=TIFFSetWarningHandler(TIFFWarnings); #if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER) if (tag_extender == (TIFFExtendProc) NULL) tag_extender=TIFFSetTagExtender(TIFFTagExtender); #endif instantiate_key=MagickTrue; } UnlockSemaphoreInfo(tiff_semaphore); *version='\0'; #if defined(TIFF_VERSION) (void) FormatLocaleString(version,MagickPathExtent,"%d",TIFF_VERSION); #endif #if defined(MAGICKCORE_TIFF_DELEGATE) { const char *p; register ssize_t i; p=TIFFGetVersion(); for (i=0; (i < (MagickPathExtent-1)) && (*p != 0) && (*p != '\n'); i++) version[i]=(*p++); version[i]='\0'; } #endif entry=AcquireMagickInfo("TIFF","GROUP4","Raw CCITT Group4"); #if defined(MAGICKCORE_TIFF_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadGROUP4Image; entry->encoder=(EncodeImageHandler *) WriteGROUP4Image; #endif entry->flags|=CoderRawSupportFlag; entry->flags|=CoderEndianSupportFlag; entry->flags|=CoderSeekableStreamFlag; entry->flags^=CoderAdjoinFlag; entry->flags^=CoderUseExtensionFlag; entry->format_type=ImplicitFormatType; entry->mime_type=ConstantString("image/tiff"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("TIFF","PTIF","Pyramid encoded TIFF"); #if defined(MAGICKCORE_TIFF_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadTIFFImage; entry->encoder=(EncodeImageHandler *) WritePTIFImage; #endif entry->flags|=CoderEndianSupportFlag; entry->flags|=CoderSeekableStreamFlag; entry->flags^=CoderUseExtensionFlag; entry->mime_type=ConstantString("image/tiff"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("TIFF","TIF",TIFFDescription); #if defined(MAGICKCORE_TIFF_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadTIFFImage; entry->encoder=(EncodeImageHandler *) WriteTIFFImage; #endif entry->flags|=CoderEndianSupportFlag; entry->flags|=CoderSeekableStreamFlag; entry->flags|=CoderStealthFlag; entry->flags^=CoderUseExtensionFlag; if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/tiff"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("TIFF","TIFF",TIFFDescription); #if defined(MAGICKCORE_TIFF_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadTIFFImage; entry->encoder=(EncodeImageHandler *) WriteTIFFImage; #endif entry->magick=(IsImageFormatHandler *) IsTIFF; entry->flags|=CoderEndianSupportFlag; entry->flags|=CoderSeekableStreamFlag; entry->flags^=CoderUseExtensionFlag; if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/tiff"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("TIFF","TIFF64","Tagged Image File Format (64-bit)"); #if defined(TIFF_VERSION_BIG) entry->decoder=(DecodeImageHandler *) ReadTIFFImage; entry->encoder=(EncodeImageHandler *) WriteTIFFImage; #endif entry->flags|=CoderEndianSupportFlag; entry->flags|=CoderSeekableStreamFlag; entry->flags^=CoderAdjoinFlag; entry->flags^=CoderUseExtensionFlag; if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/tiff"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r T I F F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterTIFFImage() removes format registrations made by the TIFF module % from the list of supported formats. % % The format of the UnregisterTIFFImage method is: % % UnregisterTIFFImage(void) % */ ModuleExport void UnregisterTIFFImage(void) { (void) UnregisterMagickInfo("TIFF64"); (void) UnregisterMagickInfo("TIFF"); (void) UnregisterMagickInfo("TIF"); (void) UnregisterMagickInfo("PTIF"); if (tiff_semaphore == (SemaphoreInfo *) NULL) ActivateSemaphoreInfo(&tiff_semaphore); LockSemaphoreInfo(tiff_semaphore); if (instantiate_key != MagickFalse) { #if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER) if (tag_extender == (TIFFExtendProc) NULL) (void) TIFFSetTagExtender(tag_extender); #endif if (DeleteMagickThreadKey(tiff_exception) == MagickFalse) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) TIFFSetWarningHandler(warning_handler); (void) TIFFSetErrorHandler(error_handler); instantiate_key=MagickFalse; } UnlockSemaphoreInfo(tiff_semaphore); RelinquishSemaphoreInfo(&tiff_semaphore); } #if defined(MAGICKCORE_TIFF_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e G R O U P 4 I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteGROUP4Image() writes an image in the raw CCITT Group 4 image format. % % The format of the WriteGROUP4Image method is: % % MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info, % Image *image,ExceptionInfo *) % % A description of each parameter follows: % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { char filename[MagickPathExtent]; FILE *file; Image *huffman_image; ImageInfo *write_info; int unique_file; MagickBooleanType status; register ssize_t i; ssize_t count; TIFF *tiff; toff_t *byte_count, strip_size; unsigned char *buffer; /* Write image as CCITT Group4 TIFF image to a temporary file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); huffman_image=CloneImage(image,0,0,MagickTrue,exception); if (huffman_image == (Image *) NULL) { (void) CloseBlob(image); return(MagickFalse); } huffman_image->endian=MSBEndian; file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); if (unique_file != -1) file=fdopen(unique_file,"wb"); if ((unique_file == -1) || (file == (FILE *) NULL)) { ThrowFileException(exception,FileOpenError,"UnableToCreateTemporaryFile", filename); return(MagickFalse); } (void) FormatLocaleString(huffman_image->filename,MagickPathExtent,"tiff:%s", filename); (void) SetImageType(huffman_image,BilevelType,exception); write_info=CloneImageInfo((ImageInfo *) NULL); SetImageInfoFile(write_info,file); (void) SetImageDepth(image,1,exception); (void) SetImageType(image,BilevelType,exception); write_info->compression=Group4Compression; write_info->type=BilevelType; (void) SetImageOption(write_info,"quantum:polarity","min-is-white"); status=WriteTIFFImage(write_info,huffman_image,exception); (void) fflush(file); write_info=DestroyImageInfo(write_info); if (status == MagickFalse) { huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); return(MagickFalse); } tiff=TIFFOpen(filename,"rb"); if (tiff == (TIFF *) NULL) { huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); ThrowFileException(exception,FileOpenError,"UnableToOpenFile", image_info->filename); return(MagickFalse); } /* Allocate raw strip buffer. */ if (TIFFGetField(tiff,TIFFTAG_STRIPBYTECOUNTS,&byte_count) != 1) { TIFFClose(tiff); huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); return(MagickFalse); } strip_size=byte_count[0]; for (i=1; i < (ssize_t) TIFFNumberOfStrips(tiff); i++) if (byte_count[i] > strip_size) strip_size=byte_count[i]; buffer=(unsigned char *) AcquireQuantumMemory((size_t) strip_size, sizeof(*buffer)); if (buffer == (unsigned char *) NULL) { TIFFClose(tiff); huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image_info->filename); } /* Compress runlength encoded to 2D Huffman pixels. */ for (i=0; i < (ssize_t) TIFFNumberOfStrips(tiff); i++) { count=(ssize_t) TIFFReadRawStrip(tiff,(uint32) i,buffer,strip_size); if (WriteBlob(image,(size_t) count,buffer) != count) status=MagickFalse; } buffer=(unsigned char *) RelinquishMagickMemory(buffer); TIFFClose(tiff); huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); (void) CloseBlob(image); return(status); } #endif #if defined(MAGICKCORE_TIFF_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P T I F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePTIFImage() writes an image in the pyrimid-encoded Tagged image file % format. % % The format of the WritePTIFImage method is: % % MagickBooleanType WritePTIFImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WritePTIFImage(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { Image *images, *next, *pyramid_image; ImageInfo *write_info; MagickBooleanType status; PointInfo resolution; size_t columns, rows; /* Create pyramid-encoded TIFF image. */ images=NewImageList(); for (next=image; next != (Image *) NULL; next=GetNextImageInList(next)) { Image *clone_image; clone_image=CloneImage(next,0,0,MagickFalse,exception); if (clone_image == (Image *) NULL) break; clone_image->previous=NewImageList(); clone_image->next=NewImageList(); (void) SetImageProperty(clone_image,"tiff:subfiletype","none",exception); AppendImageToList(&images,clone_image); columns=next->columns; rows=next->rows; resolution=next->resolution; while ((columns > 64) && (rows > 64)) { columns/=2; rows/=2; resolution.x/=2; resolution.y/=2; pyramid_image=ResizeImage(next,columns,rows,image->filter,exception); if (pyramid_image == (Image *) NULL) break; pyramid_image->resolution=resolution; (void) SetImageProperty(pyramid_image,"tiff:subfiletype","REDUCEDIMAGE", exception); AppendImageToList(&images,pyramid_image); } } images=GetFirstImageInList(images); /* Write pyramid-encoded TIFF image. */ write_info=CloneImageInfo(image_info); write_info->adjoin=MagickTrue; (void) CopyMagickString(write_info->magick,"TIFF",MagickPathExtent); (void) CopyMagickString(images->magick,"TIFF",MagickPathExtent); status=WriteTIFFImage(write_info,images,exception); images=DestroyImageList(images); write_info=DestroyImageInfo(write_info); return(status); } #endif #if defined(MAGICKCORE_TIFF_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % W r i t e T I F F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteTIFFImage() writes an image in the Tagged image file format. % % The format of the WriteTIFFImage method is: % % MagickBooleanType WriteTIFFImage(const ImageInfo *image_info, % Image *image,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. % */ typedef struct _TIFFInfo { RectangleInfo tile_geometry; unsigned char *scanline, *scanlines, *pixels; } TIFFInfo; static void DestroyTIFFInfo(TIFFInfo *tiff_info) { assert(tiff_info != (TIFFInfo *) NULL); if (tiff_info->scanlines != (unsigned char *) NULL) tiff_info->scanlines=(unsigned char *) RelinquishMagickMemory( tiff_info->scanlines); if (tiff_info->pixels != (unsigned char *) NULL) tiff_info->pixels=(unsigned char *) RelinquishMagickMemory( tiff_info->pixels); } static MagickBooleanType EncodeLabImage(Image *image,ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; ssize_t y; status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double a, b; a=QuantumScale*GetPixela(image,q)-0.5; if (a < 0.0) a+=1.0; b=QuantumScale*GetPixelb(image,q)-0.5; if (b < 0.0) b+=1.0; SetPixela(image,QuantumRange*a,q); SetPixelb(image,QuantumRange*b,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status); } static MagickBooleanType GetTIFFInfo(const ImageInfo *image_info, TIFF *tiff,TIFFInfo *tiff_info) { const char *option; MagickStatusType flags; uint32 tile_columns, tile_rows; assert(tiff_info != (TIFFInfo *) NULL); (void) ResetMagickMemory(tiff_info,0,sizeof(*tiff_info)); option=GetImageOption(image_info,"tiff:tile-geometry"); if (option == (const char *) NULL) { uint32 rows_per_strip; option=GetImageOption(image_info,"tiff:rows-per-strip"); if (option != (const char *) NULL) rows_per_strip=(size_t) strtol(option,(char **) NULL,10); else if (TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&rows_per_strip) == 0) rows_per_strip=0; /* use default */ rows_per_strip=TIFFDefaultStripSize(tiff,rows_per_strip); (void) TIFFSetField(tiff,TIFFTAG_ROWSPERSTRIP,rows_per_strip); return(MagickTrue); } /* Create tiled TIFF, ignore "tiff:rows-per-strip". */ flags=ParseAbsoluteGeometry(option,&tiff_info->tile_geometry); if ((flags & HeightValue) == 0) tiff_info->tile_geometry.height=tiff_info->tile_geometry.width; tile_columns=(uint32) tiff_info->tile_geometry.width; tile_rows=(uint32) tiff_info->tile_geometry.height; TIFFDefaultTileSize(tiff,&tile_columns,&tile_rows); (void) TIFFSetField(tiff,TIFFTAG_TILEWIDTH,tile_columns); (void) TIFFSetField(tiff,TIFFTAG_TILELENGTH,tile_rows); tiff_info->tile_geometry.width=tile_columns; tiff_info->tile_geometry.height=tile_rows; tiff_info->scanlines=(unsigned char *) AcquireQuantumMemory((size_t) tile_rows*TIFFScanlineSize(tiff),sizeof(*tiff_info->scanlines)); tiff_info->pixels=(unsigned char *) AcquireQuantumMemory((size_t) tile_rows*TIFFTileSize(tiff),sizeof(*tiff_info->scanlines)); if ((tiff_info->scanlines == (unsigned char *) NULL) || (tiff_info->pixels == (unsigned char *) NULL)) { DestroyTIFFInfo(tiff_info); return(MagickFalse); } return(MagickTrue); } static int32 TIFFWritePixels(TIFF *tiff,TIFFInfo *tiff_info,ssize_t row, tsample_t sample,Image *image) { int32 status; register ssize_t i; register unsigned char *p, *q; size_t number_tiles, tile_width; ssize_t bytes_per_pixel, j, k, l; if (TIFFIsTiled(tiff) == 0) return(TIFFWriteScanline(tiff,tiff_info->scanline,(uint32) row,sample)); /* Fill scanlines to tile height. */ i=(ssize_t) (row % tiff_info->tile_geometry.height)*TIFFScanlineSize(tiff); (void) CopyMagickMemory(tiff_info->scanlines+i,(char *) tiff_info->scanline, (size_t) TIFFScanlineSize(tiff)); if (((size_t) (row % tiff_info->tile_geometry.height) != (tiff_info->tile_geometry.height-1)) && (row != (ssize_t) (image->rows-1))) return(0); /* Write tile to TIFF image. */ status=0; bytes_per_pixel=TIFFTileSize(tiff)/(ssize_t) ( tiff_info->tile_geometry.height*tiff_info->tile_geometry.width); number_tiles=(image->columns+tiff_info->tile_geometry.width)/ tiff_info->tile_geometry.width; for (i=0; i < (ssize_t) number_tiles; i++) { tile_width=(i == (ssize_t) (number_tiles-1)) ? image->columns-(i* tiff_info->tile_geometry.width) : tiff_info->tile_geometry.width; for (j=0; j < (ssize_t) ((row % tiff_info->tile_geometry.height)+1); j++) for (k=0; k < (ssize_t) tile_width; k++) { if (bytes_per_pixel == 0) { p=tiff_info->scanlines+(j*TIFFScanlineSize(tiff)+(i* tiff_info->tile_geometry.width+k)/8); q=tiff_info->pixels+(j*TIFFTileRowSize(tiff)+k/8); *q++=(*p++); continue; } p=tiff_info->scanlines+(j*TIFFScanlineSize(tiff)+(i* tiff_info->tile_geometry.width+k)*bytes_per_pixel); q=tiff_info->pixels+(j*TIFFTileRowSize(tiff)+k*bytes_per_pixel); for (l=0; l < bytes_per_pixel; l++) *q++=(*p++); } if ((i*tiff_info->tile_geometry.width) != image->columns) status=TIFFWriteTile(tiff,tiff_info->pixels,(uint32) (i* tiff_info->tile_geometry.width),(uint32) ((row/ tiff_info->tile_geometry.height)*tiff_info->tile_geometry.height),0, sample); if (status < 0) break; } return(status); } static void TIFFSetProfiles(TIFF *tiff,Image *image) { const char *name; const StringInfo *profile; if (image->profiles == (void *) NULL) return; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (GetStringInfoLength(profile) == 0) { name=GetNextImageProfile(image); continue; } #if defined(TIFFTAG_XMLPACKET) if (LocaleCompare(name,"xmp") == 0) (void) TIFFSetField(tiff,TIFFTAG_XMLPACKET,(uint32) GetStringInfoLength( profile),GetStringInfoDatum(profile)); #endif #if defined(TIFFTAG_ICCPROFILE) if (LocaleCompare(name,"icc") == 0) (void) TIFFSetField(tiff,TIFFTAG_ICCPROFILE,(uint32) GetStringInfoLength( profile),GetStringInfoDatum(profile)); #endif if (LocaleCompare(name,"iptc") == 0) { size_t length; StringInfo *iptc_profile; iptc_profile=CloneStringInfo(profile); length=GetStringInfoLength(profile)+4-(GetStringInfoLength(profile) & 0x03); SetStringInfoLength(iptc_profile,length); if (TIFFIsByteSwapped(tiff)) TIFFSwabArrayOfLong((uint32 *) GetStringInfoDatum(iptc_profile), (unsigned long) (length/4)); (void) TIFFSetField(tiff,TIFFTAG_RICHTIFFIPTC,(uint32) GetStringInfoLength(iptc_profile)/4,GetStringInfoDatum(iptc_profile)); iptc_profile=DestroyStringInfo(iptc_profile); } #if defined(TIFFTAG_PHOTOSHOP) if (LocaleCompare(name,"8bim") == 0) (void) TIFFSetField(tiff,TIFFTAG_PHOTOSHOP,(uint32) GetStringInfoLength(profile),GetStringInfoDatum(profile)); #endif if (LocaleCompare(name,"tiff:37724") == 0) (void) TIFFSetField(tiff,37724,(uint32) GetStringInfoLength(profile), GetStringInfoDatum(profile)); if (LocaleCompare(name,"tiff:34118") == 0) (void) TIFFSetField(tiff,34118,(uint32) GetStringInfoLength(profile), GetStringInfoDatum(profile)); name=GetNextImageProfile(image); } } static void TIFFSetProperties(TIFF *tiff,const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { const char *value; value=GetImageArtifact(image,"tiff:document"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_DOCUMENTNAME,value); value=GetImageArtifact(image,"tiff:hostcomputer"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_HOSTCOMPUTER,value); value=GetImageArtifact(image,"tiff:artist"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_ARTIST,value); value=GetImageArtifact(image,"tiff:timestamp"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_DATETIME,value); value=GetImageArtifact(image,"tiff:make"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_MAKE,value); value=GetImageArtifact(image,"tiff:model"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_MODEL,value); value=GetImageArtifact(image,"tiff:software"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_SOFTWARE,value); value=GetImageArtifact(image,"tiff:copyright"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_COPYRIGHT,value); value=GetImageArtifact(image,"kodak-33423"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,33423,value); value=GetImageArtifact(image,"kodak-36867"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,36867,value); value=GetImageProperty(image,"label",exception); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_PAGENAME,value); value=GetImageProperty(image,"comment",exception); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_IMAGEDESCRIPTION,value); value=GetImageArtifact(image,"tiff:subfiletype"); if (value != (const char *) NULL) { if (LocaleCompare(value,"REDUCEDIMAGE") == 0) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE); else if (LocaleCompare(value,"PAGE") == 0) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE); else if (LocaleCompare(value,"MASK") == 0) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_MASK); } else { uint16 page, pages; page=(uint16) image->scene; pages=(uint16) GetImageListLength(image); if ((image_info->adjoin != MagickFalse) && (pages > 1)) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE); (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages); } } static void TIFFSetEXIFProperties(TIFF *tiff,Image *image, ExceptionInfo *exception) { #if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY) const char *value; register ssize_t i; uint32 offset; /* Write EXIF properties. */ offset=0; (void) TIFFSetField(tiff,TIFFTAG_SUBIFD,1,&offset); for (i=0; exif_info[i].tag != 0; i++) { value=GetImageProperty(image,exif_info[i].property,exception); if (value == (const char *) NULL) continue; switch (exif_info[i].type) { case TIFF_ASCII: { (void) TIFFSetField(tiff,exif_info[i].tag,value); break; } case TIFF_SHORT: { uint16 field; field=(uint16) StringToLong(value); (void) TIFFSetField(tiff,exif_info[i].tag,field); break; } case TIFF_LONG: { uint16 field; field=(uint16) StringToLong(value); (void) TIFFSetField(tiff,exif_info[i].tag,field); break; } case TIFF_RATIONAL: case TIFF_SRATIONAL: { float field; field=StringToDouble(value,(char **) NULL); (void) TIFFSetField(tiff,exif_info[i].tag,field); break; } default: break; } } /* (void) TIFFSetField(tiff,TIFFTAG_EXIFIFD,offset); */ #else (void) tiff; (void) image; #endif } static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { const char *mode, *option; CompressionType compression; EndianType endian_type; MagickBooleanType debug, status; MagickOffsetType scene; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; size_t length; ssize_t y; TIFF *tiff; TIFFInfo tiff_info; uint16 bits_per_sample, compress_tag, endian, photometric; unsigned char *pixels; /* Open TIFF file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); (void) SetMagickThreadValue(tiff_exception,exception); endian_type=UndefinedEndian; option=GetImageOption(image_info,"tiff:endian"); if (option != (const char *) NULL) { if (LocaleNCompare(option,"msb",3) == 0) endian_type=MSBEndian; if (LocaleNCompare(option,"lsb",3) == 0) endian_type=LSBEndian;; } switch (endian_type) { case LSBEndian: mode="wl"; break; case MSBEndian: mode="wb"; break; default: mode="w"; break; } #if defined(TIFF_VERSION_BIG) if (LocaleCompare(image_info->magick,"TIFF64") == 0) switch (endian_type) { case LSBEndian: mode="wl8"; break; case MSBEndian: mode="wb8"; break; default: mode="w8"; break; } #endif tiff=TIFFClientOpen(image->filename,mode,(thandle_t) image,TIFFReadBlob, TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob, TIFFUnmapBlob); if (tiff == (TIFF *) NULL) return(MagickFalse); scene=0; debug=IsEventLogging(); (void) debug; do { /* Initialize TIFF fields. */ if ((image_info->type != UndefinedType) && (image_info->type != OptimizeType)) (void) SetImageType(image,image_info->type,exception); compression=UndefinedCompression; if (image->compression != JPEGCompression) compression=image->compression; if (image_info->compression != UndefinedCompression) compression=image_info->compression; switch (compression) { case FaxCompression: case Group4Compression: { (void) SetImageType(image,BilevelType,exception); (void) SetImageDepth(image,1,exception); break; } case JPEGCompression: { (void) SetImageStorageClass(image,DirectClass,exception); (void) SetImageDepth(image,8,exception); break; } default: break; } quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if ((image->storage_class != PseudoClass) && (image->depth >= 32) && (quantum_info->format == UndefinedQuantumFormat) && (IsHighDynamicRangeImage(image,exception) != MagickFalse)) { status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } if ((LocaleCompare(image_info->magick,"PTIF") == 0) && (GetPreviousImageInList(image) != (Image *) NULL)) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE); if ((image->columns != (uint32) image->columns) || (image->rows != (uint32) image->rows)) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); (void) TIFFSetField(tiff,TIFFTAG_IMAGELENGTH,(uint32) image->rows); (void) TIFFSetField(tiff,TIFFTAG_IMAGEWIDTH,(uint32) image->columns); switch (compression) { case FaxCompression: { compress_tag=COMPRESSION_CCITTFAX3; SetQuantumMinIsWhite(quantum_info,MagickTrue); break; } case Group4Compression: { compress_tag=COMPRESSION_CCITTFAX4; SetQuantumMinIsWhite(quantum_info,MagickTrue); break; } #if defined(COMPRESSION_JBIG) case JBIG1Compression: { compress_tag=COMPRESSION_JBIG; break; } #endif case JPEGCompression: { compress_tag=COMPRESSION_JPEG; break; } #if defined(COMPRESSION_LZMA) case LZMACompression: { compress_tag=COMPRESSION_LZMA; break; } #endif case LZWCompression: { compress_tag=COMPRESSION_LZW; break; } case RLECompression: { compress_tag=COMPRESSION_PACKBITS; break; } case ZipCompression: { compress_tag=COMPRESSION_ADOBE_DEFLATE; break; } case NoCompression: default: { compress_tag=COMPRESSION_NONE; break; } } #if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919) if ((compress_tag != COMPRESSION_NONE) && (TIFFIsCODECConfigured(compress_tag) == 0)) { (void) ThrowMagickException(exception,GetMagickModule(),CoderError, "CompressionNotSupported","`%s'",CommandOptionToMnemonic( MagickCompressOptions,(ssize_t) compression)); compress_tag=COMPRESSION_NONE; compression=NoCompression; } #else switch (compress_tag) { #if defined(CCITT_SUPPORT) case COMPRESSION_CCITTFAX3: case COMPRESSION_CCITTFAX4: #endif #if defined(YCBCR_SUPPORT) && defined(JPEG_SUPPORT) case COMPRESSION_JPEG: #endif #if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA) case COMPRESSION_LZMA: #endif #if defined(LZW_SUPPORT) case COMPRESSION_LZW: #endif #if defined(PACKBITS_SUPPORT) case COMPRESSION_PACKBITS: #endif #if defined(ZIP_SUPPORT) case COMPRESSION_ADOBE_DEFLATE: #endif case COMPRESSION_NONE: break; default: { (void) ThrowMagickException(exception,GetMagickModule(),CoderError, "CompressionNotSupported","`%s'",CommandOptionToMnemonic( MagickCompressOptions,(ssize_t) compression)); compress_tag=COMPRESSION_NONE; compression=NoCompression; break; } } #endif if (image->colorspace == CMYKColorspace) { photometric=PHOTOMETRIC_SEPARATED; (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,4); (void) TIFFSetField(tiff,TIFFTAG_INKSET,INKSET_CMYK); } else { /* Full color TIFF raster. */ if (image->colorspace == LabColorspace) { photometric=PHOTOMETRIC_CIELAB; EncodeLabImage(image,exception); } else if (image->colorspace == YCbCrColorspace) { photometric=PHOTOMETRIC_YCBCR; (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,1,1); (void) SetImageStorageClass(image,DirectClass,exception); (void) SetImageDepth(image,8,exception); } else photometric=PHOTOMETRIC_RGB; (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,3); if ((image_info->type != TrueColorType) && (image_info->type != TrueColorAlphaType)) { if ((image_info->type != PaletteType) && (SetImageGray(image,exception) != MagickFalse)) { photometric=(uint16) (quantum_info->min_is_white != MagickFalse ? PHOTOMETRIC_MINISWHITE : PHOTOMETRIC_MINISBLACK); (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1); if ((image->depth == 1) && (image->alpha_trait == UndefinedPixelTrait)) SetImageMonochrome(image,exception); } else if (image->storage_class == PseudoClass) { size_t depth; /* Colormapped TIFF raster. */ (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1); photometric=PHOTOMETRIC_PALETTE; depth=1; while ((GetQuantumRange(depth)+1) < image->colors) depth<<=1; status=SetQuantumDepth(image,quantum_info,depth); if (status == MagickFalse) ThrowWriterException(ResourceLimitError, "MemoryAllocationFailed"); } } } (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian); if ((compress_tag == COMPRESSION_CCITTFAX3) && (photometric != PHOTOMETRIC_MINISWHITE)) { compress_tag=COMPRESSION_NONE; endian=FILLORDER_MSB2LSB; } else if ((compress_tag == COMPRESSION_CCITTFAX4) && (photometric != PHOTOMETRIC_MINISWHITE)) { compress_tag=COMPRESSION_NONE; endian=FILLORDER_MSB2LSB; } option=GetImageOption(image_info,"tiff:fill-order"); if (option != (const char *) NULL) { if (LocaleNCompare(option,"msb",3) == 0) endian=FILLORDER_MSB2LSB; if (LocaleNCompare(option,"lsb",3) == 0) endian=FILLORDER_LSB2MSB; } (void) TIFFSetField(tiff,TIFFTAG_COMPRESSION,compress_tag); (void) TIFFSetField(tiff,TIFFTAG_FILLORDER,endian); (void) TIFFSetField(tiff,TIFFTAG_BITSPERSAMPLE,quantum_info->depth); if (image->alpha_trait != UndefinedPixelTrait) { uint16 extra_samples, sample_info[1], samples_per_pixel; /* TIFF has a matte channel. */ extra_samples=1; sample_info[0]=EXTRASAMPLE_UNASSALPHA; option=GetImageOption(image_info,"tiff:alpha"); if (option != (const char *) NULL) { if (LocaleCompare(option,"associated") == 0) sample_info[0]=EXTRASAMPLE_ASSOCALPHA; else if (LocaleCompare(option,"unspecified") == 0) sample_info[0]=EXTRASAMPLE_UNSPECIFIED; } (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL, &samples_per_pixel); (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,samples_per_pixel+1); (void) TIFFSetField(tiff,TIFFTAG_EXTRASAMPLES,extra_samples, &sample_info); if (sample_info[0] == EXTRASAMPLE_ASSOCALPHA) SetQuantumAlphaType(quantum_info,AssociatedQuantumAlpha); } (void) TIFFSetField(tiff,TIFFTAG_PHOTOMETRIC,photometric); switch (quantum_info->format) { case FloatingPointQuantumFormat: { (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_IEEEFP); (void) TIFFSetField(tiff,TIFFTAG_SMINSAMPLEVALUE,quantum_info->minimum); (void) TIFFSetField(tiff,TIFFTAG_SMAXSAMPLEVALUE,quantum_info->maximum); break; } case SignedQuantumFormat: { (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_INT); break; } case UnsignedQuantumFormat: { (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_UINT); break; } default: break; } (void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,ORIENTATION_TOPLEFT); (void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_CONTIG); if (photometric == PHOTOMETRIC_RGB) if ((image_info->interlace == PlaneInterlace) || (image_info->interlace == PartitionInterlace)) (void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_SEPARATE); switch (compress_tag) { case COMPRESSION_JPEG: { #if defined(JPEG_SUPPORT) const char *sampling_factor; GeometryInfo geometry_info; MagickStatusType flags; if (image_info->quality != UndefinedCompressionQuality) (void) TIFFSetField(tiff,TIFFTAG_JPEGQUALITY,image_info->quality); (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RAW); if (IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) { const char *value; (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RGB); sampling_factor=(const char *) NULL; value=GetImageProperty(image,"jpeg:sampling-factor",exception); if (value != (char *) NULL) { sampling_factor=value; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Input sampling-factors=%s",sampling_factor); } if (image_info->sampling_factor != (char *) NULL) sampling_factor=image_info->sampling_factor; if (sampling_factor != (const char *) NULL) { flags=ParseGeometry(sampling_factor,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=geometry_info.rho; if (image->colorspace == YCbCrColorspace) (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,(uint16) geometry_info.rho,(uint16) geometry_info.sigma); } } (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (bits_per_sample == 12) (void) TIFFSetField(tiff,TIFFTAG_JPEGTABLESMODE,JPEGTABLESMODE_QUANT); #endif break; } case COMPRESSION_ADOBE_DEFLATE: { (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL); (void) TIFFSetField(tiff,TIFFTAG_ZIPQUALITY,(long) ( image_info->quality == UndefinedCompressionQuality ? 7 : MagickMin((ssize_t) image_info->quality/10,9))); break; } case COMPRESSION_CCITTFAX3: { /* Byte-aligned EOL. */ (void) TIFFSetField(tiff,TIFFTAG_GROUP3OPTIONS,4); break; } case COMPRESSION_CCITTFAX4: break; #if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA) case COMPRESSION_LZMA: { if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL); (void) TIFFSetField(tiff,TIFFTAG_LZMAPRESET,(long) ( image_info->quality == UndefinedCompressionQuality ? 7 : MagickMin((ssize_t) image_info->quality/10,9))); break; } #endif case COMPRESSION_LZW: { (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL); break; } default: break; } if ((image->resolution.x != 0.0) && (image->resolution.y != 0.0)) { unsigned short units; /* Set image resolution. */ units=RESUNIT_NONE; if (image->units == PixelsPerInchResolution) units=RESUNIT_INCH; if (image->units == PixelsPerCentimeterResolution) units=RESUNIT_CENTIMETER; (void) TIFFSetField(tiff,TIFFTAG_RESOLUTIONUNIT,(uint16) units); (void) TIFFSetField(tiff,TIFFTAG_XRESOLUTION,image->resolution.x); (void) TIFFSetField(tiff,TIFFTAG_YRESOLUTION,image->resolution.y); if ((image->page.x < 0) || (image->page.y < 0)) (void) ThrowMagickException(exception,GetMagickModule(),CoderError, "TIFF: negative image positions unsupported","%s",image->filename); if ((image->page.x > 0) && (image->resolution.x > 0.0)) { /* Set horizontal image position. */ (void) TIFFSetField(tiff,TIFFTAG_XPOSITION,(float) image->page.x/ image->resolution.x); } if ((image->page.y > 0) && (image->resolution.y > 0.0)) { /* Set vertical image position. */ (void) TIFFSetField(tiff,TIFFTAG_YPOSITION,(float) image->page.y/ image->resolution.y); } } if (image->chromaticity.white_point.x != 0.0) { float chromaticity[6]; /* Set image chromaticity. */ chromaticity[0]=(float) image->chromaticity.red_primary.x; chromaticity[1]=(float) image->chromaticity.red_primary.y; chromaticity[2]=(float) image->chromaticity.green_primary.x; chromaticity[3]=(float) image->chromaticity.green_primary.y; chromaticity[4]=(float) image->chromaticity.blue_primary.x; chromaticity[5]=(float) image->chromaticity.blue_primary.y; (void) TIFFSetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,chromaticity); chromaticity[0]=(float) image->chromaticity.white_point.x; chromaticity[1]=(float) image->chromaticity.white_point.y; (void) TIFFSetField(tiff,TIFFTAG_WHITEPOINT,chromaticity); } if ((LocaleCompare(image_info->magick,"PTIF") != 0) && (image_info->adjoin != MagickFalse) && (GetImageListLength(image) > 1)) { (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE); if (image->scene != 0) (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,(uint16) image->scene, GetImageListLength(image)); } if (image->orientation != UndefinedOrientation) (void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,(uint16) image->orientation); (void) TIFFSetProfiles(tiff,image); { uint16 page, pages; page=(uint16) scene; pages=(uint16) GetImageListLength(image); if ((LocaleCompare(image_info->magick,"PTIF") != 0) && (image_info->adjoin != MagickFalse) && (pages > 1)) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE); (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages); } (void) TIFFSetProperties(tiff,image_info,image,exception); DisableMSCWarning(4127) if (0) RestoreMSCWarning (void) TIFFSetEXIFProperties(tiff,image,exception); /* Write image scanlines. */ if (GetTIFFInfo(image_info,tiff,&tiff_info) == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); quantum_info->endian=LSBEndian; pixels=(unsigned char *) GetQuantumPixels(quantum_info); tiff_info.scanline=(unsigned char *) GetQuantumPixels(quantum_info); switch (photometric) { case PHOTOMETRIC_CIELAB: case PHOTOMETRIC_YCBCR: case PHOTOMETRIC_RGB: { /* RGB TIFF image. */ switch (image_info->interlace) { case NoInterlace: default: { quantum_type=RGBQuantum; if (image->alpha_trait != UndefinedPixelTrait) quantum_type=RGBAQuantum; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); (void) length; if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } break; } case PlaneInterlace: case PartitionInterlace: { /* Plane interlacing: RRRRRR...GGGGGG...BBBBBB... */ for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, RedQuantum,pixels,exception); if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,100,400); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, GreenQuantum,pixels,exception); if (TIFFWritePixels(tiff,&tiff_info,y,1,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,200,400); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, BlueQuantum,pixels,exception); if (TIFFWritePixels(tiff,&tiff_info,y,2,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,300,400); if (status == MagickFalse) break; } if (image->alpha_trait != UndefinedPixelTrait) for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,AlphaQuantum,pixels,exception); if (TIFFWritePixels(tiff,&tiff_info,y,3,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,400,400); if (status == MagickFalse) break; } break; } } break; } case PHOTOMETRIC_SEPARATED: { /* CMYK TIFF image. */ quantum_type=CMYKQuantum; if (image->alpha_trait != UndefinedPixelTrait) quantum_type=CMYKAQuantum; if (image->colorspace != CMYKColorspace) (void) TransformImageColorspace(image,CMYKColorspace,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case PHOTOMETRIC_PALETTE: { uint16 *blue, *green, *red; /* Colormapped TIFF image. */ red=(uint16 *) AcquireQuantumMemory(65536,sizeof(*red)); green=(uint16 *) AcquireQuantumMemory(65536,sizeof(*green)); blue=(uint16 *) AcquireQuantumMemory(65536,sizeof(*blue)); if ((red == (uint16 *) NULL) || (green == (uint16 *) NULL) || (blue == (uint16 *) NULL)) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize TIFF colormap. */ (void) ResetMagickMemory(red,0,65536*sizeof(*red)); (void) ResetMagickMemory(green,0,65536*sizeof(*green)); (void) ResetMagickMemory(blue,0,65536*sizeof(*blue)); for (i=0; i < (ssize_t) image->colors; i++) { red[i]=ScaleQuantumToShort(image->colormap[i].red); green[i]=ScaleQuantumToShort(image->colormap[i].green); blue[i]=ScaleQuantumToShort(image->colormap[i].blue); } (void) TIFFSetField(tiff,TIFFTAG_COLORMAP,red,green,blue); red=(uint16 *) RelinquishMagickMemory(red); green=(uint16 *) RelinquishMagickMemory(green); blue=(uint16 *) RelinquishMagickMemory(blue); } default: { /* Convert PseudoClass packets to contiguous grayscale scanlines. */ quantum_type=IndexQuantum; if (image->alpha_trait != UndefinedPixelTrait) { if (photometric != PHOTOMETRIC_PALETTE) quantum_type=GrayAlphaQuantum; else quantum_type=IndexAlphaQuantum; } else if (photometric != PHOTOMETRIC_PALETTE) quantum_type=GrayQuantum; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } } quantum_info=DestroyQuantumInfo(quantum_info); if (image->colorspace == LabColorspace) DecodeLabImage(image,exception); DestroyTIFFInfo(&tiff_info); DisableMSCWarning(4127) if (0 && (image_info->verbose != MagickFalse)) RestoreMSCWarning TIFFPrintDirectory(tiff,stdout,MagickFalse); (void) TIFFWriteDirectory(tiff); image=SyncNextImageInList(image); if (image == (Image *) NULL) break; status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); TIFFClose(tiff); return(MagickTrue); } #endif
./CrossVul/dataset_final_sorted/CWE-119/c/bad_5359_0
crossvul-cpp_data_bad_344_6
/* * pkcs15-sc-hsm.c : Initialize PKCS#15 emulation * * Copyright (C) 2012 Andreas Schwier, CardContact, Minden, Germany * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <string.h> #include <stdio.h> #include "internal.h" #include "pkcs15.h" #include "asn1.h" #include "common/compat_strlcpy.h" #include "common/compat_strnlen.h" #include "card-sc-hsm.h" extern struct sc_aid sc_hsm_aid; void sc_hsm_set_serialnr(sc_card_t *card, char *serial); static struct ec_curve curves[] = { { { (unsigned char *) "\x2A\x86\x48\xCE\x3D\x03\x01\x01", 8}, // secp192r1 aka prime192r1 { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", 24}, { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFC", 24}, { (unsigned char *) "\x64\x21\x05\x19\xE5\x9C\x80\xE7\x0F\xA7\xE9\xAB\x72\x24\x30\x49\xFE\xB8\xDE\xEC\xC1\x46\xB9\xB1", 24}, { (unsigned char *) "\x04\x18\x8D\xA8\x0E\xB0\x30\x90\xF6\x7C\xBF\x20\xEB\x43\xA1\x88\x00\xF4\xFF\x0A\xFD\x82\xFF\x10\x12\x07\x19\x2B\x95\xFF\xC8\xDA\x78\x63\x10\x11\xED\x6B\x24\xCD\xD5\x73\xF9\x77\xA1\x1E\x79\x48\x11", 49}, { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x99\xDE\xF8\x36\x14\x6B\xC9\xB1\xB4\xD2\x28\x31", 24}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2A\x86\x48\xCE\x3D\x03\x01\x07", 8}, // secp256r1 aka prime256r1 { (unsigned char *) "\xFF\xFF\xFF\xFF\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", 32}, { (unsigned char *) "\xFF\xFF\xFF\xFF\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFC", 32}, { (unsigned char *) "\x5A\xC6\x35\xD8\xAA\x3A\x93\xE7\xB3\xEB\xBD\x55\x76\x98\x86\xBC\x65\x1D\x06\xB0\xCC\x53\xB0\xF6\x3B\xCE\x3C\x3E\x27\xD2\x60\x4B", 32}, { (unsigned char *) "\x04\x6B\x17\xD1\xF2\xE1\x2C\x42\x47\xF8\xBC\xE6\xE5\x63\xA4\x40\xF2\x77\x03\x7D\x81\x2D\xEB\x33\xA0\xF4\xA1\x39\x45\xD8\x98\xC2\x96\x4F\xE3\x42\xE2\xFE\x1A\x7F\x9B\x8E\xE7\xEB\x4A\x7C\x0F\x9E\x16\x2B\xCE\x33\x57\x6B\x31\x5E\xCE\xCB\xB6\x40\x68\x37\xBF\x51\xF5", 65}, { (unsigned char *) "\xFF\xFF\xFF\xFF\x00\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xBC\xE6\xFA\xAD\xA7\x17\x9E\x84\xF3\xB9\xCA\xC2\xFC\x63\x25\x51", 32}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2B\x24\x03\x03\x02\x08\x01\x01\x03", 9}, // brainpoolP192r1 { (unsigned char *) "\xC3\x02\xF4\x1D\x93\x2A\x36\xCD\xA7\xA3\x46\x30\x93\xD1\x8D\xB7\x8F\xCE\x47\x6D\xE1\xA8\x62\x97", 24}, { (unsigned char *) "\x6A\x91\x17\x40\x76\xB1\xE0\xE1\x9C\x39\xC0\x31\xFE\x86\x85\xC1\xCA\xE0\x40\xE5\xC6\x9A\x28\xEF", 24}, { (unsigned char *) "\x46\x9A\x28\xEF\x7C\x28\xCC\xA3\xDC\x72\x1D\x04\x4F\x44\x96\xBC\xCA\x7E\xF4\x14\x6F\xBF\x25\xC9", 24}, { (unsigned char *) "\x04\xC0\xA0\x64\x7E\xAA\xB6\xA4\x87\x53\xB0\x33\xC5\x6C\xB0\xF0\x90\x0A\x2F\x5C\x48\x53\x37\x5F\xD6\x14\xB6\x90\x86\x6A\xBD\x5B\xB8\x8B\x5F\x48\x28\xC1\x49\x00\x02\xE6\x77\x3F\xA2\xFA\x29\x9B\x8F", 49}, { (unsigned char *) "\xC3\x02\xF4\x1D\x93\x2A\x36\xCD\xA7\xA3\x46\x2F\x9E\x9E\x91\x6B\x5B\xE8\xF1\x02\x9A\xC4\xAC\xC1", 24}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2B\x24\x03\x03\x02\x08\x01\x01\x05", 9}, // brainpoolP224r1 { (unsigned char *) "\xD7\xC1\x34\xAA\x26\x43\x66\x86\x2A\x18\x30\x25\x75\xD1\xD7\x87\xB0\x9F\x07\x57\x97\xDA\x89\xF5\x7E\xC8\xC0\xFF", 28}, { (unsigned char *) "\x68\xA5\xE6\x2C\xA9\xCE\x6C\x1C\x29\x98\x03\xA6\xC1\x53\x0B\x51\x4E\x18\x2A\xD8\xB0\x04\x2A\x59\xCA\xD2\x9F\x43", 28}, { (unsigned char *) "\x25\x80\xF6\x3C\xCF\xE4\x41\x38\x87\x07\x13\xB1\xA9\x23\x69\xE3\x3E\x21\x35\xD2\x66\xDB\xB3\x72\x38\x6C\x40\x0B", 28}, { (unsigned char *) "\x04\x0D\x90\x29\xAD\x2C\x7E\x5C\xF4\x34\x08\x23\xB2\xA8\x7D\xC6\x8C\x9E\x4C\xE3\x17\x4C\x1E\x6E\xFD\xEE\x12\xC0\x7D\x58\xAA\x56\xF7\x72\xC0\x72\x6F\x24\xC6\xB8\x9E\x4E\xCD\xAC\x24\x35\x4B\x9E\x99\xCA\xA3\xF6\xD3\x76\x14\x02\xCD", 57}, { (unsigned char *) "\xD7\xC1\x34\xAA\x26\x43\x66\x86\x2A\x18\x30\x25\x75\xD0\xFB\x98\xD1\x16\xBC\x4B\x6D\xDE\xBC\xA3\xA5\xA7\x93\x9F", 28}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2B\x24\x03\x03\x02\x08\x01\x01\x07", 9}, // brainpoolP256r1 { (unsigned char *) "\xA9\xFB\x57\xDB\xA1\xEE\xA9\xBC\x3E\x66\x0A\x90\x9D\x83\x8D\x72\x6E\x3B\xF6\x23\xD5\x26\x20\x28\x20\x13\x48\x1D\x1F\x6E\x53\x77", 32}, { (unsigned char *) "\x7D\x5A\x09\x75\xFC\x2C\x30\x57\xEE\xF6\x75\x30\x41\x7A\xFF\xE7\xFB\x80\x55\xC1\x26\xDC\x5C\x6C\xE9\x4A\x4B\x44\xF3\x30\xB5\xD9", 32}, { (unsigned char *) "\x26\xDC\x5C\x6C\xE9\x4A\x4B\x44\xF3\x30\xB5\xD9\xBB\xD7\x7C\xBF\x95\x84\x16\x29\x5C\xF7\xE1\xCE\x6B\xCC\xDC\x18\xFF\x8C\x07\xB6", 32}, { (unsigned char *) "\x04\x8B\xD2\xAE\xB9\xCB\x7E\x57\xCB\x2C\x4B\x48\x2F\xFC\x81\xB7\xAF\xB9\xDE\x27\xE1\xE3\xBD\x23\xC2\x3A\x44\x53\xBD\x9A\xCE\x32\x62\x54\x7E\xF8\x35\xC3\xDA\xC4\xFD\x97\xF8\x46\x1A\x14\x61\x1D\xC9\xC2\x77\x45\x13\x2D\xED\x8E\x54\x5C\x1D\x54\xC7\x2F\x04\x69\x97", 65}, { (unsigned char *) "\xA9\xFB\x57\xDB\xA1\xEE\xA9\xBC\x3E\x66\x0A\x90\x9D\x83\x8D\x71\x8C\x39\x7A\xA3\xB5\x61\xA6\xF7\x90\x1E\x0E\x82\x97\x48\x56\xA7", 32}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2B\x24\x03\x03\x02\x08\x01\x01\x09", 9}, // brainpoolP320r1 { (unsigned char *) "\xD3\x5E\x47\x20\x36\xBC\x4F\xB7\xE1\x3C\x78\x5E\xD2\x01\xE0\x65\xF9\x8F\xCF\xA6\xF6\xF4\x0D\xEF\x4F\x92\xB9\xEC\x78\x93\xEC\x28\xFC\xD4\x12\xB1\xF1\xB3\x2E\x27", 40}, { (unsigned char *) "\x3E\xE3\x0B\x56\x8F\xBA\xB0\xF8\x83\xCC\xEB\xD4\x6D\x3F\x3B\xB8\xA2\xA7\x35\x13\xF5\xEB\x79\xDA\x66\x19\x0E\xB0\x85\xFF\xA9\xF4\x92\xF3\x75\xA9\x7D\x86\x0E\xB4", 40}, { (unsigned char *) "\x52\x08\x83\x94\x9D\xFD\xBC\x42\xD3\xAD\x19\x86\x40\x68\x8A\x6F\xE1\x3F\x41\x34\x95\x54\xB4\x9A\xCC\x31\xDC\xCD\x88\x45\x39\x81\x6F\x5E\xB4\xAC\x8F\xB1\xF1\xA6", 40}, { (unsigned char *) "\x04\x43\xBD\x7E\x9A\xFB\x53\xD8\xB8\x52\x89\xBC\xC4\x8E\xE5\xBF\xE6\xF2\x01\x37\xD1\x0A\x08\x7E\xB6\xE7\x87\x1E\x2A\x10\xA5\x99\xC7\x10\xAF\x8D\x0D\x39\xE2\x06\x11\x14\xFD\xD0\x55\x45\xEC\x1C\xC8\xAB\x40\x93\x24\x7F\x77\x27\x5E\x07\x43\xFF\xED\x11\x71\x82\xEA\xA9\xC7\x78\x77\xAA\xAC\x6A\xC7\xD3\x52\x45\xD1\x69\x2E\x8E\xE1", 81}, { (unsigned char *) "\xD3\x5E\x47\x20\x36\xBC\x4F\xB7\xE1\x3C\x78\x5E\xD2\x01\xE0\x65\xF9\x8F\xCF\xA5\xB6\x8F\x12\xA3\x2D\x48\x2E\xC7\xEE\x86\x58\xE9\x86\x91\x55\x5B\x44\xC5\x93\x11", 40}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2B\x81\x04\x00\x1F", 5}, // secp192k1 { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF\xEE\x37", 24}, { (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 24}, { (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03", 24}, { (unsigned char *) "\x04\xDB\x4F\xF1\x0E\xC0\x57\xE9\xAE\x26\xB0\x7D\x02\x80\xB7\xF4\x34\x1D\xA5\xD1\xB1\xEA\xE0\x6C\x7D\x9B\x2F\x2F\x6D\x9C\x56\x28\xA7\x84\x41\x63\xD0\x15\xBE\x86\x34\x40\x82\xAA\x88\xD9\x5E\x2F\x9D", 49}, { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\x26\xF2\xFC\x17\x0F\x69\x46\x6A\x74\xDE\xFD\x8D", 24}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2B\x81\x04\x00\x0A", 5}, // secp256k1 { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF\xFC\x2F", 32}, { (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 32}, { (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x07", 32}, { (unsigned char *) "\x04\x79\xBE\x66\x7E\xF9\xDC\xBB\xAC\x55\xA0\x62\x95\xCE\x87\x0B\x07\x02\x9B\xFC\xDB\x2D\xCE\x28\xD9\x59\xF2\x81\x5B\x16\xF8\x17\x98\x48\x3A\xDA\x77\x26\xA3\xC4\x65\x5D\xA4\xFB\xFC\x0E\x11\x08\xA8\xFD\x17\xB4\x48\xA6\x85\x54\x19\x9C\x47\xD0\x8F\xFB\x10\xD4\xB8", 65}, { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xBA\xAE\xDC\xE6\xAF\x48\xA0\x3B\xBF\xD2\x5E\x8C\xD0\x36\x41\x41", 32}, { (unsigned char *) "\x01", 1} }, { { NULL, 0}, { NULL, 0}, { NULL, 0}, { NULL, 0}, { NULL, 0}, { NULL, 0}, { NULL, 0} } }; #define C_ASN1_CVC_PUBKEY_SIZE 10 static const struct sc_asn1_entry c_asn1_cvc_pubkey[C_ASN1_CVC_PUBKEY_SIZE] = { { "publicKeyOID", SC_ASN1_OBJECT, SC_ASN1_UNI | SC_ASN1_OBJECT, 0, NULL, NULL }, { "primeOrModulus", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 1, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "coefficientAorExponent", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 2, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "coefficientB", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 3, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "basePointG", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 4, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "order", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 5, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "publicPoint", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 6, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "cofactor", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 7, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "modulusSize", SC_ASN1_INTEGER, SC_ASN1_UNI | SC_ASN1_INTEGER, SC_ASN1_OPTIONAL, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; #define C_ASN1_CVC_BODY_SIZE 5 static const struct sc_asn1_entry c_asn1_cvc_body[C_ASN1_CVC_BODY_SIZE] = { { "certificateProfileIdentifier", SC_ASN1_INTEGER, SC_ASN1_APP | 0x1F29, 0, NULL, NULL }, { "certificationAuthorityReference", SC_ASN1_PRINTABLESTRING, SC_ASN1_APP | 2, 0, NULL, NULL }, { "publicKey", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 0x1F49, 0, NULL, NULL }, { "certificateHolderReference", SC_ASN1_PRINTABLESTRING, SC_ASN1_APP | 0x1F20, 0, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; #define C_ASN1_CVCERT_SIZE 3 static const struct sc_asn1_entry c_asn1_cvcert[C_ASN1_CVCERT_SIZE] = { { "certificateBody", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 0x1F4E, 0, NULL, NULL }, { "signature", SC_ASN1_OCTET_STRING, SC_ASN1_APP | 0x1F37, SC_ASN1_ALLOC, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; #define C_ASN1_CVC_SIZE 2 static const struct sc_asn1_entry c_asn1_cvc[C_ASN1_CVC_SIZE] = { { "certificate", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 0x1F21, 0, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; #define C_ASN1_AUTHREQ_SIZE 4 static const struct sc_asn1_entry c_asn1_authreq[C_ASN1_AUTHREQ_SIZE] = { { "certificate", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 0x1F21, 0, NULL, NULL }, { "outerCAR", SC_ASN1_PRINTABLESTRING, SC_ASN1_APP | 2, 0, NULL, NULL }, { "signature", SC_ASN1_OCTET_STRING, SC_ASN1_APP | 0x1F37, SC_ASN1_ALLOC, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; #define C_ASN1_REQ_SIZE 2 static const struct sc_asn1_entry c_asn1_req[C_ASN1_REQ_SIZE] = { { "authenticatedrequest", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 7, 0, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; static int read_file(sc_pkcs15_card_t * p15card, u8 fid[2], u8 *efbin, size_t *len, int optional) { sc_path_t path; int r; sc_path_set(&path, SC_PATH_TYPE_FILE_ID, fid, 2, 0, 0); /* look this up with our AID */ path.aid = sc_hsm_aid; /* we don't have a pre-known size of the file */ path.count = -1; if (!p15card->opts.use_file_cache || !efbin || SC_SUCCESS != sc_pkcs15_read_cached_file(p15card, &path, &efbin, len)) { /* avoid re-selection of SC-HSM */ path.aid.len = 0; r = sc_select_file(p15card->card, &path, NULL); if (r < 0) { sc_log(p15card->card->ctx, "Could not select EF"); } else { r = sc_read_binary(p15card->card, 0, efbin, *len, 0); } if (r < 0) { sc_log(p15card->card->ctx, "Could not read EF"); if (!optional) { return r; } /* optional files are saved as empty files to avoid card * transactions. Parsing the file's data will reveal that they were * missing. */ *len = 0; } else { *len = r; } if (p15card->opts.use_file_cache) { /* save this with our AID */ path.aid = sc_hsm_aid; sc_pkcs15_cache_file(p15card, &path, efbin, *len); } } return SC_SUCCESS; } /* * Decode a card verifiable certificate as defined in TR-03110. */ int sc_pkcs15emu_sc_hsm_decode_cvc(sc_pkcs15_card_t * p15card, const u8 ** buf, size_t *buflen, sc_cvc_t *cvc) { sc_card_t *card = p15card->card; struct sc_asn1_entry asn1_req[C_ASN1_REQ_SIZE]; struct sc_asn1_entry asn1_authreq[C_ASN1_AUTHREQ_SIZE]; struct sc_asn1_entry asn1_cvc[C_ASN1_CVC_SIZE]; struct sc_asn1_entry asn1_cvcert[C_ASN1_CVCERT_SIZE]; struct sc_asn1_entry asn1_cvc_body[C_ASN1_CVC_BODY_SIZE]; struct sc_asn1_entry asn1_cvc_pubkey[C_ASN1_CVC_PUBKEY_SIZE]; unsigned int cla,tag; size_t taglen; size_t lenchr = sizeof(cvc->chr); size_t lencar = sizeof(cvc->car); size_t lenoutercar = sizeof(cvc->outer_car); const u8 *tbuf; int r; memset(cvc, 0, sizeof(*cvc)); sc_copy_asn1_entry(c_asn1_req, asn1_req); sc_copy_asn1_entry(c_asn1_authreq, asn1_authreq); sc_copy_asn1_entry(c_asn1_cvc, asn1_cvc); sc_copy_asn1_entry(c_asn1_cvcert, asn1_cvcert); sc_copy_asn1_entry(c_asn1_cvc_body, asn1_cvc_body); sc_copy_asn1_entry(c_asn1_cvc_pubkey, asn1_cvc_pubkey); sc_format_asn1_entry(asn1_cvc_pubkey , &cvc->pukoid, NULL, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 1, &cvc->primeOrModulus, &cvc->primeOrModuluslen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 2, &cvc->coefficientAorExponent, &cvc->coefficientAorExponentlen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 3, &cvc->coefficientB, &cvc->coefficientBlen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 4, &cvc->basePointG, &cvc->basePointGlen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 5, &cvc->order, &cvc->orderlen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 6, &cvc->publicPoint, &cvc->publicPointlen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 7, &cvc->cofactor, &cvc->cofactorlen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 8, &cvc->modulusSize, NULL, 0); sc_format_asn1_entry(asn1_cvc_body , &cvc->cpi, NULL, 0); sc_format_asn1_entry(asn1_cvc_body + 1, &cvc->car, &lencar, 0); sc_format_asn1_entry(asn1_cvc_body + 2, &asn1_cvc_pubkey, NULL, 0); sc_format_asn1_entry(asn1_cvc_body + 3, &cvc->chr, &lenchr, 0); sc_format_asn1_entry(asn1_cvcert , &asn1_cvc_body, NULL, 0); sc_format_asn1_entry(asn1_cvcert + 1, &cvc->signature, &cvc->signatureLen, 0); sc_format_asn1_entry(asn1_cvc , &asn1_cvcert, NULL, 0); sc_format_asn1_entry(asn1_authreq , &asn1_cvcert, NULL, 0); sc_format_asn1_entry(asn1_authreq + 1, &cvc->outer_car, &lenoutercar, 0); sc_format_asn1_entry(asn1_authreq + 2, &cvc->outerSignature, &cvc->outerSignatureLen, 0); sc_format_asn1_entry(asn1_req , &asn1_authreq, NULL, 0); /* sc_asn1_print_tags(*buf, *buflen); */ tbuf = *buf; r = sc_asn1_read_tag(&tbuf, *buflen, &cla, &tag, &taglen); LOG_TEST_RET(card->ctx, r, "Could not decode card verifiable certificate"); /* Determine if we deal with an authenticated request, plain request or certificate */ if ((cla == (SC_ASN1_TAG_APPLICATION|SC_ASN1_TAG_CONSTRUCTED)) && (tag == 7)) { r = sc_asn1_decode(card->ctx, asn1_req, *buf, *buflen, buf, buflen); } else { r = sc_asn1_decode(card->ctx, asn1_cvc, *buf, *buflen, buf, buflen); } LOG_TEST_RET(card->ctx, r, "Could not decode card verifiable certificate"); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } /* * Encode a card verifiable certificate as defined in TR-03110. */ int sc_pkcs15emu_sc_hsm_encode_cvc(sc_pkcs15_card_t * p15card, sc_cvc_t *cvc, u8 ** buf, size_t *buflen) { sc_card_t *card = p15card->card; struct sc_asn1_entry asn1_cvc[C_ASN1_CVC_SIZE]; struct sc_asn1_entry asn1_cvcert[C_ASN1_CVCERT_SIZE]; struct sc_asn1_entry asn1_cvc_body[C_ASN1_CVC_BODY_SIZE]; struct sc_asn1_entry asn1_cvc_pubkey[C_ASN1_CVC_PUBKEY_SIZE]; size_t lenchr; size_t lencar; int r; sc_copy_asn1_entry(c_asn1_cvc, asn1_cvc); sc_copy_asn1_entry(c_asn1_cvcert, asn1_cvcert); sc_copy_asn1_entry(c_asn1_cvc_body, asn1_cvc_body); sc_copy_asn1_entry(c_asn1_cvc_pubkey, asn1_cvc_pubkey); asn1_cvc_pubkey[1].flags = SC_ASN1_OPTIONAL; asn1_cvcert[1].flags = SC_ASN1_OPTIONAL; sc_format_asn1_entry(asn1_cvc_pubkey , &cvc->pukoid, NULL, 1); if (cvc->primeOrModulus && (cvc->primeOrModuluslen > 0)) { sc_format_asn1_entry(asn1_cvc_pubkey + 1, cvc->primeOrModulus, &cvc->primeOrModuluslen, 1); } sc_format_asn1_entry(asn1_cvc_pubkey + 2, cvc->coefficientAorExponent, &cvc->coefficientAorExponentlen, 1); if (cvc->coefficientB && (cvc->coefficientBlen > 0)) { sc_format_asn1_entry(asn1_cvc_pubkey + 3, cvc->coefficientB, &cvc->coefficientBlen, 1); sc_format_asn1_entry(asn1_cvc_pubkey + 4, cvc->basePointG, &cvc->basePointGlen, 1); sc_format_asn1_entry(asn1_cvc_pubkey + 5, cvc->order, &cvc->orderlen, 1); if (cvc->publicPoint && (cvc->publicPointlen > 0)) { sc_format_asn1_entry(asn1_cvc_pubkey + 6, cvc->publicPoint, &cvc->publicPointlen, 1); } sc_format_asn1_entry(asn1_cvc_pubkey + 7, cvc->cofactor, &cvc->cofactorlen, 1); } if (cvc->modulusSize > 0) { sc_format_asn1_entry(asn1_cvc_pubkey + 8, &cvc->modulusSize, NULL, 1); } sc_format_asn1_entry(asn1_cvc_body , &cvc->cpi, NULL, 1); lencar = strnlen(cvc->car, sizeof cvc->car); sc_format_asn1_entry(asn1_cvc_body + 1, &cvc->car, &lencar, 1); sc_format_asn1_entry(asn1_cvc_body + 2, &asn1_cvc_pubkey, NULL, 1); lenchr = strnlen(cvc->chr, sizeof cvc->chr); sc_format_asn1_entry(asn1_cvc_body + 3, &cvc->chr, &lenchr, 1); sc_format_asn1_entry(asn1_cvcert , &asn1_cvc_body, NULL, 1); if (cvc->signature && (cvc->signatureLen > 0)) { sc_format_asn1_entry(asn1_cvcert + 1, cvc->signature, &cvc->signatureLen, 1); } sc_format_asn1_entry(asn1_cvc , &asn1_cvcert, NULL, 1); r = sc_asn1_encode(card->ctx, asn1_cvc, buf, buflen); LOG_TEST_RET(card->ctx, r, "Could not encode card verifiable certificate"); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } int sc_pkcs15emu_sc_hsm_get_curve(struct ec_curve **curve, u8 *oid, size_t oidlen) { int i; for (i = 0; curves[i].oid.value; i++) { if ((curves[i].oid.len == oidlen) && !memcmp(curves[i].oid.value, oid, oidlen)) { *curve = &curves[i]; return SC_SUCCESS; } } return SC_ERROR_INVALID_DATA; } int sc_pkcs15emu_sc_hsm_get_curve_oid(sc_cvc_t *cvc, const struct sc_lv_data **oid) { int i; for (i = 0; curves[i].oid.value; i++) { if ((curves[i].prime.len == cvc->primeOrModuluslen) && !memcmp(curves[i].prime.value, cvc->primeOrModulus, cvc->primeOrModuluslen)) { *oid = &curves[i].oid; return SC_SUCCESS; } } return SC_ERROR_INVALID_DATA; } static int sc_pkcs15emu_sc_hsm_get_rsa_public_key(struct sc_context *ctx, sc_cvc_t *cvc, struct sc_pkcs15_pubkey *pubkey) { pubkey->algorithm = SC_ALGORITHM_RSA; pubkey->alg_id = (struct sc_algorithm_id *)calloc(1, sizeof(struct sc_algorithm_id)); if (!pubkey->alg_id) return SC_ERROR_OUT_OF_MEMORY; pubkey->alg_id->algorithm = SC_ALGORITHM_RSA; pubkey->u.rsa.modulus.len = cvc->primeOrModuluslen; pubkey->u.rsa.modulus.data = malloc(pubkey->u.rsa.modulus.len); pubkey->u.rsa.exponent.len = cvc->coefficientAorExponentlen; pubkey->u.rsa.exponent.data = malloc(pubkey->u.rsa.exponent.len); if (!pubkey->u.rsa.modulus.data || !pubkey->u.rsa.exponent.data) return SC_ERROR_OUT_OF_MEMORY; memcpy(pubkey->u.rsa.exponent.data, cvc->coefficientAorExponent, pubkey->u.rsa.exponent.len); memcpy(pubkey->u.rsa.modulus.data, cvc->primeOrModulus, pubkey->u.rsa.modulus.len); return SC_SUCCESS; } static int sc_pkcs15emu_sc_hsm_get_ec_public_key(struct sc_context *ctx, sc_cvc_t *cvc, struct sc_pkcs15_pubkey *pubkey) { struct sc_ec_parameters *ecp; const struct sc_lv_data *oid; int r; pubkey->algorithm = SC_ALGORITHM_EC; r = sc_pkcs15emu_sc_hsm_get_curve_oid(cvc, &oid); if (r != SC_SUCCESS) return r; ecp = calloc(1, sizeof(struct sc_ec_parameters)); if (!ecp) return SC_ERROR_OUT_OF_MEMORY; ecp->der.len = oid->len + 2; ecp->der.value = calloc(ecp->der.len, 1); if (!ecp->der.value) { free(ecp); return SC_ERROR_OUT_OF_MEMORY; } *(ecp->der.value + 0) = 0x06; *(ecp->der.value + 1) = (u8)oid->len; memcpy(ecp->der.value + 2, oid->value, oid->len); ecp->type = 1; // Named curve pubkey->alg_id = (struct sc_algorithm_id *)calloc(1, sizeof(struct sc_algorithm_id)); if (!pubkey->alg_id) { free(ecp->der.value); free(ecp); return SC_ERROR_OUT_OF_MEMORY; } pubkey->alg_id->algorithm = SC_ALGORITHM_EC; pubkey->alg_id->params = ecp; pubkey->u.ec.ecpointQ.value = malloc(cvc->publicPointlen); if (!pubkey->u.ec.ecpointQ.value) return SC_ERROR_OUT_OF_MEMORY; memcpy(pubkey->u.ec.ecpointQ.value, cvc->publicPoint, cvc->publicPointlen); pubkey->u.ec.ecpointQ.len = cvc->publicPointlen; pubkey->u.ec.params.der.value = malloc(ecp->der.len); if (!pubkey->u.ec.params.der.value) return SC_ERROR_OUT_OF_MEMORY; memcpy(pubkey->u.ec.params.der.value, ecp->der.value, ecp->der.len); pubkey->u.ec.params.der.len = ecp->der.len; /* FIXME: check return value? */ sc_pkcs15_fix_ec_parameters(ctx, &pubkey->u.ec.params); return SC_SUCCESS; } int sc_pkcs15emu_sc_hsm_get_public_key(struct sc_context *ctx, sc_cvc_t *cvc, struct sc_pkcs15_pubkey *pubkey) { if (cvc->publicPoint && cvc->publicPointlen) { return sc_pkcs15emu_sc_hsm_get_ec_public_key(ctx, cvc, pubkey); } else { return sc_pkcs15emu_sc_hsm_get_rsa_public_key(ctx, cvc, pubkey); } } void sc_pkcs15emu_sc_hsm_free_cvc(sc_cvc_t *cvc) { if (cvc->signature) { free(cvc->signature); cvc->signature = NULL; } if (cvc->primeOrModulus) { free(cvc->primeOrModulus); cvc->primeOrModulus = NULL; } if (cvc->coefficientAorExponent) { free(cvc->coefficientAorExponent); cvc->coefficientAorExponent = NULL; } if (cvc->coefficientB) { free(cvc->coefficientB); cvc->coefficientB = NULL; } if (cvc->basePointG) { free(cvc->basePointG); cvc->basePointG = NULL; } if (cvc->order) { free(cvc->order); cvc->order = NULL; } if (cvc->publicPoint) { free(cvc->publicPoint); cvc->publicPoint = NULL; } if (cvc->cofactor) { free(cvc->cofactor); cvc->cofactor = NULL; } } static int sc_pkcs15emu_sc_hsm_add_pubkey(sc_pkcs15_card_t *p15card, u8 *efbin, size_t len, sc_pkcs15_prkey_info_t *key_info, char *label) { struct sc_context *ctx = p15card->card->ctx; sc_card_t *card = p15card->card; sc_pkcs15_pubkey_info_t pubkey_info; sc_pkcs15_object_t pubkey_obj; struct sc_pkcs15_pubkey pubkey; sc_cvc_t cvc; u8 *cvcpo; int r; cvcpo = efbin; memset(&cvc, 0, sizeof(cvc)); r = sc_pkcs15emu_sc_hsm_decode_cvc(p15card, (const u8 **)&cvcpo, &len, &cvc); LOG_TEST_RET(ctx, r, "Could decode certificate signing request"); memset(&pubkey, 0, sizeof(pubkey)); r = sc_pkcs15emu_sc_hsm_get_public_key(ctx, &cvc, &pubkey); LOG_TEST_RET(card->ctx, r, "Could not extract public key"); memset(&pubkey_info, 0, sizeof(pubkey_info)); memset(&pubkey_obj, 0, sizeof(pubkey_obj)); r = sc_pkcs15_encode_pubkey(ctx, &pubkey, &pubkey_obj.content.value, &pubkey_obj.content.len); LOG_TEST_RET(ctx, r, "Could not encode public key"); r = sc_pkcs15_encode_pubkey(ctx, &pubkey, &pubkey_info.direct.raw.value, &pubkey_info.direct.raw.len); LOG_TEST_RET(ctx, r, "Could not encode public key"); r = sc_pkcs15_encode_pubkey_as_spki(ctx, &pubkey, &pubkey_info.direct.spki.value, &pubkey_info.direct.spki.len); LOG_TEST_RET(ctx, r, "Could not encode public key"); pubkey_info.id = key_info->id; strlcpy(pubkey_obj.label, label, sizeof(pubkey_obj.label)); if (pubkey.algorithm == SC_ALGORITHM_RSA) { pubkey_info.modulus_length = pubkey.u.rsa.modulus.len << 3; pubkey_info.usage = SC_PKCS15_PRKEY_USAGE_ENCRYPT|SC_PKCS15_PRKEY_USAGE_VERIFY|SC_PKCS15_PRKEY_USAGE_WRAP; r = sc_pkcs15emu_add_rsa_pubkey(p15card, &pubkey_obj, &pubkey_info); } else { /* TODO fix if support of non multiple of 8 curves are added */ pubkey_info.field_length = cvc.primeOrModuluslen << 3; pubkey_info.usage = SC_PKCS15_PRKEY_USAGE_VERIFY; r = sc_pkcs15emu_add_ec_pubkey(p15card, &pubkey_obj, &pubkey_info); } LOG_TEST_RET(ctx, r, "Could not add public key"); sc_pkcs15emu_sc_hsm_free_cvc(&cvc); sc_pkcs15_erase_pubkey(&pubkey); return SC_SUCCESS; } /* * Add a key and the key description in PKCS#15 format to the framework */ static int sc_pkcs15emu_sc_hsm_add_prkd(sc_pkcs15_card_t * p15card, u8 keyid) { sc_card_t *card = p15card->card; sc_pkcs15_cert_info_t cert_info; sc_pkcs15_object_t cert_obj; struct sc_pkcs15_object prkd; sc_pkcs15_prkey_info_t *key_info; u8 fid[2]; /* enough to hold a complete certificate */ u8 efbin[4096]; u8 *ptr; size_t len; int r; fid[0] = PRKD_PREFIX; fid[1] = keyid; /* Try to select a related EF containing the PKCS#15 description of the key */ len = sizeof efbin; r = read_file(p15card, fid, efbin, &len, 1); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.PRKD"); ptr = efbin; memset(&prkd, 0, sizeof(prkd)); r = sc_pkcs15_decode_prkdf_entry(p15card, &prkd, (const u8 **)&ptr, &len); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.PRKD"); /* All keys require user PIN authentication */ prkd.auth_id.len = 1; prkd.auth_id.value[0] = 1; /* * Set private key flag as all keys are private anyway */ prkd.flags |= SC_PKCS15_CO_FLAG_PRIVATE; key_info = (sc_pkcs15_prkey_info_t *)prkd.data; key_info->key_reference = keyid; key_info->path.aid.len = 0; if (prkd.type == SC_PKCS15_TYPE_PRKEY_RSA) { r = sc_pkcs15emu_add_rsa_prkey(p15card, &prkd, key_info); } else { r = sc_pkcs15emu_add_ec_prkey(p15card, &prkd, key_info); } LOG_TEST_RET(card->ctx, r, "Could not add private key to framework"); /* Check if we also have a certificate for the private key */ fid[0] = EE_CERTIFICATE_PREFIX; len = sizeof efbin; r = read_file(p15card, fid, efbin, &len, 0); LOG_TEST_RET(card->ctx, r, "Could not read EF"); if (efbin[0] == 0x67) { /* Decode CSR and create public key object */ sc_pkcs15emu_sc_hsm_add_pubkey(p15card, efbin, len, key_info, prkd.label); free(key_info); return SC_SUCCESS; /* Ignore any errors */ } if (efbin[0] != 0x30) { free(key_info); return SC_SUCCESS; } memset(&cert_info, 0, sizeof(cert_info)); memset(&cert_obj, 0, sizeof(cert_obj)); cert_info.id = key_info->id; sc_path_set(&cert_info.path, SC_PATH_TYPE_FILE_ID, fid, 2, 0, 0); cert_info.path.count = -1; if (p15card->opts.use_file_cache) { /* look this up with our AID, which should already be cached from the * call to `read_file`. This may have the side effect that OpenSC's * caching layer re-selects our applet *if the cached file cannot be * found/used* and we may loose the authentication status. We assume * that caching works perfectly without this side effect. */ cert_info.path.aid = sc_hsm_aid; } strlcpy(cert_obj.label, prkd.label, sizeof(cert_obj.label)); r = sc_pkcs15emu_add_x509_cert(p15card, &cert_obj, &cert_info); free(key_info); LOG_TEST_RET(card->ctx, r, "Could not add certificate"); return SC_SUCCESS; } /* * Add a data object and description in PKCS#15 format to the framework */ static int sc_pkcs15emu_sc_hsm_add_dcod(sc_pkcs15_card_t * p15card, u8 id) { sc_card_t *card = p15card->card; sc_pkcs15_data_info_t *data_info; sc_pkcs15_object_t data_obj; u8 fid[2]; u8 efbin[512]; const u8 *ptr; size_t len; int r; fid[0] = DCOD_PREFIX; fid[1] = id; /* Try to select a related EF containing the PKCS#15 description of the data */ len = sizeof efbin; r = read_file(p15card, fid, efbin, &len, 1); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.DCOD"); ptr = efbin; memset(&data_obj, 0, sizeof(data_obj)); r = sc_pkcs15_decode_dodf_entry(p15card, &data_obj, &ptr, &len); LOG_TEST_RET(card->ctx, r, "Could not decode optional EF.DCOD"); data_info = (sc_pkcs15_data_info_t *)data_obj.data; r = sc_pkcs15emu_add_data_object(p15card, &data_obj, data_info); LOG_TEST_RET(card->ctx, r, "Could not add data object to framework"); return SC_SUCCESS; } /* * Add a unrelated certificate object and description in PKCS#15 format to the framework */ static int sc_pkcs15emu_sc_hsm_add_cd(sc_pkcs15_card_t * p15card, u8 id) { sc_card_t *card = p15card->card; sc_pkcs15_cert_info_t *cert_info; sc_pkcs15_object_t obj; u8 fid[2]; u8 efbin[512]; const u8 *ptr; size_t len; int r; fid[0] = CD_PREFIX; fid[1] = id; /* Try to select a related EF containing the PKCS#15 description of the data */ len = sizeof efbin; r = read_file(p15card, fid, efbin, &len, 1); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.DCOD"); ptr = efbin; memset(&obj, 0, sizeof(obj)); r = sc_pkcs15_decode_cdf_entry(p15card, &obj, &ptr, &len); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.CDOD"); cert_info = (sc_pkcs15_cert_info_t *)obj.data; r = sc_pkcs15emu_add_x509_cert(p15card, &obj, cert_info); LOG_TEST_RET(card->ctx, r, "Could not add data object to framework"); return SC_SUCCESS; } static int sc_pkcs15emu_sc_hsm_read_tokeninfo (sc_pkcs15_card_t * p15card) { sc_card_t *card = p15card->card; int r; u8 efbin[512]; size_t len; LOG_FUNC_CALLED(card->ctx); /* Read token info */ len = sizeof efbin; r = read_file(p15card, (u8 *) "\x2F\x03", efbin, &len, 1); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.TokenInfo"); r = sc_pkcs15_parse_tokeninfo(card->ctx, p15card->tokeninfo, efbin, len); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.TokenInfo"); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } /* * Initialize PKCS#15 emulation with user PIN, private keys, certificate and data objects * */ static int sc_pkcs15emu_sc_hsm_init (sc_pkcs15_card_t * p15card) { sc_card_t *card = p15card->card; sc_hsm_private_data_t *priv = (sc_hsm_private_data_t *) card->drv_data; sc_file_t *file = NULL; sc_path_t path; u8 filelist[MAX_EXT_APDU_LENGTH]; int filelistlength; int r, i; sc_cvc_t devcert; struct sc_app_info *appinfo; struct sc_pkcs15_auth_info pin_info; struct sc_pkcs15_object pin_obj; struct sc_pin_cmd_data pindata; u8 efbin[1024]; u8 *ptr; size_t len; LOG_FUNC_CALLED(card->ctx); appinfo = calloc(1, sizeof(struct sc_app_info)); if (appinfo == NULL) { LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); } appinfo->aid = sc_hsm_aid; appinfo->ddo.aid = sc_hsm_aid; p15card->app = appinfo; sc_path_set(&path, SC_PATH_TYPE_DF_NAME, sc_hsm_aid.value, sc_hsm_aid.len, 0, 0); r = sc_select_file(card, &path, &file); LOG_TEST_RET(card->ctx, r, "Could not select SmartCard-HSM application"); p15card->card->version.hw_major = 24; /* JCOP 2.4.1r3 */ p15card->card->version.hw_minor = 13; if (file && file->prop_attr && file->prop_attr_len >= 2) { p15card->card->version.fw_major = file->prop_attr[file->prop_attr_len - 2]; p15card->card->version.fw_minor = file->prop_attr[file->prop_attr_len - 1]; } sc_file_free(file); /* Read device certificate to determine serial number */ if (priv->EF_C_DevAut && priv->EF_C_DevAut_len) { ptr = priv->EF_C_DevAut; len = priv->EF_C_DevAut_len; } else { len = sizeof efbin; r = read_file(p15card, (u8 *) "\x2F\x02", efbin, &len, 1); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.C_DevAut"); /* save EF_C_DevAut for further use */ ptr = realloc(priv->EF_C_DevAut, len); if (ptr) { memcpy(ptr, efbin, len); priv->EF_C_DevAut = ptr; priv->EF_C_DevAut_len = len; } ptr = efbin; } memset(&devcert, 0 ,sizeof(devcert)); r = sc_pkcs15emu_sc_hsm_decode_cvc(p15card, (const u8 **)&ptr, &len, &devcert); LOG_TEST_RET(card->ctx, r, "Could not decode EF.C_DevAut"); sc_pkcs15emu_sc_hsm_read_tokeninfo(p15card); if (p15card->tokeninfo->label == NULL) { if (p15card->card->type == SC_CARD_TYPE_SC_HSM_GOID || p15card->card->type == SC_CARD_TYPE_SC_HSM_SOC) { p15card->tokeninfo->label = strdup("GoID"); } else { p15card->tokeninfo->label = strdup("SmartCard-HSM"); } if (p15card->tokeninfo->label == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); } if ((p15card->tokeninfo->manufacturer_id != NULL) && !strcmp("(unknown)", p15card->tokeninfo->manufacturer_id)) { free(p15card->tokeninfo->manufacturer_id); p15card->tokeninfo->manufacturer_id = NULL; } if (p15card->tokeninfo->manufacturer_id == NULL) { if (p15card->card->type == SC_CARD_TYPE_SC_HSM_GOID || p15card->card->type == SC_CARD_TYPE_SC_HSM_SOC) { p15card->tokeninfo->manufacturer_id = strdup("Bundesdruckerei GmbH"); } else { p15card->tokeninfo->manufacturer_id = strdup("www.CardContact.de"); } if (p15card->tokeninfo->manufacturer_id == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); } appinfo->label = strdup(p15card->tokeninfo->label); if (appinfo->label == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); len = strnlen(devcert.chr, sizeof devcert.chr); /* Strip last 5 digit sequence number from CHR */ assert(len >= 8); len -= 5; p15card->tokeninfo->serial_number = calloc(len + 1, 1); if (p15card->tokeninfo->serial_number == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); memcpy(p15card->tokeninfo->serial_number, devcert.chr, len); *(p15card->tokeninfo->serial_number + len) = 0; sc_hsm_set_serialnr(card, p15card->tokeninfo->serial_number); sc_pkcs15emu_sc_hsm_free_cvc(&devcert); memset(&pin_info, 0, sizeof(pin_info)); memset(&pin_obj, 0, sizeof(pin_obj)); pin_info.auth_id.len = 1; pin_info.auth_id.value[0] = 1; pin_info.path.aid = sc_hsm_aid; pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN; pin_info.attrs.pin.reference = 0x81; pin_info.attrs.pin.flags = SC_PKCS15_PIN_FLAG_LOCAL|SC_PKCS15_PIN_FLAG_INITIALIZED|SC_PKCS15_PIN_FLAG_EXCHANGE_REF_DATA; pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_ASCII_NUMERIC; pin_info.attrs.pin.min_length = 6; pin_info.attrs.pin.stored_length = 0; pin_info.attrs.pin.max_length = 15; pin_info.attrs.pin.pad_char = '\0'; pin_info.tries_left = 3; pin_info.max_tries = 3; pin_obj.auth_id.len = 1; pin_obj.auth_id.value[0] = 2; strlcpy(pin_obj.label, "UserPIN", sizeof(pin_obj.label)); pin_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE|SC_PKCS15_CO_FLAG_MODIFIABLE; r = sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info); if (r < 0) LOG_FUNC_RETURN(card->ctx, r); memset(&pin_info, 0, sizeof(pin_info)); memset(&pin_obj, 0, sizeof(pin_obj)); pin_info.auth_id.len = 1; pin_info.auth_id.value[0] = 2; pin_info.path.aid = sc_hsm_aid; pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN; pin_info.attrs.pin.reference = 0x88; pin_info.attrs.pin.flags = SC_PKCS15_PIN_FLAG_LOCAL|SC_PKCS15_PIN_FLAG_INITIALIZED|SC_PKCS15_PIN_FLAG_UNBLOCK_DISABLED|SC_PKCS15_PIN_FLAG_SO_PIN; pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_BCD; pin_info.attrs.pin.min_length = 16; pin_info.attrs.pin.stored_length = 0; pin_info.attrs.pin.max_length = 16; pin_info.attrs.pin.pad_char = '\0'; pin_info.tries_left = 15; pin_info.max_tries = 15; strlcpy(pin_obj.label, "SOPIN", sizeof(pin_obj.label)); pin_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE; r = sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info); if (r < 0) LOG_FUNC_RETURN(card->ctx, r); if (card->type == SC_CARD_TYPE_SC_HSM_SOC || card->type == SC_CARD_TYPE_SC_HSM_GOID) { /* SC-HSM of this type always has a PIN-Pad */ r = SC_SUCCESS; } else { memset(&pindata, 0, sizeof(pindata)); pindata.cmd = SC_PIN_CMD_GET_INFO; pindata.pin_type = SC_AC_CHV; pindata.pin_reference = 0x85; r = sc_pin_cmd(card, &pindata, NULL); } if (r == SC_ERROR_DATA_OBJECT_NOT_FOUND) { memset(&pindata, 0, sizeof(pindata)); pindata.cmd = SC_PIN_CMD_GET_INFO; pindata.pin_type = SC_AC_CHV; pindata.pin_reference = 0x86; r = sc_pin_cmd(card, &pindata, NULL); } if ((r != SC_ERROR_DATA_OBJECT_NOT_FOUND) && (r != SC_ERROR_INCORRECT_PARAMETERS)) card->caps |= SC_CARD_CAP_PROTECTED_AUTHENTICATION_PATH; filelistlength = sc_list_files(card, filelist, sizeof(filelist)); LOG_TEST_RET(card->ctx, filelistlength, "Could not enumerate file and key identifier"); for (i = 0; i < filelistlength; i += 2) { switch(filelist[i]) { case KEY_PREFIX: r = sc_pkcs15emu_sc_hsm_add_prkd(p15card, filelist[i + 1]); break; case DCOD_PREFIX: r = sc_pkcs15emu_sc_hsm_add_dcod(p15card, filelist[i + 1]); break; case CD_PREFIX: r = sc_pkcs15emu_sc_hsm_add_cd(p15card, filelist[i + 1]); break; } if (r != SC_SUCCESS) { sc_log(card->ctx, "Error %d adding elements to framework", r); } } LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } int sc_pkcs15emu_sc_hsm_init_ex(sc_pkcs15_card_t *p15card, struct sc_aid *aid, sc_pkcs15emu_opt_t *opts) { if (opts && (opts->flags & SC_PKCS15EMU_FLAGS_NO_CHECK)) { return sc_pkcs15emu_sc_hsm_init(p15card); } else { if (p15card->card->type != SC_CARD_TYPE_SC_HSM && p15card->card->type != SC_CARD_TYPE_SC_HSM_SOC && p15card->card->type != SC_CARD_TYPE_SC_HSM_GOID) { return SC_ERROR_WRONG_CARD; } return sc_pkcs15emu_sc_hsm_init(p15card); } }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_344_6
crossvul-cpp_data_bad_346_0
/* * card-cac.c: Support for CAC from NIST SP800-73 * card-default.c: Support for cards with no driver * * Copyright (C) 2001, 2002 Juha Yrjölä <juha.yrjola@iki.fi> * Copyright (C) 2005,2006,2007,2008,2009,2010 Douglas E. Engert <deengert@anl.gov> * Copyright (C) 2006, Identity Alliance, Thomas Harning <thomas.harning@identityalliance.com> * Copyright (C) 2007, EMC, Russell Larner <rlarner@rsa.com> * Copyright (C) 2016 - 2018, Red Hat, Inc. * * CAC driver author: Robert Relyea <rrelyea@redhat.com> * Further work: Jakub Jelen <jjelen@redhat.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #include <ctype.h> #include <fcntl.h> #include <limits.h> #include <stdlib.h> #include <string.h> #ifdef _WIN32 #include <io.h> #else #include <unistd.h> #endif #ifdef ENABLE_OPENSSL /* openssl only needed for card administration */ #include <openssl/evp.h> #include <openssl/bio.h> #include <openssl/pem.h> #include <openssl/rand.h> #include <openssl/rsa.h> #endif /* ENABLE_OPENSSL */ #include "internal.h" #include "simpletlv.h" #include "cardctl.h" #ifdef ENABLE_ZLIB #include "compression.h" #endif #include "iso7816.h" #define CAC_MAX_SIZE 4096 /* arbitrary, just needs to be 'large enough' */ /* * CAC hardware and APDU constants */ #define CAC_MAX_CHUNK_SIZE 240 #define CAC_INS_SIGN_DECRYPT 0x42 /* A crypto operation */ #define CAC_INS_READ_FILE 0x52 /* read a TL or V file */ #define CAC_INS_GET_ACR 0x4c #define CAC_INS_GET_PROPERTIES 0x56 #define CAC_P1_STEP 0x80 #define CAC_P1_FINAL 0x00 #define CAC_FILE_TAG 1 #define CAC_FILE_VALUE 2 /* TAGS in a TL file */ #define CAC_TAG_CERTIFICATE 0x70 #define CAC_TAG_CERTINFO 0x71 #define CAC_TAG_MSCUID 0x72 #define CAC_TAG_CUID 0xF0 #define CAC_TAG_CC_VERSION_NUMBER 0xF1 #define CAC_TAG_GRAMMAR_VERION_NUMBER 0xF2 #define CAC_TAG_CARDURL 0xF3 #define CAC_TAG_PKCS15 0xF4 #define CAC_TAG_ACCESS_CONTROL 0xF6 #define CAC_TAG_DATA_MODEL 0xF5 #define CAC_TAG_CARD_APDU 0xF7 #define CAC_TAG_REDIRECTION 0xFA #define CAC_TAG_CAPABILITY_TUPLES 0xFB #define CAC_TAG_STATUS_TUPLES 0xFC #define CAC_TAG_NEXT_CCC 0xFD #define CAC_TAG_ERROR_CODES 0xFE #define CAC_TAG_APPLET_FAMILY 0x01 #define CAC_TAG_NUMBER_APPLETS 0x94 #define CAC_TAG_APPLET_ENTRY 0x93 #define CAC_TAG_APPLET_AID 0x92 #define CAC_TAG_APPLET_INFORMATION 0x01 #define CAC_TAG_NUMBER_OF_OBJECTS 0x40 #define CAC_TAG_TV_BUFFER 0x50 #define CAC_TAG_PKI_OBJECT 0x51 #define CAC_TAG_OBJECT_ID 0x41 #define CAC_TAG_BUFFER_PROPERTIES 0x42 #define CAC_TAG_PKI_PROPERTIES 0x43 #define CAC_APP_TYPE_GENERAL 0x01 #define CAC_APP_TYPE_SKI 0x02 #define CAC_APP_TYPE_PKI 0x04 #define CAC_ACR_ACR 0x00 #define CAC_ACR_APPLET_OBJECT 0x10 #define CAC_ACR_AMP 0x20 #define CAC_ACR_SERVICE 0x21 /* hardware data structures (returned in the CCC) */ /* part of the card_url */ typedef struct cac_access_profile { u8 GCACR_listID; u8 GCACR_readTagListACRID; u8 GCACR_updatevalueACRID; u8 GCACR_readvalueACRID; u8 GCACR_createACRID; u8 GCACR_deleteACRID; u8 CryptoACR_listID; u8 CryptoACR_getChallengeACRID; u8 CryptoACR_internalAuthenicateACRID; u8 CryptoACR_pkiComputeACRID; u8 CryptoACR_readTagListACRID; u8 CryptoACR_updatevalueACRID; u8 CryptoACR_readvalueACRID; u8 CryptoACR_createACRID; u8 CryptoACR_deleteACRID; } cac_access_profile_t; /* part of the card url */ typedef struct cac_access_key_info { u8 keyFileID[2]; u8 keynumber; } cac_access_key_info_t; typedef struct cac_card_url { u8 rid[5]; u8 cardApplicationType; u8 objectID[2]; u8 applicationID[2]; cac_access_profile_t accessProfile; u8 pinID; /* not used for VM cards */ cac_access_key_info_t accessKeyInfo; /* not used for VM cards */ u8 keyCryptoAlgorithm; /* not used for VM cards */ } cac_card_url_t; typedef struct cac_cuid { u8 gsc_rid[5]; u8 manufacturer_id; u8 card_type; u8 card_id; } cac_cuid_t; /* data structures to store meta data about CAC objects */ typedef struct cac_object { const char *name; int fd; sc_path_t path; } cac_object_t; #define CAC_MAX_OBJECTS 16 typedef struct { /* OID has two bytes */ unsigned char oid[2]; /* Format is NOT SimpleTLV? */ unsigned char simpletlv; /* Is certificate object and private key is initialized */ unsigned char privatekey; } cac_properties_object_t; typedef struct { unsigned int num_objects; cac_properties_object_t objects[CAC_MAX_OBJECTS]; } cac_properties_t; /* * Flags for Current Selected Object Type * CAC files are TLV files, with TL and V separated. For generic * containers we reintegrate the TL anv V portions into a single * file to read. Certs are also TLV files, but pkcs15 wants the * actual certificate. At select time we know the patch which tells * us what time of files we want to read. We remember that type * so that read_binary can do the appropriate processing. */ #define CAC_OBJECT_TYPE_CERT 1 #define CAC_OBJECT_TYPE_TLV_FILE 4 #define CAC_OBJECT_TYPE_GENERIC 5 /* * CAC private data per card state */ typedef struct cac_private_data { int object_type; /* select set this so we know how to read the file */ int cert_next; /* index number for the next certificate found in the list */ u8 *cache_buf; /* cached version of the currently selected file */ size_t cache_buf_len; /* length of the cached selected file */ int cached; /* is the cached selected file valid */ cac_cuid_t cuid; /* card unique ID from the CCC */ u8 *cac_id; /* card serial number */ size_t cac_id_len; /* card serial number len */ list_t pki_list; /* list of pki containers */ cac_object_t *pki_current; /* current pki object _ctl function */ list_t general_list; /* list of general containers */ cac_object_t *general_current; /* current object for _ctl function */ sc_path_t *aca_path; /* ACA path to be selected before pin verification */ } cac_private_data_t; #define CAC_DATA(card) ((cac_private_data_t*)card->drv_data) int cac_list_compare_path(const void *a, const void *b) { if (a == NULL || b == NULL) return 1; return memcmp( &((cac_object_t *) a)->path, &((cac_object_t *) b)->path, sizeof(sc_path_t)); } /* For SimCList autocopy, we need to know the size of the data elements */ size_t cac_list_meter(const void *el) { return sizeof(cac_object_t); } static cac_private_data_t *cac_new_private_data(void) { cac_private_data_t *priv; priv = calloc(1, sizeof(cac_private_data_t)); if (!priv) return NULL; list_init(&priv->pki_list); list_attributes_comparator(&priv->pki_list, cac_list_compare_path); list_attributes_copy(&priv->pki_list, cac_list_meter, 1); list_init(&priv->general_list); list_attributes_comparator(&priv->general_list, cac_list_compare_path); list_attributes_copy(&priv->general_list, cac_list_meter, 1); /* set other fields as appropriate */ return priv; } static void cac_free_private_data(cac_private_data_t *priv) { free(priv->cac_id); free(priv->cache_buf); free(priv->aca_path); list_destroy(&priv->pki_list); list_destroy(&priv->general_list); free(priv); return; } static int cac_add_object_to_list(list_t *list, const cac_object_t *object) { if (list_append(list, object) < 0) return SC_ERROR_UNKNOWN; return SC_SUCCESS; } /* * Set up the normal CAC paths */ #define CAC_TO_AID(x) x, sizeof(x)-1 #define CAC_2_RID "\xA0\x00\x00\x01\x16" #define CAC_1_RID "\xA0\x00\x00\x00\x79" static const sc_path_t cac_ACA_Path = { "", 0, 0,0,SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x10\x00") } }; static const sc_path_t cac_CCC_Path = { "", 0, 0,0,SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_2_RID "\xDB\x00") } }; #define MAX_CAC_SLOTS 16 /* Maximum number of slots is 16 now */ /* default certificate labels for the CAC card */ static const char *cac_labels[MAX_CAC_SLOTS] = { "CAC ID Certificate", "CAC Email Signature Certificate", "CAC Email Encryption Certificate", "CAC Cert 4", "CAC Cert 5", "CAC Cert 6", "CAC Cert 7", "CAC Cert 8", "CAC Cert 9", "CAC Cert 10", "CAC Cert 11", "CAC Cert 12", "CAC Cert 13", "CAC Cert 14", "CAC Cert 15", "CAC Cert 16" }; /* template for a CAC pki object */ static const cac_object_t cac_cac_pki_obj = { "CAC Certificate", 0x0, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x01\x00") } } }; /* template for emulated cuid */ static const cac_cuid_t cac_cac_cuid = { { 0xa0, 0x00, 0x00, 0x00, 0x79 }, 2, 2, 0 }; /* * CAC general objects defined in 4.3.1.2 of CAC Applet Developer Guide Version 1.0. * doubles as a source for CAC-2 labels. */ static const cac_object_t cac_objects[] = { { "Person Instance", 0x200, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\x00") }}}, { "Personnel", 0x201, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\x01") }}}, { "Benefits", 0x202, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\x02") }}}, { "Other Benefits", 0x203, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\x03") }}}, { "PKI Credential", 0x2FD, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\xFD") }}}, { "PKI Certificate", 0x2FE, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\xFE") }}}, }; static const int cac_object_count = sizeof(cac_objects)/sizeof(cac_objects[0]); /* * use the object id to find our object info on the object in our CAC-1 list */ static const cac_object_t *cac_find_obj_by_id(unsigned short object_id) { int i; for (i = 0; i < cac_object_count; i++) { if (cac_objects[i].fd == object_id) { return &cac_objects[i]; } } return NULL; } /* * Lookup the path in the pki list to see if it is a cert path */ static int cac_is_cert(cac_private_data_t * priv, const sc_path_t *in_path) { cac_object_t test_obj; test_obj.path = *in_path; test_obj.path.index = 0; test_obj.path.count = 0; return (list_contains(&priv->pki_list, &test_obj) != 0); } /* * Send a command and receive data. * * A caller may provide a buffer, and length to read. If not provided, * an internal 4096 byte buffer is used, and a copy is returned to the * caller. that need to be freed by the caller. * * modelled after a similar function in card-piv.c */ static int cac_apdu_io(sc_card_t *card, int ins, int p1, int p2, const u8 * sendbuf, size_t sendbuflen, u8 ** recvbuf, size_t * recvbuflen) { int r; sc_apdu_t apdu; u8 rbufinitbuf[CAC_MAX_SIZE]; u8 *rbuf; size_t rbuflen; unsigned int apdu_case = SC_APDU_CASE_1; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "%02x %02x %02x %"SC_FORMAT_LEN_SIZE_T"u : %"SC_FORMAT_LEN_SIZE_T"u %"SC_FORMAT_LEN_SIZE_T"u\n", ins, p1, p2, sendbuflen, card->max_send_size, card->max_recv_size); rbuf = rbufinitbuf; rbuflen = sizeof(rbufinitbuf); /* if caller provided a buffer and length */ if (recvbuf && *recvbuf && recvbuflen && *recvbuflen) { rbuf = *recvbuf; rbuflen = *recvbuflen; } if (recvbuf) { if (sendbuf) apdu_case = SC_APDU_CASE_4_SHORT; else apdu_case = SC_APDU_CASE_2_SHORT; } else if (sendbuf) apdu_case = SC_APDU_CASE_3_SHORT; sc_format_apdu(card, &apdu, apdu_case, ins, p1, p2); apdu.lc = sendbuflen; apdu.datalen = sendbuflen; apdu.data = sendbuf; if (recvbuf) { apdu.resp = rbuf; apdu.le = (rbuflen > 255) ? 255 : rbuflen; apdu.resplen = rbuflen; } else { apdu.resp = rbuf; apdu.le = 0; apdu.resplen = 0; } sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "calling sc_transmit_apdu flags=%lx le=%"SC_FORMAT_LEN_SIZE_T"u, resplen=%"SC_FORMAT_LEN_SIZE_T"u, resp=%p", apdu.flags, apdu.le, apdu.resplen, apdu.resp); /* with new adpu.c and chaining, this actually reads the whole object */ r = sc_transmit_apdu(card, &apdu); sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "result r=%d apdu.resplen=%"SC_FORMAT_LEN_SIZE_T"u sw1=%02x sw2=%02x", r, apdu.resplen, apdu.sw1, apdu.sw2); if (r < 0) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,"Transmit failed"); goto err; } r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r < 0) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Card returned error "); goto err; } if (recvbuflen) { if (recvbuf && *recvbuf == NULL) { *recvbuf = malloc(apdu.resplen); if (*recvbuf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto err; } memcpy(*recvbuf, rbuf, apdu.resplen); } *recvbuflen = apdu.resplen; r = *recvbuflen; } err: SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } /* * Get ACR of currently ACA applet identified by the acr_type * 5.3.3.5 Get ACR APDU */ static int cac_get_acr(sc_card_t *card, int acr_type, u8 **out_buf, size_t *out_len) { u8 *out = NULL; /* XXX assuming it will not be longer than 255 B */ size_t len = 256; int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* for simplicity we support only ACR without arguments now */ if (acr_type != 0x00 && acr_type != 0x10 && acr_type != 0x20 && acr_type != 0x21) { return SC_ERROR_INVALID_ARGUMENTS; } r = cac_apdu_io(card, CAC_INS_GET_ACR, acr_type, 0, NULL, 0, &out, &len); if (len == 0) { r = SC_ERROR_FILE_NOT_FOUND; } if (r < 0) goto fail; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "got %"SC_FORMAT_LEN_SIZE_T"u bytes out=%p", len, out); *out_len = len; *out_buf = out; return SC_SUCCESS; fail: if (out) free(out); *out_buf = NULL; *out_len = 0; return r; } /* * Read a CAC TLV file. Parameters specify if the TLV file is TL (Tag/Length) file or a V (value) file */ #define HIGH_BYTE_OF_SHORT(x) (((x)>> 8) & 0xff) #define LOW_BYTE_OF_SHORT(x) ((x) & 0xff) static int cac_read_file(sc_card_t *card, int file_type, u8 **out_buf, size_t *out_len) { u8 params[2]; u8 count[2]; u8 *out = NULL; u8 *out_ptr; size_t offset = 0; size_t size = 0; size_t left = 0; size_t len; int r; params[0] = file_type; params[1] = 2; /* get the size */ len = sizeof(count); out_ptr = count; r = cac_apdu_io(card, CAC_INS_READ_FILE, 0, 0, &params[0], sizeof(params), &out_ptr, &len); if (len == 0) { r = SC_ERROR_FILE_NOT_FOUND; } if (r < 0) goto fail; left = size = lebytes2ushort(count); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "got %"SC_FORMAT_LEN_SIZE_T"u bytes out_ptr=%p count&=%p count[0]=0x%02x count[1]=0x%02x, len=0x%04"SC_FORMAT_LEN_SIZE_T"x (%"SC_FORMAT_LEN_SIZE_T"u)", len, out_ptr, &count, count[0], count[1], size, size); out = out_ptr = malloc(size); if (out == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto fail; } for (offset += 2; left > 0; offset += len, left -= len, out_ptr += len) { len = MIN(left, CAC_MAX_CHUNK_SIZE); params[1] = len; r = cac_apdu_io(card, CAC_INS_READ_FILE, HIGH_BYTE_OF_SHORT(offset), LOW_BYTE_OF_SHORT(offset), &params[0], sizeof(params), &out_ptr, &len); /* if there is no data, assume there is no file */ if (len == 0) { r = SC_ERROR_FILE_NOT_FOUND; } if (r < 0) { goto fail; } } *out_len = size; *out_buf = out; return SC_SUCCESS; fail: if (out) free(out); *out_len = 0; return r; } /* * Callers of this may be expecting a certificate, * select file will have saved the object type for us * as well as set that we want the cert from the object. */ static int cac_read_binary(sc_card_t *card, unsigned int idx, unsigned char *buf, size_t count, unsigned long flags) { cac_private_data_t * priv = CAC_DATA(card); int r = 0; u8 *tl = NULL, *val = NULL; u8 *tl_ptr, *val_ptr, *tlv_ptr, *tl_start; u8 *cert_ptr; size_t tl_len, val_len, tlv_len; size_t len, tl_head_len, cert_len; u8 cert_type, tag; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* if we didn't return it all last time, return the remainder */ if (priv->cached) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "returning cached value idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u", idx, count); if (idx > priv->cache_buf_len) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_END_REACHED); } len = MIN(count, priv->cache_buf_len-idx); memcpy(buf, &priv->cache_buf[idx], len); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, len); } sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "clearing cache idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u", idx, count); if (priv->cache_buf) { free(priv->cache_buf); priv->cache_buf = NULL; priv->cache_buf_len = 0; } if (priv->object_type <= 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INTERNAL); r = cac_read_file(card, CAC_FILE_TAG, &tl, &tl_len); if (r < 0) { goto done; } r = cac_read_file(card, CAC_FILE_VALUE, &val, &val_len); if (r < 0) goto done; switch (priv->object_type) { case CAC_OBJECT_TYPE_TLV_FILE: tlv_len = tl_len + val_len; priv->cache_buf = malloc(tlv_len); if (priv->cache_buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto done; } priv->cache_buf_len = tlv_len; for (tl_ptr = tl, val_ptr=val, tlv_ptr = priv->cache_buf; tl_len >= 2 && tlv_len > 0; val_len -= len, tlv_len -= len, val_ptr += len, tlv_ptr += len) { /* get the tag and the length */ tl_start = tl_ptr; if (sc_simpletlv_read_tag(&tl_ptr, tl_len, &tag, &len) != SC_SUCCESS) break; tl_head_len = (tl_ptr - tl_start); sc_simpletlv_put_tag(tag, len, tlv_ptr, tlv_len, &tlv_ptr); tlv_len -= tl_head_len; tl_len -= tl_head_len; /* don't crash on bad data */ if (val_len < len) { len = val_len; } /* if we run out of return space, truncate */ if (tlv_len < len) { len = tlv_len; } memcpy(tlv_ptr, val_ptr, len); } break; case CAC_OBJECT_TYPE_CERT: /* read file */ sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, " obj= cert_file, val_len=%"SC_FORMAT_LEN_SIZE_T"u (0x%04"SC_FORMAT_LEN_SIZE_T"x)", val_len, val_len); cert_len = 0; cert_ptr = NULL; cert_type = 0; for (tl_ptr = tl, val_ptr = val; tl_len >= 2; val_len -= len, val_ptr += len, tl_len -= tl_head_len) { tl_start = tl_ptr; if (sc_simpletlv_read_tag(&tl_ptr, tl_len, &tag, &len) != SC_SUCCESS) break; tl_head_len = tl_ptr - tl_start; /* incomplete value */ if (val_len < len) break; if (tag == CAC_TAG_CERTIFICATE) { cert_len = len; cert_ptr = val_ptr; } if (tag == CAC_TAG_CERTINFO) { if ((len >= 1) && (val_len >=1)) { cert_type = *val_ptr; } } if (tag == CAC_TAG_MSCUID) { sc_log_hex(card->ctx, "MSCUID", val_ptr, len); } if ((val_len < len) || (tl_len < tl_head_len)) { break; } } /* if the info byte is 1, then the cert is compressed, decompress it */ if ((cert_type & 0x3) == 1) { #ifdef ENABLE_ZLIB r = sc_decompress_alloc(&priv->cache_buf, &priv->cache_buf_len, cert_ptr, cert_len, COMPRESSION_AUTO); #else sc_log(card->ctx, "CAC compression not supported, no zlib"); r = SC_ERROR_NOT_SUPPORTED; #endif if (r) goto done; } else if (cert_len > 0) { priv->cache_buf = malloc(cert_len); if (priv->cache_buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto done; } priv->cache_buf_len = cert_len; memcpy(priv->cache_buf, cert_ptr, cert_len); } else { sc_log(card->ctx, "Can't read zero-length certificate"); goto done; } break; case CAC_OBJECT_TYPE_GENERIC: /* TODO * We have some two buffers in unknown encoding that we * need to present in PKCS#15 layer. */ default: /* Unknown object type */ sc_log(card->ctx, "Unknown object type: %x", priv->object_type); r = SC_ERROR_INTERNAL; goto done; } /* OK we've read the data, now copy the required portion out to the callers buffer */ priv->cached = 1; len = MIN(count, priv->cache_buf_len-idx); memcpy(buf, &priv->cache_buf[idx], len); r = len; done: if (tl) free(tl); if (val) free(val); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } /* CAC driver is read only */ static int cac_write_binary(sc_card_t *card, unsigned int idx, const u8 *buf, size_t count, unsigned long flags) { SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_NOT_SUPPORTED); } /* initialize getting a list and return the number of elements in the list */ static int cac_get_init_and_get_count(list_t *list, cac_object_t **entry, int *countp) { *countp = list_size(list); list_iterator_start(list); *entry = list_iterator_next(list); return SC_SUCCESS; } /* finalize the list iterator */ static int cac_final_iterator(list_t *list) { list_iterator_stop(list); return SC_SUCCESS; } /* fill in the obj_info for the current object on the list and advance to the next object */ static int cac_fill_object_info(list_t *list, cac_object_t **entry, sc_pkcs15_data_info_t *obj_info) { memset(obj_info, 0, sizeof(sc_pkcs15_data_info_t)); if (*entry == NULL) { return SC_ERROR_FILE_END_REACHED; } obj_info->path = (*entry)->path; obj_info->path.count = CAC_MAX_SIZE-1; /* read something from the object */ obj_info->id.value[0] = ((*entry)->fd >> 8) & 0xff; obj_info->id.value[1] = (*entry)->fd & 0xff; obj_info->id.len = 2; strncpy(obj_info->app_label, (*entry)->name, SC_PKCS15_MAX_LABEL_SIZE-1); *entry = list_iterator_next(list); return SC_SUCCESS; } static int cac_get_serial_nr_from_CUID(sc_card_t* card, sc_serial_number_t* serial) { cac_private_data_t * priv = CAC_DATA(card); SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_NORMAL); if (card->serialnr.len) { *serial = card->serialnr; SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } if (priv->cac_id_len) { serial->len = MIN(priv->cac_id_len, SC_MAX_SERIALNR); memcpy(serial->value, priv->cac_id, priv->cac_id_len); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_NOT_FOUND); } static int cac_get_ACA_path(sc_card_t *card, sc_path_t *path) { cac_private_data_t * priv = CAC_DATA(card); SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_NORMAL); if (priv->aca_path) { *path = *priv->aca_path; } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } static int cac_card_ctl(sc_card_t *card, unsigned long cmd, void *ptr) { cac_private_data_t * priv = CAC_DATA(card); LOG_FUNC_CALLED(card->ctx); sc_log(card->ctx, "cmd=%ld ptr=%p", cmd, ptr); if (priv == NULL) { LOG_FUNC_RETURN(card->ctx, SC_ERROR_INTERNAL); } switch(cmd) { case SC_CARDCTL_CAC_GET_ACA_PATH: return cac_get_ACA_path(card, (sc_path_t *) ptr); case SC_CARDCTL_GET_SERIALNR: return cac_get_serial_nr_from_CUID(card, (sc_serial_number_t *) ptr); case SC_CARDCTL_CAC_INIT_GET_GENERIC_OBJECTS: return cac_get_init_and_get_count(&priv->general_list, &priv->general_current, (int *)ptr); case SC_CARDCTL_CAC_INIT_GET_CERT_OBJECTS: return cac_get_init_and_get_count(&priv->pki_list, &priv->pki_current, (int *)ptr); case SC_CARDCTL_CAC_GET_NEXT_GENERIC_OBJECT: return cac_fill_object_info(&priv->general_list, &priv->general_current, (sc_pkcs15_data_info_t *)ptr); case SC_CARDCTL_CAC_GET_NEXT_CERT_OBJECT: return cac_fill_object_info(&priv->pki_list, &priv->pki_current, (sc_pkcs15_data_info_t *)ptr); case SC_CARDCTL_CAC_FINAL_GET_GENERIC_OBJECTS: return cac_final_iterator(&priv->general_list); case SC_CARDCTL_CAC_FINAL_GET_CERT_OBJECTS: return cac_final_iterator(&priv->pki_list); } LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); } static int cac_get_challenge(sc_card_t *card, u8 *rnd, size_t len) { /* CAC requires 8 byte response */ u8 rbuf[8]; u8 *rbufp = &rbuf[0]; size_t out_len = sizeof rbuf; int r; LOG_FUNC_CALLED(card->ctx); r = cac_apdu_io(card, 0x84, 0x00, 0x00, NULL, 0, &rbufp, &out_len); LOG_TEST_RET(card->ctx, r, "Could not get challenge"); if (len < out_len) { out_len = len; } memcpy(rnd, rbuf, out_len); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, (int) out_len); } static int cac_set_security_env(sc_card_t *card, const sc_security_env_t *env, int se_num) { int r = SC_SUCCESS; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "flags=%08lx op=%d alg=%d algf=%08x algr=%08x kr0=%02x, krfl=%"SC_FORMAT_LEN_SIZE_T"u\n", env->flags, env->operation, env->algorithm, env->algorithm_flags, env->algorithm_ref, env->key_ref[0], env->key_ref_len); if (env->algorithm != SC_ALGORITHM_RSA) { r = SC_ERROR_NO_CARD_SUPPORT; } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r); } static int cac_restore_security_env(sc_card_t *card, int se_num) { SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } static int cac_rsa_op(sc_card_t *card, const u8 * data, size_t datalen, u8 * out, size_t outlen) { int r; u8 *outp, *rbuf; size_t rbuflen, outplen; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "datalen=%"SC_FORMAT_LEN_SIZE_T"u outlen=%"SC_FORMAT_LEN_SIZE_T"u\n", datalen, outlen); outp = out; outplen = outlen; /* Not strictly necessary. This code requires the caller to have selected the correct PKI container * and authenticated to that container with the verifyPin command... All of this under the reader lock. * The PKCS #15 higher level driver code does all this correctly (it's the same for all cards, just * different sets of APDU's that need to be called), so this call is really a little bit of paranoia */ r = sc_lock(card); if (r != SC_SUCCESS) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); rbuf = NULL; rbuflen = 0; for (; datalen > CAC_MAX_CHUNK_SIZE; data += CAC_MAX_CHUNK_SIZE, datalen -= CAC_MAX_CHUNK_SIZE) { r = cac_apdu_io(card, CAC_INS_SIGN_DECRYPT, CAC_P1_STEP, 0, data, CAC_MAX_CHUNK_SIZE, &rbuf, &rbuflen); if (r < 0) { break; } if (rbuflen != 0) { int n = MIN(rbuflen, outplen); memcpy(outp,rbuf, n); outp += n; outplen -= n; } free(rbuf); rbuf = NULL; rbuflen = 0; } if (r < 0) { goto err; } rbuf = NULL; rbuflen = 0; r = cac_apdu_io(card, CAC_INS_SIGN_DECRYPT, CAC_P1_FINAL, 0, data, datalen, &rbuf, &rbuflen); if (r < 0) { goto err; } if (rbuflen != 0) { int n = MIN(rbuflen, outplen); memcpy(outp,rbuf, n); /*outp += n; unused */ outplen -= n; } free(rbuf); rbuf = NULL; r = outlen-outplen; err: sc_unlock(card); if (r < 0) { sc_mem_clear(out, outlen); } if (rbuf) { free(rbuf); } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } static int cac_compute_signature(sc_card_t *card, const u8 * data, size_t datalen, u8 * out, size_t outlen) { SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, cac_rsa_op(card, data, datalen, out, outlen)); } static int cac_decipher(sc_card_t *card, const u8 * data, size_t datalen, u8 * out, size_t outlen) { SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, cac_rsa_op(card, data, datalen, out, outlen)); } static int cac_parse_properties_object(sc_card_t *card, u8 type, u8 *data, size_t data_len, cac_properties_object_t *object) { size_t len; u8 *val, *val_end, tag; int parsed = 0; if (data_len < 11) return -1; /* Initilize: non-PKI applet */ object->privatekey = 0; val = data; val_end = data + data_len; for (; val < val_end; val += len) { /* get the tag and the length */ if (sc_simpletlv_read_tag(&val, val_end - val, &tag, &len) != SC_SUCCESS) break; switch (tag) { case CAC_TAG_OBJECT_ID: if (len != 2) { sc_log(card->ctx, "TAG: Object ID: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Object ID = 0x%02x 0x%02x", val[0], val[1]); memcpy(&object->oid, val, 2); parsed++; break; case CAC_TAG_BUFFER_PROPERTIES: if (len != 5) { sc_log(card->ctx, "TAG: Buffer Properties: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } /* First byte is "Type of Tag Supported" */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Buffer Properties: Type of Tag Supported = 0x%02x", val[0]); object->simpletlv = val[0]; parsed++; break; case CAC_TAG_PKI_PROPERTIES: /* 4th byte is "Private Key Initialized" */ if (len != 4) { sc_log(card->ctx, "TAG: PKI Properties: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } if (type != CAC_TAG_PKI_OBJECT) { sc_log(card->ctx, "TAG: PKI Properties outside of PKI Object"); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: PKI Properties: Private Key Initialized = 0x%02x", val[2]); object->privatekey = val[2]; parsed++; break; default: /* ignore tags we don't understand */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Unknown (0x%02x)",tag ); break; } } if (parsed < 2) return SC_ERROR_INVALID_DATA; return SC_SUCCESS; } static int cac_get_properties(sc_card_t *card, cac_properties_t *prop) { u8 *rbuf = NULL; size_t rbuflen = 0, len; u8 *val, *val_end, tag; size_t i = 0; int r; prop->num_objects = 0; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); r = cac_apdu_io(card, CAC_INS_GET_PROPERTIES, 0x01, 0x00, NULL, 0, &rbuf, &rbuflen); if (r < 0) return r; val = rbuf; val_end = val + rbuflen; for (; val < val_end; val += len) { /* get the tag and the length */ if (sc_simpletlv_read_tag(&val, val_end - val, &tag, &len) != SC_SUCCESS) break; switch (tag) { case CAC_TAG_APPLET_INFORMATION: if (len != 5) { sc_log(card->ctx, "TAG: Applet Information: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Applet Information: Family: 0x%0x", val[0]); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, " Applet Version: 0x%02x 0x%02x 0x%02x 0x%02x", val[1], val[2], val[3], val[4]); break; case CAC_TAG_NUMBER_OF_OBJECTS: if (len != 1) { sc_log(card->ctx, "TAG: Num objects: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Num objects = %hhd", *val); /* make sure we do not overrun buffer */ prop->num_objects = MIN(val[0], CAC_MAX_OBJECTS); break; case CAC_TAG_TV_BUFFER: if (len != 17) { sc_log(card->ctx, "TAG: TV Object: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: TV Object nr. %"SC_FORMAT_LEN_SIZE_T"u", i); if (i >= CAC_MAX_OBJECTS) { free(rbuf); return SC_SUCCESS; } if (cac_parse_properties_object(card, tag, val, len, &prop->objects[i]) == SC_SUCCESS) i++; break; case CAC_TAG_PKI_OBJECT: if (len != 17) { sc_log(card->ctx, "TAG: PKI Object: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: PKI Object nr. %"SC_FORMAT_LEN_SIZE_T"u", i); if (i >= CAC_MAX_OBJECTS) { free(rbuf); return SC_SUCCESS; } if (cac_parse_properties_object(card, tag, val, len, &prop->objects[i]) == SC_SUCCESS) i++; break; default: /* ignore tags we don't understand */ sc_log(card->ctx, "TAG: Unknown (0x%02x), len=%" SC_FORMAT_LEN_SIZE_T"u", tag, len); break; } } free(rbuf); /* sanity */ if (i != prop->num_objects) sc_log(card->ctx, "The announced number of objects (%u) " "did not match reality (%"SC_FORMAT_LEN_SIZE_T"u)", prop->num_objects, i); prop->num_objects = i; return SC_SUCCESS; } /* * CAC cards use SC_PATH_SELECT_OBJECT_ID rather than SC_PATH_SELECT_FILE_ID. In order to use more * of the PKCS #15 structure, we call the selection SC_PATH_SELECT_FILE_ID, but we set p1 to 2 instead * of 0. Also cac1 does not do any FCI, but it doesn't understand not selecting it. It returns invalid INS * if it doesn't like anything about the select, so we always 'request' FCI for CAC1 * * The rest is just copied from iso7816_select_file */ static int cac_select_file_by_type(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out, int type) { struct sc_context *ctx; struct sc_apdu apdu; unsigned char buf[SC_MAX_APDU_BUFFER_SIZE]; unsigned char pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf; int r, pathlen, pathtype; struct sc_file *file = NULL; cac_private_data_t * priv = CAC_DATA(card); assert(card != NULL && in_path != NULL); ctx = card->ctx; SC_FUNC_CALLED(ctx, SC_LOG_DEBUG_VERBOSE); memcpy(path, in_path->value, in_path->len); pathlen = in_path->len; pathtype = in_path->type; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "path->aid=%x %x %x %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u, path->value = %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u path->type=%d (%x)", in_path->aid.value[0], in_path->aid.value[1], in_path->aid.value[2], in_path->aid.value[3], in_path->aid.value[4], in_path->aid.value[5], in_path->aid.value[6], in_path->aid.len, in_path->value[0], in_path->value[1], in_path->value[2], in_path->value[3], in_path->len, in_path->type, in_path->type); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "file_out=%p index=%d count=%d\n", file_out, in_path->index, in_path->count); /* Sigh, sc_key_select expects paths to keys to have specific formats. There is no override. * we have to add some bytes to the path to make it happy. A better fix would be to give sc_key_file * a flag that says 'no, really this path is fine'. We only need to do this for private keys */ if ((pathlen > 2) && (pathlen <= 4) && memcmp(path, "\x3F\x00", 2) == 0) { if (pathlen > 2) { path += 2; pathlen -= 2; } } /* CAC has multiple different type of objects that aren't PKCS #15. When we read * them we need convert them to something PKCS #15 would understand. Find the object * and object type here: */ if (priv) { /* don't record anything if we haven't been initialized yet */ priv->object_type = CAC_OBJECT_TYPE_GENERIC; if (cac_is_cert(priv, in_path)) { priv->object_type = CAC_OBJECT_TYPE_CERT; } /* forget any old cached values */ if (priv->cache_buf) { free(priv->cache_buf); priv->cache_buf = NULL; } priv->cache_buf_len = 0; priv->cached = 0; } if (in_path->aid.len) { if (!pathlen) { memcpy(path, in_path->aid.value, in_path->aid.len); pathlen = in_path->aid.len; pathtype = SC_PATH_TYPE_DF_NAME; } else { /* First, select the application */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"select application" ); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xA4, 4, 0); apdu.data = in_path->aid.value; apdu.datalen = in_path->aid.len; apdu.lc = in_path->aid.len; r = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r) LOG_FUNC_RETURN(ctx, r); } } sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0, 0); switch (pathtype) { /* ideally we would had SC_PATH_TYPE_OBJECT_ID and add code to the iso7816 select. * Unfortunately we'd also need to update the caching code as well. For now just * use FILE_ID and change p1 here */ case SC_PATH_TYPE_FILE_ID: apdu.p1 = 2; if (pathlen != 2) return SC_ERROR_INVALID_ARGUMENTS; break; case SC_PATH_TYPE_DF_NAME: apdu.p1 = 4; break; default: LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); } apdu.lc = pathlen; apdu.data = path; apdu.datalen = pathlen; apdu.resp = buf; apdu.resplen = sizeof(buf); apdu.le = sc_get_max_recv_size(card) < 256 ? sc_get_max_recv_size(card) : 256; if (file_out != NULL) { apdu.p2 = 0; /* first record, return FCI */ } else { apdu.p2 = 0x0C; } r = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, r, "APDU transmit failed"); if (file_out == NULL) { /* For some cards 'SELECT' can be only with request to return FCI/FCP. */ r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (apdu.sw1 == 0x6A && apdu.sw2 == 0x86) { apdu.p2 = 0x00; apdu.resplen = sizeof(buf); if (sc_transmit_apdu(card, &apdu) == SC_SUCCESS) r = sc_check_sw(card, apdu.sw1, apdu.sw2); } if (apdu.sw1 == 0x61) LOG_FUNC_RETURN(ctx, SC_SUCCESS); LOG_FUNC_RETURN(ctx, r); } r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r) LOG_FUNC_RETURN(ctx, r); /* This needs to come after the applet selection */ if (priv && in_path->len >= 2) { /* get applet properties to know if we can treat the * buffer as SimpleLTV and if we have PKI applet. * * Do this only if we select applets for reading * (not during driver initialization) */ cac_properties_t prop; size_t i = -1; r = cac_get_properties(card, &prop); if (r == SC_SUCCESS) { for (i = 0; i < prop.num_objects; i++) { sc_log(card->ctx, "Searching for our OID: 0x%02x 0x%02x = 0x%02x 0x%02x", prop.objects[i].oid[0], prop.objects[i].oid[1], in_path->value[0], in_path->value[1]); if (memcmp(prop.objects[i].oid, in_path->value, 2) == 0) break; } } if (i < prop.num_objects) { if (prop.objects[i].privatekey) priv->object_type = CAC_OBJECT_TYPE_CERT; else if (prop.objects[i].simpletlv == 0) priv->object_type = CAC_OBJECT_TYPE_TLV_FILE; } } /* CAC cards never return FCI, fake one */ file = sc_file_new(); if (file == NULL) LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY); file->path = *in_path; file->size = CAC_MAX_SIZE; /* we don't know how big, just give a large size until we can read the file */ *file_out = file; SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } static int cac_select_file(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out) { return cac_select_file_by_type(card, in_path, file_out, card->type); } static int cac_finish(sc_card_t *card) { cac_private_data_t * priv = CAC_DATA(card); SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); if (priv) { cac_free_private_data(priv); } return SC_SUCCESS; } /* select the Card Capabilities Container on CAC-2 */ static int cac_select_CCC(sc_card_t *card) { return cac_select_file_by_type(card, &cac_CCC_Path, NULL, SC_CARD_TYPE_CAC_II); } /* Select ACA in non-standard location */ static int cac_select_ACA(sc_card_t *card) { return cac_select_file_by_type(card, &cac_ACA_Path, NULL, SC_CARD_TYPE_CAC_II); } static int cac_path_from_cardurl(sc_card_t *card, sc_path_t *path, cac_card_url_t *val, int len) { if (len < 10) { return SC_ERROR_INVALID_DATA; } sc_mem_clear(path, sizeof(sc_path_t)); memcpy(path->aid.value, &val->rid, sizeof(val->rid)); memcpy(&path->aid.value[5], &val->applicationID, sizeof(val->applicationID)); path->aid.len = sizeof(val->rid) + sizeof(val->applicationID); memcpy(path->value, &val->objectID, sizeof(val->objectID)); path->len = sizeof(val->objectID); path->type = SC_PATH_TYPE_FILE_ID; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "path->aid=%x %x %x %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u, path->value = %x %x len=%"SC_FORMAT_LEN_SIZE_T"u path->type=%d (%x)", path->aid.value[0], path->aid.value[1], path->aid.value[2], path->aid.value[3], path->aid.value[4], path->aid.value[5], path->aid.value[6], path->aid.len, path->value[0], path->value[1], path->len, path->type, path->type); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "rid=%x %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u appid= %x %x len=%"SC_FORMAT_LEN_SIZE_T"u objid= %x %x len=%"SC_FORMAT_LEN_SIZE_T"u", val->rid[0], val->rid[1], val->rid[2], val->rid[3], val->rid[4], sizeof(val->rid), val->applicationID[0], val->applicationID[1], sizeof(val->applicationID), val->objectID[0], val->objectID[1], sizeof(val->objectID)); return SC_SUCCESS; } static int cac_parse_aid(sc_card_t *card, cac_private_data_t *priv, u8 *aid, int aid_len) { cac_object_t new_object; cac_properties_t prop; size_t i; int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* Search for PKI applets (7 B). Ignore generic objects for now */ if (aid_len != 7 || (memcmp(aid, CAC_1_RID "\x01", 6) != 0 && memcmp(aid, CAC_1_RID "\x00", 6) != 0)) return SC_SUCCESS; sc_mem_clear(&new_object.path, sizeof(sc_path_t)); memcpy(new_object.path.aid.value, aid, aid_len); new_object.path.aid.len = aid_len; /* Call without OID set will just select the AID without subseqent * OID selection, which we need to figure out just now */ cac_select_file_by_type(card, &new_object.path, NULL, SC_CARD_TYPE_CAC_II); r = cac_get_properties(card, &prop); if (r < 0) return SC_ERROR_INTERNAL; for (i = 0; i < prop.num_objects; i++) { /* don't fail just because we have more certs than we can support */ if (priv->cert_next >= MAX_CAC_SLOTS) return SC_SUCCESS; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "ACA: pki_object found, cert_next=%d (%s), privkey=%d", priv->cert_next, cac_labels[priv->cert_next], prop.objects[i].privatekey); /* If the private key is not initialized, we can safely * ignore this object here, but increase the pointer to follow * the certificate labels */ if (!prop.objects[i].privatekey) { priv->cert_next++; continue; } /* OID here has always 2B */ memcpy(new_object.path.value, &prop.objects[i].oid, 2); new_object.path.len = 2; new_object.path.type = SC_PATH_TYPE_FILE_ID; new_object.name = cac_labels[priv->cert_next]; new_object.fd = priv->cert_next+1; cac_add_object_to_list(&priv->pki_list, &new_object); priv->cert_next++; } return SC_SUCCESS; } static int cac_parse_cardurl(sc_card_t *card, cac_private_data_t *priv, cac_card_url_t *val, int len) { cac_object_t new_object; const cac_object_t *obj; unsigned short object_id; int r; r = cac_path_from_cardurl(card, &new_object.path, val, len); if (r != SC_SUCCESS) { return r; } switch (val->cardApplicationType) { case CAC_APP_TYPE_PKI: /* we don't want to overflow the cac_label array. This test could * go way if we create a label function that will create a unique label * from a cert index. */ if (priv->cert_next >= MAX_CAC_SLOTS) break; /* don't fail just because we have more certs than we can support */ new_object.name = cac_labels[priv->cert_next]; new_object.fd = priv->cert_next+1; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: pki_object found, cert_next=%d (%s),", priv->cert_next, new_object.name); cac_add_object_to_list(&priv->pki_list, &new_object); priv->cert_next++; break; case CAC_APP_TYPE_GENERAL: object_id = bebytes2ushort(val->objectID); obj = cac_find_obj_by_id(object_id); if (obj == NULL) break; /* don't fail just because we don't recognize the object */ new_object.name = obj->name; new_object.fd = 0; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: gen_object found, objectID=%x (%s),", object_id, new_object.name); cac_add_object_to_list(&priv->general_list, &new_object); break; case CAC_APP_TYPE_SKI: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: ski_object found"); break; default: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: unknown object_object found (type=0x%02x)", val->cardApplicationType); /* don't fail just because there is an unknown object in the CCC */ break; } return SC_SUCCESS; } static int cac_parse_cuid(sc_card_t *card, cac_private_data_t *priv, cac_cuid_t *val, size_t len) { size_t card_id_len; if (len < sizeof(cac_cuid_t)) { return SC_ERROR_INVALID_DATA; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "gsc_rid=%s", sc_dump_hex(val->gsc_rid, sizeof(val->gsc_rid))); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "manufacture id=%x", val->manufacturer_id); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "cac_type=%d", val->card_type); card_id_len = len - (&val->card_id - (u8 *)val); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "card_id=%s (%"SC_FORMAT_LEN_SIZE_T"u)", sc_dump_hex(&val->card_id, card_id_len), card_id_len); priv->cuid = *val; priv->cac_id = malloc(card_id_len); if (priv->cac_id == NULL) { return SC_ERROR_OUT_OF_MEMORY; } memcpy(priv->cac_id, &val->card_id, card_id_len); priv->cac_id_len = card_id_len; return SC_SUCCESS; } static int cac_process_CCC(sc_card_t *card, cac_private_data_t *priv); static int cac_parse_CCC(sc_card_t *card, cac_private_data_t *priv, u8 *tl, size_t tl_len, u8 *val, size_t val_len) { size_t len = 0; u8 *tl_end = tl + tl_len; u8 *val_end = val + val_len; sc_path_t new_path; int r; for (; (tl < tl_end) && (val< val_end); val += len) { /* get the tag and the length */ u8 tag; if (sc_simpletlv_read_tag(&tl, tl_end - tl, &tag, &len) != SC_SUCCESS) break; switch (tag) { case CAC_TAG_CUID: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:CUID"); r = cac_parse_cuid(card, priv, (cac_cuid_t *)val, len); if (r < 0) return r; break; case CAC_TAG_CC_VERSION_NUMBER: if (len != 1) { sc_log(card->ctx, "TAG: CC Version: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } /* ignore the version numbers for now */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: CC Version = 0x%02x", *val); break; case CAC_TAG_GRAMMAR_VERION_NUMBER: if (len != 1) { sc_log(card->ctx, "TAG: Grammar Version: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } /* ignore the version numbers for now */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Grammar Version = 0x%02x", *val); break; case CAC_TAG_CARDURL: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:CARDURL"); r = cac_parse_cardurl(card, priv, (cac_card_url_t *)val, len); if (r < 0) return r; break; /* * The following are really for file systems cards. This code only cares about CAC VM cards */ case CAC_TAG_PKCS15: if (len != 1) { sc_log(card->ctx, "TAG: PKCS15: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } /* TODO should verify that this is '0'. If it's not * zero, we should drop out of here and let the PKCS 15 * code handle this card */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG: PKCS15 = 0x%02x", *val); break; case CAC_TAG_DATA_MODEL: case CAC_TAG_CARD_APDU: case CAC_TAG_CAPABILITY_TUPLES: case CAC_TAG_STATUS_TUPLES: case CAC_TAG_REDIRECTION: case CAC_TAG_ERROR_CODES: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:FSSpecific(0x%02x)", tag); break; case CAC_TAG_ACCESS_CONTROL: /* TODO handle access control later */ sc_log_hex(card->ctx, "TAG:ACCESS Control", val, len); break; case CAC_TAG_NEXT_CCC: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:NEXT CCC"); r = cac_path_from_cardurl(card, &new_path, (cac_card_url_t *)val, len); if (r < 0) return r; r = cac_select_file_by_type(card, &new_path, NULL, SC_CARD_TYPE_CAC_II); if (r < 0) return r; r = cac_process_CCC(card, priv); if (r < 0) return r; break; default: /* ignore tags we don't understand */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:Unknown (0x%02x)",tag ); break; } } return SC_SUCCESS; } static int cac_process_CCC(sc_card_t *card, cac_private_data_t *priv) { u8 *tl = NULL, *val = NULL; size_t tl_len, val_len; int r; r = cac_read_file(card, CAC_FILE_TAG, &tl, &tl_len); if (r < 0) goto done; r = cac_read_file(card, CAC_FILE_VALUE, &val, &val_len); if (r < 0) goto done; r = cac_parse_CCC(card, priv, tl, tl_len, val, val_len); done: if (tl) free(tl); if (val) free(val); return r; } /* Service Applet Table (Table 5-21) should list all the applets on the * card, which is a good start if we don't have CCC */ static int cac_parse_ACA_service(sc_card_t *card, cac_private_data_t *priv, u8 *val, size_t val_len) { size_t len = 0; u8 *val_end = val + val_len; int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); for (; val < val_end; val += len) { /* get the tag and the length */ u8 tag; if (sc_simpletlv_read_tag(&val, val_end - val, &tag, &len) != SC_SUCCESS) break; switch (tag) { case CAC_TAG_APPLET_FAMILY: if (len != 5) { sc_log(card->ctx, "TAG: Applet Information: " "bad length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Applet Information: Family: 0x%02x", val[0]); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, " Applet Version: 0x%02x 0x%02x 0x%02x 0x%02x", val[1], val[2], val[3], val[4]); break; case CAC_TAG_NUMBER_APPLETS: if (len != 1) { sc_log(card->ctx, "TAG: Num applets: " "bad length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Num applets = %hhd", *val); break; case CAC_TAG_APPLET_ENTRY: /* Make sure we match the outer length */ if (len < 3 || val[2] != len - 3) { sc_log(card->ctx, "TAG: Applet Entry: " "bad length (%"SC_FORMAT_LEN_SIZE_T "u) or length of internal buffer", len); break; } sc_debug_hex(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Applet Entry: AID", &val[3], val[2]); /* This is SimpleTLV prefixed with applet ID (1B) */ r = cac_parse_aid(card, priv, &val[3], val[2]); if (r < 0) return r; break; default: /* ignore tags we don't understand */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Unknown (0x%02x)", tag); break; } } return SC_SUCCESS; } /* select a CAC pki applet by index */ static int cac_select_pki_applet(sc_card_t *card, int index) { sc_path_t applet_path = cac_cac_pki_obj.path; applet_path.aid.value[applet_path.aid.len-1] = index; return cac_select_file_by_type(card, &applet_path, NULL, SC_CARD_TYPE_CAC_II); } /* * Find the first existing CAC applet. If none found, then this isn't a CAC */ static int cac_find_first_pki_applet(sc_card_t *card, int *index_out) { int r, i; for (i = 0; i < MAX_CAC_SLOTS; i++) { r = cac_select_pki_applet(card, i); if (r == SC_SUCCESS) { /* Try to read first two bytes of the buffer to * make sure it is not just malfunctioning card */ u8 params[2] = {CAC_FILE_TAG, 2}; u8 data[2], *out_ptr = data; size_t len = 2; r = cac_apdu_io(card, CAC_INS_READ_FILE, 0, 0, &params[0], sizeof(params), &out_ptr, &len); if (r != 2) continue; *index_out = i; return SC_SUCCESS; } } return SC_ERROR_OBJECT_NOT_FOUND; } /* * This emulates CCC for Alt tokens, that do not come with CCC nor ACA applets */ static int cac_populate_cac_alt(sc_card_t *card, int index, cac_private_data_t *priv) { int r, i; cac_object_t pki_obj = cac_cac_pki_obj; u8 buf[100]; u8 *val; size_t val_len; /* populate PKI objects */ for (i = index; i < MAX_CAC_SLOTS; i++) { r = cac_select_pki_applet(card, i); if (r == SC_SUCCESS) { pki_obj.name = cac_labels[i]; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "CAC: pki_object found, cert_next=%d (%s),", i, pki_obj.name); pki_obj.path.aid.value[pki_obj.path.aid.len-1] = i; pki_obj.fd = i+1; /* don't use id of zero */ cac_add_object_to_list(&priv->pki_list, &pki_obj); } } /* populate non-PKI objects */ for (i=0; i < cac_object_count; i++) { r = cac_select_file_by_type(card, &cac_objects[i].path, NULL, SC_CARD_TYPE_CAC_II); if (r == SC_SUCCESS) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "CAC: obj_object found, cert_next=%d (%s),", i, cac_objects[i].name); cac_add_object_to_list(&priv->general_list, &cac_objects[i]); } } /* * create a cuid to simulate the cac 2 cuid. */ priv->cuid = cac_cac_cuid; /* create a serial number by hashing the first 100 bytes of the * first certificate on the card */ r = cac_select_pki_applet(card, index); if (r < 0) { return r; /* shouldn't happen unless the card has been removed or is malfunctioning */ } val = buf; val_len = cac_read_binary(card, 0, val, sizeof(buf), 0); if (val_len > 0) { priv->cac_id = malloc(20); if (priv->cac_id == NULL) { return SC_ERROR_OUT_OF_MEMORY; } #ifdef ENABLE_OPENSSL SHA1(val, val_len, priv->cac_id); priv->cac_id_len = 20; sc_debug_hex(card->ctx, SC_LOG_DEBUG_VERBOSE, "cuid", priv->cac_id, priv->cac_id_len); #else sc_log(card->ctx, "OpenSSL Required"); return SC_ERROR_NOT_SUPPORTED; #endif /* ENABLE_OPENSSL */ } return SC_SUCCESS; } static int cac_process_ACA(sc_card_t *card, cac_private_data_t *priv) { int r; u8 *val = NULL; size_t val_len; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* Assuming ACA is already selected */ r = cac_get_acr(card, CAC_ACR_SERVICE, &val, &val_len); if (r < 0) goto done; r = cac_parse_ACA_service(card, priv, val, val_len); if (r == SC_SUCCESS) { priv->aca_path = malloc(sizeof(sc_path_t)); if (!priv->aca_path) { r = SC_ERROR_OUT_OF_MEMORY; goto done; } memcpy(priv->aca_path, &cac_ACA_Path, sizeof(sc_path_t)); } done: if (val) free(val); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } /* * Look for a CAC card. If it exists, initialize our data structures */ static int cac_find_and_initialize(sc_card_t *card, int initialize) { int r, index; cac_private_data_t *priv = NULL; /* already initialized? */ if (card->drv_data) { return SC_SUCCESS; } /* is this a CAC-2 specified in NIST Interagency Report 6887 - * "Government Smart Card Interoperability Specification v2.1 July 2003" */ r = cac_select_CCC(card); if (r == SC_SUCCESS) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "CCC found, is CAC-2"); if (!initialize) /* match card only */ return r; priv = cac_new_private_data(); if (!priv) return SC_ERROR_OUT_OF_MEMORY; r = cac_process_CCC(card, priv); if (r == SC_SUCCESS) { card->type = SC_CARD_TYPE_CAC_II; card->drv_data = priv; return r; } } /* Even some ALT tokens can be missing CCC so we should try with ACA */ r = cac_select_ACA(card); if (r == SC_SUCCESS) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "ACA found, is CAC-2 without CCC"); if (!initialize) /* match card only */ return r; if (!priv) { priv = cac_new_private_data(); if (!priv) return SC_ERROR_OUT_OF_MEMORY; } r = cac_process_ACA(card, priv); if (r == SC_SUCCESS) { card->type = SC_CARD_TYPE_CAC_II; card->drv_data = priv; return r; } } /* is this a CAC Alt token without any accompanying structures */ r = cac_find_first_pki_applet(card, &index); if (r == SC_SUCCESS) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "PKI applet found, is bare CAC Alt"); if (!initialize) /* match card only */ return r; if (!priv) { priv = cac_new_private_data(); if (!priv) return SC_ERROR_OUT_OF_MEMORY; } card->drv_data = priv; /* needed for the read_binary() */ r = cac_populate_cac_alt(card, index, priv); if (r == SC_SUCCESS) { card->type = SC_CARD_TYPE_CAC_II; return r; } card->drv_data = NULL; /* reset on failure */ } if (priv) { cac_free_private_data(priv); } return r; } /* NOTE: returns a bool, 1 card matches, 0 it does not */ static int cac_match_card(sc_card_t *card) { int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* Since we send an APDU, the card's logout function may be called... * however it may be in dirty memory */ card->ops->logout = NULL; r = cac_find_and_initialize(card, 0); return (r == SC_SUCCESS); /* never match */ } static int cac_init(sc_card_t *card) { int r; unsigned long flags; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); r = cac_find_and_initialize(card, 1); if (r < 0) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_CARD); } flags = SC_ALGORITHM_RSA_RAW; _sc_card_add_rsa_alg(card, 1024, flags, 0); /* mandatory */ _sc_card_add_rsa_alg(card, 2048, flags, 0); /* optional */ _sc_card_add_rsa_alg(card, 3072, flags, 0); /* optional */ card->caps |= SC_CARD_CAP_RNG | SC_CARD_CAP_ISO7816_PIN_INFO; SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } static int cac_pin_cmd(sc_card_t *card, struct sc_pin_cmd_data *data, int *tries_left) { /* CAC, like PIV needs Extra validation of (new) PIN during * a PIN change request, to ensure it's not outside the * FIPS 201 4.1.6.1 (numeric only) and * FIPS 140-2 * (6 character minimum) requirements. */ struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); if (data->cmd == SC_PIN_CMD_CHANGE) { int i = 0; if (data->pin2.len < 6) { return SC_ERROR_INVALID_PIN_LENGTH; } for(i=0; i < data->pin2.len; ++i) { if (!isdigit(data->pin2.data[i])) { return SC_ERROR_INVALID_DATA; } } } return iso_drv->ops->pin_cmd(card, data, tries_left); } static struct sc_card_operations cac_ops; static struct sc_card_driver cac_drv = { "Common Access Card (CAC)", "cac", &cac_ops, NULL, 0, NULL }; static struct sc_card_driver * sc_get_driver(void) { struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); cac_ops = *iso_drv->ops; cac_ops.match_card = cac_match_card; cac_ops.init = cac_init; cac_ops.finish = cac_finish; cac_ops.select_file = cac_select_file; /* need to record object type */ cac_ops.get_challenge = cac_get_challenge; cac_ops.read_binary = cac_read_binary; cac_ops.write_binary = cac_write_binary; cac_ops.set_security_env = cac_set_security_env; cac_ops.restore_security_env = cac_restore_security_env; cac_ops.compute_signature = cac_compute_signature; cac_ops.decipher = cac_decipher; cac_ops.card_ctl = cac_card_ctl; cac_ops.pin_cmd = cac_pin_cmd; return &cac_drv; } struct sc_card_driver * sc_get_cac_driver(void) { return sc_get_driver(); }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_346_0
crossvul-cpp_data_good_1848_3
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % SSSSS U U N N % % SS U U NN N % % SSS U U N N N % % SS U U N NN % % SSSSS UUU N N % % % % % % Read/Write Sun Rasterfile Image Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2015 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colormap.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/string_.h" #include "MagickCore/module.h" /* Forward declarations. */ static MagickBooleanType WriteSUNImage(const ImageInfo *,Image *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s S U N % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsSUN() returns MagickTrue if the image format type, identified by the % magick string, is SUN. % % The format of the IsSUN method is: % % MagickBooleanType IsSUN(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsSUN(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (memcmp(magick,"\131\246\152\225",4) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e c o d e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DecodeImage unpacks the packed image pixels into runlength-encoded pixel % packets. % % The format of the DecodeImage method is: % % MagickBooleanType DecodeImage(const unsigned char *compressed_pixels, % const size_t length,unsigned char *pixels) % % A description of each parameter follows: % % o compressed_pixels: The address of a byte (8 bits) array of compressed % pixel data. % % o length: An integer value that is the total number of bytes of the % source image (as just read by ReadBlob) % % o pixels: The address of a byte (8 bits) array of pixel data created by % the uncompression process. The number of bytes in this array % must be at least equal to the number columns times the number of rows % of the source pixels. % */ static MagickBooleanType DecodeImage(const unsigned char *compressed_pixels, const size_t length,unsigned char *pixels,size_t maxpixels) { register const unsigned char *l, *p; register unsigned char *q; ssize_t count; unsigned char byte; (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(compressed_pixels != (unsigned char *) NULL); assert(pixels != (unsigned char *) NULL); p=compressed_pixels; q=pixels; l=q+maxpixels; while (((size_t) (p-compressed_pixels) < length) && (q < l)) { byte=(*p++); if (byte != 128U) *q++=byte; else { /* Runlength-encoded packet: <count><byte> */ count=(ssize_t) (*p++); if (count > 0) byte=(*p++); while ((count >= 0) && (q < l)) { *q++=byte; count--; } } } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d S U N I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadSUNImage() reads a SUN image file and returns it. It allocates % the memory necessary for the new Image structure and returns a pointer to % the new image. % % The format of the ReadSUNImage method is: % % Image *ReadSUNImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadSUNImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define RMT_EQUAL_RGB 1 #define RMT_NONE 0 #define RMT_RAW 2 #define RT_STANDARD 1 #define RT_ENCODED 2 #define RT_FORMAT_RGB 3 typedef struct _SUNInfo { unsigned int magic, width, height, depth, length, type, maptype, maplength; } SUNInfo; Image *image; int bit; MagickBooleanType status; MagickSizeType number_pixels; register Quantum *q; register ssize_t i, x; register unsigned char *p; size_t bytes_per_line, extent, length; ssize_t count, y; SUNInfo sun_info; unsigned char *sun_data, *sun_pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read SUN raster header. */ (void) ResetMagickMemory(&sun_info,0,sizeof(sun_info)); sun_info.magic=ReadBlobMSBLong(image); do { /* Verify SUN identifier. */ if (sun_info.magic != 0x59a66a95) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); sun_info.width=ReadBlobMSBLong(image); sun_info.height=ReadBlobMSBLong(image); sun_info.depth=ReadBlobMSBLong(image); sun_info.length=ReadBlobMSBLong(image); sun_info.type=ReadBlobMSBLong(image); sun_info.maptype=ReadBlobMSBLong(image); sun_info.maplength=ReadBlobMSBLong(image); extent=sun_info.height*sun_info.width; if ((sun_info.height != 0) && (sun_info.width != extent/sun_info.height)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.type != RT_STANDARD) && (sun_info.type != RT_ENCODED) && (sun_info.type != RT_FORMAT_RGB)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.maptype == RMT_NONE) && (sun_info.maplength != 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.depth == 0) || (sun_info.depth > 32)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.maptype != RMT_NONE) && (sun_info.maptype != RMT_EQUAL_RGB) && (sun_info.maptype != RMT_RAW)) ThrowReaderException(CoderError,"ColormapTypeNotSupported"); image->columns=sun_info.width; image->rows=sun_info.height; image->depth=sun_info.depth <= 8 ? sun_info.depth : MAGICKCORE_QUANTUM_DEPTH; if (sun_info.depth < 24) { size_t one; image->colors=sun_info.maplength; one=1; if (sun_info.maptype == RMT_NONE) image->colors=one << sun_info.depth; if (sun_info.maptype == RMT_EQUAL_RGB) image->colors=sun_info.maplength/3; if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } switch (sun_info.maptype) { case RMT_NONE: break; case RMT_EQUAL_RGB: { unsigned char *sun_colormap; /* Read SUN raster colormap. */ sun_colormap=(unsigned char *) AcquireQuantumMemory(image->colors, sizeof(*sun_colormap)); if (sun_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,image->colors,sun_colormap); if (count != (ssize_t) image->colors) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].red=(MagickRealType) ScaleCharToQuantum( sun_colormap[i]); count=ReadBlob(image,image->colors,sun_colormap); if (count != (ssize_t) image->colors) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].green=(MagickRealType) ScaleCharToQuantum( sun_colormap[i]); count=ReadBlob(image,image->colors,sun_colormap); if (count != (ssize_t) image->colors) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum( sun_colormap[i]); sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap); break; } case RMT_RAW: { unsigned char *sun_colormap; /* Read SUN raster colormap. */ sun_colormap=(unsigned char *) AcquireQuantumMemory(sun_info.maplength, sizeof(*sun_colormap)); if (sun_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,sun_info.maplength,sun_colormap); if (count != (ssize_t) sun_info.maplength) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap); break; } default: ThrowReaderException(CoderError,"ColormapTypeNotSupported"); } image->alpha_trait=sun_info.depth == 32 ? BlendPixelTrait : UndefinedPixelTrait; image->columns=sun_info.width; image->rows=sun_info.height; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); if ((sun_info.length*sizeof(*sun_data))/sizeof(*sun_data) != sun_info.length || !sun_info.length) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); number_pixels=(MagickSizeType) image->columns*image->rows; if ((sun_info.type != RT_ENCODED) && (sun_info.depth >= 8) && ((number_pixels*((sun_info.depth+7)/8)) > sun_info.length)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); bytes_per_line=sun_info.width*sun_info.depth; sun_data=(unsigned char *) AcquireQuantumMemory((size_t) MagickMax( sun_info.length,bytes_per_line*sun_info.width),sizeof(*sun_data)); if (sun_data == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=(ssize_t) ReadBlob(image,sun_info.length,sun_data); if (count != (ssize_t) sun_info.length) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); sun_pixels=sun_data; bytes_per_line=0; if (sun_info.type == RT_ENCODED) { size_t height; /* Read run-length encoded raster pixels. */ height=sun_info.height; if ((height == 0) || (sun_info.width == 0) || (sun_info.depth == 0) || ((bytes_per_line/sun_info.depth) != sun_info.width)) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); bytes_per_line+=15; bytes_per_line<<=1; if ((bytes_per_line >> 1) != (sun_info.width*sun_info.depth+15)) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); bytes_per_line>>=4; sun_pixels=(unsigned char *) AcquireQuantumMemory(height, bytes_per_line*sizeof(*sun_pixels)); if (sun_pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) DecodeImage(sun_data,sun_info.length,sun_pixels,bytes_per_line* height); sun_data=(unsigned char *) RelinquishMagickMemory(sun_data); } /* Convert SUN raster image to pixel packets. */ p=sun_pixels; if (sun_info.depth == 1) for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < ((ssize_t) image->columns-7); x+=8) { for (bit=7; bit >= 0; bit--) { SetPixelIndex(image,(Quantum) ((*p) & (0x01 << bit) ? 0x00 : 0x01), q); q+=GetPixelChannels(image); } p++; } if ((image->columns % 8) != 0) { for (bit=7; bit >= (int) (8-(image->columns % 8)); bit--) { SetPixelIndex(image,(Quantum) ((*p) & (0x01 << bit) ? 0x00 : 0x01),q); q+=GetPixelChannels(image); } p++; } if ((((image->columns/8)+(image->columns % 8 ? 1 : 0)) % 2) != 0) p++; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } else if (image->storage_class == PseudoClass) { if (bytes_per_line == 0) bytes_per_line=image->columns; length=image->rows*(image->columns+image->columns % 2); if (((sun_info.type == RT_ENCODED) && (length > (bytes_per_line*image->rows))) || ((sun_info.type != RT_ENCODED) && (length > sun_info.length))) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelIndex(image,*p++,q); q+=GetPixelChannels(image); } if ((image->columns % 2) != 0) p++; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else { size_t bytes_per_pixel; bytes_per_pixel=3; if (image->alpha_trait != UndefinedPixelTrait) bytes_per_pixel++; if (bytes_per_line == 0) bytes_per_line=bytes_per_pixel*image->columns; length=image->rows*(bytes_per_line+image->columns % 2); if (((sun_info.type == RT_ENCODED) && (length > (bytes_per_line*image->rows))) || ((sun_info.type != RT_ENCODED) && (length > sun_info.length))) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ScaleCharToQuantum(*p++),q); if (sun_info.type == RT_STANDARD) { SetPixelBlue(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelRed(image,ScaleCharToQuantum(*p++),q); } else { SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelBlue(image,ScaleCharToQuantum(*p++),q); } if (image->colors != 0) { SetPixelRed(image,ClampToQuantum(image->colormap[(ssize_t) GetPixelRed(image,q)].red),q); SetPixelGreen(image,ClampToQuantum(image->colormap[(ssize_t) GetPixelGreen(image,q)].green),q); SetPixelBlue(image,ClampToQuantum(image->colormap[(ssize_t) GetPixelBlue(image,q)].blue),q); } q+=GetPixelChannels(image); } if (((bytes_per_pixel*image->columns) % 2) != 0) p++; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } if (image->storage_class == PseudoClass) (void) SyncImage(image,exception); sun_pixels=(unsigned char *) RelinquishMagickMemory(sun_pixels); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; sun_info.magic=ReadBlobMSBLong(image); if (sun_info.magic == 0x59a66a95) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (sun_info.magic == 0x59a66a95); (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r S U N I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterSUNImage() adds attributes for the SUN image format to % the list of supported formats. The attributes include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterSUNImage method is: % % size_t RegisterSUNImage(void) % */ ModuleExport size_t RegisterSUNImage(void) { MagickInfo *entry; entry=SetMagickInfo("RAS"); entry->decoder=(DecodeImageHandler *) ReadSUNImage; entry->encoder=(EncodeImageHandler *) WriteSUNImage; entry->magick=(IsImageFormatHandler *) IsSUN; entry->description=ConstantString("SUN Rasterfile"); entry->module=ConstantString("SUN"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("SUN"); entry->decoder=(DecodeImageHandler *) ReadSUNImage; entry->encoder=(EncodeImageHandler *) WriteSUNImage; entry->description=ConstantString("SUN Rasterfile"); entry->module=ConstantString("SUN"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r S U N I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterSUNImage() removes format registrations made by the % SUN module from the list of supported formats. % % The format of the UnregisterSUNImage method is: % % UnregisterSUNImage(void) % */ ModuleExport void UnregisterSUNImage(void) { (void) UnregisterMagickInfo("RAS"); (void) UnregisterMagickInfo("SUN"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e S U N I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteSUNImage() writes an image in the SUN rasterfile format. % % The format of the WriteSUNImage method is: % % MagickBooleanType WriteSUNImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WriteSUNImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { #define RMT_EQUAL_RGB 1 #define RMT_NONE 0 #define RMT_RAW 2 #define RT_STANDARD 1 #define RT_FORMAT_RGB 3 typedef struct _SUNInfo { unsigned int magic, width, height, depth, length, type, maptype, maplength; } SUNInfo; MagickBooleanType status; MagickOffsetType scene; MagickSizeType number_pixels; register const Quantum *p; register ssize_t i, x; ssize_t y; SUNInfo sun_info; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); scene=0; do { /* Initialize SUN raster file header. */ (void) TransformImageColorspace(image,sRGBColorspace,exception); sun_info.magic=0x59a66a95; if ((image->columns != (unsigned int) image->columns) || (image->rows != (unsigned int) image->rows)) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); sun_info.width=(unsigned int) image->columns; sun_info.height=(unsigned int) image->rows; sun_info.type=(unsigned int) (image->storage_class == DirectClass ? RT_FORMAT_RGB : RT_STANDARD); sun_info.maptype=RMT_NONE; sun_info.maplength=0; number_pixels=(MagickSizeType) image->columns*image->rows; if ((4*number_pixels) != (size_t) (4*number_pixels)) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if (image->storage_class == DirectClass) { /* Full color SUN raster. */ sun_info.depth=(unsigned int) image->alpha_trait != UndefinedPixelTrait ? 32U : 24U; sun_info.length=(unsigned int) ((image->alpha_trait != UndefinedPixelTrait ? 4 : 3)*number_pixels); sun_info.length+=sun_info.length & 0x01 ? (unsigned int) image->rows : 0; } else if (IsImageMonochrome(image,exception) != MagickFalse) { /* Monochrome SUN raster. */ sun_info.depth=1; sun_info.length=(unsigned int) (((image->columns+7) >> 3)* image->rows); sun_info.length+=(unsigned int) (((image->columns/8)+(image->columns % 8 ? 1 : 0)) % 2 ? image->rows : 0); } else { /* Colormapped SUN raster. */ sun_info.depth=8; sun_info.length=(unsigned int) number_pixels; sun_info.length+=(unsigned int) (image->columns & 0x01 ? image->rows : 0); sun_info.maptype=RMT_EQUAL_RGB; sun_info.maplength=(unsigned int) (3*image->colors); } /* Write SUN header. */ (void) WriteBlobMSBLong(image,sun_info.magic); (void) WriteBlobMSBLong(image,sun_info.width); (void) WriteBlobMSBLong(image,sun_info.height); (void) WriteBlobMSBLong(image,sun_info.depth); (void) WriteBlobMSBLong(image,sun_info.length); (void) WriteBlobMSBLong(image,sun_info.type); (void) WriteBlobMSBLong(image,sun_info.maptype); (void) WriteBlobMSBLong(image,sun_info.maplength); /* Convert MIFF to SUN raster pixels. */ x=0; y=0; if (image->storage_class == DirectClass) { register unsigned char *q; size_t bytes_per_pixel, length; unsigned char *pixels; /* Allocate memory for pixels. */ bytes_per_pixel=3; if (image->alpha_trait != UndefinedPixelTrait) bytes_per_pixel++; length=image->columns; pixels=(unsigned char *) AcquireQuantumMemory(length,4*sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Convert DirectClass packet to SUN RGB pixel. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels; for (x=0; x < (ssize_t) image->columns; x++) { if (image->alpha_trait != UndefinedPixelTrait) *q++=ScaleQuantumToChar(GetPixelAlpha(image,p)); *q++=ScaleQuantumToChar(GetPixelRed(image,p)); *q++=ScaleQuantumToChar(GetPixelGreen(image,p)); *q++=ScaleQuantumToChar(GetPixelBlue(image,p)); p+=GetPixelChannels(image); } if (((bytes_per_pixel*image->columns) & 0x01) != 0) *q++='\0'; /* pad scanline */ (void) WriteBlob(image,(size_t) (q-pixels),pixels); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } pixels=(unsigned char *) RelinquishMagickMemory(pixels); } else if (IsImageMonochrome(image,exception) != MagickFalse) { register unsigned char bit, byte; /* Convert PseudoClass image to a SUN monochrome image. */ (void) SetImageType(image,BilevelType,exception); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; bit=0; byte=0; for (x=0; x < (ssize_t) image->columns; x++) { byte<<=1; if (GetPixelLuma(image,p) < (QuantumRange/2.0)) byte|=0x01; bit++; if (bit == 8) { (void) WriteBlobByte(image,byte); bit=0; byte=0; } p+=GetPixelChannels(image); } if (bit != 0) (void) WriteBlobByte(image,(unsigned char) (byte << (8-bit))); if ((((image->columns/8)+ (image->columns % 8 ? 1 : 0)) % 2) != 0) (void) WriteBlobByte(image,0); /* pad scanline */ if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else { /* Dump colormap to file. */ for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar( ClampToQuantum(image->colormap[i].red))); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar( ClampToQuantum(image->colormap[i].green))); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar( ClampToQuantum(image->colormap[i].blue))); /* Convert PseudoClass packet to SUN colormapped pixel. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { (void) WriteBlobByte(image,(unsigned char) GetPixelIndex(image,p)); p+=GetPixelChannels(image); } if (image->columns & 0x01) (void) WriteBlobByte(image,0); /* pad scanline */ if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(MagickTrue); }
./CrossVul/dataset_final_sorted/CWE-119/c/good_1848_3
crossvul-cpp_data_bad_3317_0
/* * Copyright (c) 1999-2013 Petko Manolov (petkan@nucleusys.com) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * ChangeLog: * .... Most of the time spent on reading sources & docs. * v0.2.x First official release for the Linux kernel. * v0.3.0 Beutified and structured, some bugs fixed. * v0.3.x URBifying bulk requests and bugfixing. First relatively * stable release. Still can touch device's registers only * from top-halves. * v0.4.0 Control messages remained unurbified are now URBs. * Now we can touch the HW at any time. * v0.4.9 Control urbs again use process context to wait. Argh... * Some long standing bugs (enable_net_traffic) fixed. * Also nasty trick about resubmiting control urb from * interrupt context used. Please let me know how it * behaves. Pegasus II support added since this version. * TODO: suppressing HCD warnings spewage on disconnect. * v0.4.13 Ethernet address is now set at probe(), not at open() * time as this seems to break dhcpd. * v0.5.0 branch to 2.5.x kernels * v0.5.1 ethtool support added * v0.5.5 rx socket buffers are in a pool and the their allocation * is out of the interrupt routine. * ... * v0.9.3 simplified [get|set]_register(s), async update registers * logic revisited, receive skb_pool removed. */ #include <linux/sched.h> #include <linux/slab.h> #include <linux/init.h> #include <linux/delay.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/ethtool.h> #include <linux/mii.h> #include <linux/usb.h> #include <linux/module.h> #include <asm/byteorder.h> #include <linux/uaccess.h> #include "pegasus.h" /* * Version Information */ #define DRIVER_VERSION "v0.9.3 (2013/04/25)" #define DRIVER_AUTHOR "Petko Manolov <petkan@nucleusys.com>" #define DRIVER_DESC "Pegasus/Pegasus II USB Ethernet driver" static const char driver_name[] = "pegasus"; #undef PEGASUS_WRITE_EEPROM #define BMSR_MEDIA (BMSR_10HALF | BMSR_10FULL | BMSR_100HALF | \ BMSR_100FULL | BMSR_ANEGCAPABLE) static bool loopback; static bool mii_mode; static char *devid; static struct usb_eth_dev usb_dev_id[] = { #define PEGASUS_DEV(pn, vid, pid, flags) \ {.name = pn, .vendor = vid, .device = pid, .private = flags}, #define PEGASUS_DEV_CLASS(pn, vid, pid, dclass, flags) \ PEGASUS_DEV(pn, vid, pid, flags) #include "pegasus.h" #undef PEGASUS_DEV #undef PEGASUS_DEV_CLASS {NULL, 0, 0, 0}, {NULL, 0, 0, 0} }; static struct usb_device_id pegasus_ids[] = { #define PEGASUS_DEV(pn, vid, pid, flags) \ {.match_flags = USB_DEVICE_ID_MATCH_DEVICE, .idVendor = vid, .idProduct = pid}, /* * The Belkin F8T012xx1 bluetooth adaptor has the same vendor and product * IDs as the Belkin F5D5050, so we need to teach the pegasus driver to * ignore adaptors belonging to the "Wireless" class 0xE0. For this one * case anyway, seeing as the pegasus is for "Wired" adaptors. */ #define PEGASUS_DEV_CLASS(pn, vid, pid, dclass, flags) \ {.match_flags = (USB_DEVICE_ID_MATCH_DEVICE | USB_DEVICE_ID_MATCH_DEV_CLASS), \ .idVendor = vid, .idProduct = pid, .bDeviceClass = dclass}, #include "pegasus.h" #undef PEGASUS_DEV #undef PEGASUS_DEV_CLASS {}, {} }; MODULE_AUTHOR(DRIVER_AUTHOR); MODULE_DESCRIPTION(DRIVER_DESC); MODULE_LICENSE("GPL"); module_param(loopback, bool, 0); module_param(mii_mode, bool, 0); module_param(devid, charp, 0); MODULE_PARM_DESC(loopback, "Enable MAC loopback mode (bit 0)"); MODULE_PARM_DESC(mii_mode, "Enable HomePNA mode (bit 0),default=MII mode = 0"); MODULE_PARM_DESC(devid, "The format is: 'DEV_name:VendorID:DeviceID:Flags'"); /* use ethtool to change the level for any given device */ static int msg_level = -1; module_param(msg_level, int, 0); MODULE_PARM_DESC(msg_level, "Override default message level"); MODULE_DEVICE_TABLE(usb, pegasus_ids); static const struct net_device_ops pegasus_netdev_ops; /*****/ static void async_ctrl_callback(struct urb *urb) { struct usb_ctrlrequest *req = (struct usb_ctrlrequest *)urb->context; int status = urb->status; if (status < 0) dev_dbg(&urb->dev->dev, "%s failed with %d", __func__, status); kfree(req); usb_free_urb(urb); } static int get_registers(pegasus_t *pegasus, __u16 indx, __u16 size, void *data) { int ret; ret = usb_control_msg(pegasus->usb, usb_rcvctrlpipe(pegasus->usb, 0), PEGASUS_REQ_GET_REGS, PEGASUS_REQT_READ, 0, indx, data, size, 1000); if (ret < 0) netif_dbg(pegasus, drv, pegasus->net, "%s returned %d\n", __func__, ret); return ret; } static int set_registers(pegasus_t *pegasus, __u16 indx, __u16 size, void *data) { int ret; ret = usb_control_msg(pegasus->usb, usb_sndctrlpipe(pegasus->usb, 0), PEGASUS_REQ_SET_REGS, PEGASUS_REQT_WRITE, 0, indx, data, size, 100); if (ret < 0) netif_dbg(pegasus, drv, pegasus->net, "%s returned %d\n", __func__, ret); return ret; } static int set_register(pegasus_t *pegasus, __u16 indx, __u8 data) { int ret; ret = usb_control_msg(pegasus->usb, usb_sndctrlpipe(pegasus->usb, 0), PEGASUS_REQ_SET_REG, PEGASUS_REQT_WRITE, data, indx, &data, 1, 1000); if (ret < 0) netif_dbg(pegasus, drv, pegasus->net, "%s returned %d\n", __func__, ret); return ret; } static int update_eth_regs_async(pegasus_t *pegasus) { int ret = -ENOMEM; struct urb *async_urb; struct usb_ctrlrequest *req; req = kmalloc(sizeof(struct usb_ctrlrequest), GFP_ATOMIC); if (req == NULL) return ret; async_urb = usb_alloc_urb(0, GFP_ATOMIC); if (async_urb == NULL) { kfree(req); return ret; } req->bRequestType = PEGASUS_REQT_WRITE; req->bRequest = PEGASUS_REQ_SET_REGS; req->wValue = cpu_to_le16(0); req->wIndex = cpu_to_le16(EthCtrl0); req->wLength = cpu_to_le16(3); usb_fill_control_urb(async_urb, pegasus->usb, usb_sndctrlpipe(pegasus->usb, 0), (void *)req, pegasus->eth_regs, 3, async_ctrl_callback, req); ret = usb_submit_urb(async_urb, GFP_ATOMIC); if (ret) { if (ret == -ENODEV) netif_device_detach(pegasus->net); netif_err(pegasus, drv, pegasus->net, "%s returned %d\n", __func__, ret); } return ret; } static int __mii_op(pegasus_t *p, __u8 phy, __u8 indx, __u16 *regd, __u8 cmd) { int i; __u8 data[4] = { phy, 0, 0, indx }; __le16 regdi; int ret = -ETIMEDOUT; if (cmd & PHY_WRITE) { __le16 *t = (__le16 *) & data[1]; *t = cpu_to_le16(*regd); } set_register(p, PhyCtrl, 0); set_registers(p, PhyAddr, sizeof(data), data); set_register(p, PhyCtrl, (indx | cmd)); for (i = 0; i < REG_TIMEOUT; i++) { ret = get_registers(p, PhyCtrl, 1, data); if (ret < 0) goto fail; if (data[0] & PHY_DONE) break; } if (i >= REG_TIMEOUT) goto fail; if (cmd & PHY_READ) { ret = get_registers(p, PhyData, 2, &regdi); *regd = le16_to_cpu(regdi); return ret; } return 0; fail: netif_dbg(p, drv, p->net, "%s failed\n", __func__); return ret; } /* Returns non-negative int on success, error on failure */ static int read_mii_word(pegasus_t *pegasus, __u8 phy, __u8 indx, __u16 *regd) { return __mii_op(pegasus, phy, indx, regd, PHY_READ); } /* Returns zero on success, error on failure */ static int write_mii_word(pegasus_t *pegasus, __u8 phy, __u8 indx, __u16 *regd) { return __mii_op(pegasus, phy, indx, regd, PHY_WRITE); } static int mdio_read(struct net_device *dev, int phy_id, int loc) { pegasus_t *pegasus = netdev_priv(dev); u16 res; read_mii_word(pegasus, phy_id, loc, &res); return (int)res; } static void mdio_write(struct net_device *dev, int phy_id, int loc, int val) { pegasus_t *pegasus = netdev_priv(dev); u16 data = val; write_mii_word(pegasus, phy_id, loc, &data); } static int read_eprom_word(pegasus_t *pegasus, __u8 index, __u16 *retdata) { int i; __u8 tmp; __le16 retdatai; int ret; set_register(pegasus, EpromCtrl, 0); set_register(pegasus, EpromOffset, index); set_register(pegasus, EpromCtrl, EPROM_READ); for (i = 0; i < REG_TIMEOUT; i++) { ret = get_registers(pegasus, EpromCtrl, 1, &tmp); if (tmp & EPROM_DONE) break; if (ret == -ESHUTDOWN) goto fail; } if (i >= REG_TIMEOUT) goto fail; ret = get_registers(pegasus, EpromData, 2, &retdatai); *retdata = le16_to_cpu(retdatai); return ret; fail: netif_warn(pegasus, drv, pegasus->net, "%s failed\n", __func__); return -ETIMEDOUT; } #ifdef PEGASUS_WRITE_EEPROM static inline void enable_eprom_write(pegasus_t *pegasus) { __u8 tmp; get_registers(pegasus, EthCtrl2, 1, &tmp); set_register(pegasus, EthCtrl2, tmp | EPROM_WR_ENABLE); } static inline void disable_eprom_write(pegasus_t *pegasus) { __u8 tmp; get_registers(pegasus, EthCtrl2, 1, &tmp); set_register(pegasus, EpromCtrl, 0); set_register(pegasus, EthCtrl2, tmp & ~EPROM_WR_ENABLE); } static int write_eprom_word(pegasus_t *pegasus, __u8 index, __u16 data) { int i; __u8 tmp, d[4] = { 0x3f, 0, 0, EPROM_WRITE }; int ret; __le16 le_data = cpu_to_le16(data); set_registers(pegasus, EpromOffset, 4, d); enable_eprom_write(pegasus); set_register(pegasus, EpromOffset, index); set_registers(pegasus, EpromData, 2, &le_data); set_register(pegasus, EpromCtrl, EPROM_WRITE); for (i = 0; i < REG_TIMEOUT; i++) { ret = get_registers(pegasus, EpromCtrl, 1, &tmp); if (ret == -ESHUTDOWN) goto fail; if (tmp & EPROM_DONE) break; } disable_eprom_write(pegasus); if (i >= REG_TIMEOUT) goto fail; return ret; fail: netif_warn(pegasus, drv, pegasus->net, "%s failed\n", __func__); return -ETIMEDOUT; } #endif /* PEGASUS_WRITE_EEPROM */ static inline void get_node_id(pegasus_t *pegasus, __u8 *id) { int i; __u16 w16; for (i = 0; i < 3; i++) { read_eprom_word(pegasus, i, &w16); ((__le16 *) id)[i] = cpu_to_le16(w16); } } static void set_ethernet_addr(pegasus_t *pegasus) { __u8 node_id[6]; if (pegasus->features & PEGASUS_II) { get_registers(pegasus, 0x10, sizeof(node_id), node_id); } else { get_node_id(pegasus, node_id); set_registers(pegasus, EthID, sizeof(node_id), node_id); } memcpy(pegasus->net->dev_addr, node_id, sizeof(node_id)); } static inline int reset_mac(pegasus_t *pegasus) { __u8 data = 0x8; int i; set_register(pegasus, EthCtrl1, data); for (i = 0; i < REG_TIMEOUT; i++) { get_registers(pegasus, EthCtrl1, 1, &data); if (~data & 0x08) { if (loopback) break; if (mii_mode && (pegasus->features & HAS_HOME_PNA)) set_register(pegasus, Gpio1, 0x34); else set_register(pegasus, Gpio1, 0x26); set_register(pegasus, Gpio0, pegasus->features); set_register(pegasus, Gpio0, DEFAULT_GPIO_SET); break; } } if (i == REG_TIMEOUT) return -ETIMEDOUT; if (usb_dev_id[pegasus->dev_index].vendor == VENDOR_LINKSYS || usb_dev_id[pegasus->dev_index].vendor == VENDOR_DLINK) { set_register(pegasus, Gpio0, 0x24); set_register(pegasus, Gpio0, 0x26); } if (usb_dev_id[pegasus->dev_index].vendor == VENDOR_ELCON) { __u16 auxmode; read_mii_word(pegasus, 3, 0x1b, &auxmode); auxmode |= 4; write_mii_word(pegasus, 3, 0x1b, &auxmode); } return 0; } static int enable_net_traffic(struct net_device *dev, struct usb_device *usb) { __u16 linkpart; __u8 data[4]; pegasus_t *pegasus = netdev_priv(dev); int ret; read_mii_word(pegasus, pegasus->phy, MII_LPA, &linkpart); data[0] = 0xc8; /* TX & RX enable, append status, no CRC */ data[1] = 0; if (linkpart & (ADVERTISE_100FULL | ADVERTISE_10FULL)) data[1] |= 0x20; /* set full duplex */ if (linkpart & (ADVERTISE_100FULL | ADVERTISE_100HALF)) data[1] |= 0x10; /* set 100 Mbps */ if (mii_mode) data[1] = 0; data[2] = loopback ? 0x09 : 0x01; memcpy(pegasus->eth_regs, data, sizeof(data)); ret = set_registers(pegasus, EthCtrl0, 3, data); if (usb_dev_id[pegasus->dev_index].vendor == VENDOR_LINKSYS || usb_dev_id[pegasus->dev_index].vendor == VENDOR_LINKSYS2 || usb_dev_id[pegasus->dev_index].vendor == VENDOR_DLINK) { u16 auxmode; read_mii_word(pegasus, 0, 0x1b, &auxmode); auxmode |= 4; write_mii_word(pegasus, 0, 0x1b, &auxmode); } return ret; } static void read_bulk_callback(struct urb *urb) { pegasus_t *pegasus = urb->context; struct net_device *net; int rx_status, count = urb->actual_length; int status = urb->status; u8 *buf = urb->transfer_buffer; __u16 pkt_len; if (!pegasus) return; net = pegasus->net; if (!netif_device_present(net) || !netif_running(net)) return; switch (status) { case 0: break; case -ETIME: netif_dbg(pegasus, rx_err, net, "reset MAC\n"); pegasus->flags &= ~PEGASUS_RX_BUSY; break; case -EPIPE: /* stall, or disconnect from TT */ /* FIXME schedule work to clear the halt */ netif_warn(pegasus, rx_err, net, "no rx stall recovery\n"); return; case -ENOENT: case -ECONNRESET: case -ESHUTDOWN: netif_dbg(pegasus, ifdown, net, "rx unlink, %d\n", status); return; default: netif_dbg(pegasus, rx_err, net, "RX status %d\n", status); goto goon; } if (count < 4) goto goon; rx_status = buf[count - 2]; if (rx_status & 0x1e) { netif_dbg(pegasus, rx_err, net, "RX packet error %x\n", rx_status); pegasus->stats.rx_errors++; if (rx_status & 0x06) /* long or runt */ pegasus->stats.rx_length_errors++; if (rx_status & 0x08) pegasus->stats.rx_crc_errors++; if (rx_status & 0x10) /* extra bits */ pegasus->stats.rx_frame_errors++; goto goon; } if (pegasus->chip == 0x8513) { pkt_len = le32_to_cpu(*(__le32 *)urb->transfer_buffer); pkt_len &= 0x0fff; pegasus->rx_skb->data += 2; } else { pkt_len = buf[count - 3] << 8; pkt_len += buf[count - 4]; pkt_len &= 0xfff; pkt_len -= 4; } /* * If the packet is unreasonably long, quietly drop it rather than * kernel panicing by calling skb_put. */ if (pkt_len > PEGASUS_MTU) goto goon; /* * at this point we are sure pegasus->rx_skb != NULL * so we go ahead and pass up the packet. */ skb_put(pegasus->rx_skb, pkt_len); pegasus->rx_skb->protocol = eth_type_trans(pegasus->rx_skb, net); netif_rx(pegasus->rx_skb); pegasus->stats.rx_packets++; pegasus->stats.rx_bytes += pkt_len; if (pegasus->flags & PEGASUS_UNPLUG) return; pegasus->rx_skb = __netdev_alloc_skb_ip_align(pegasus->net, PEGASUS_MTU, GFP_ATOMIC); if (pegasus->rx_skb == NULL) goto tl_sched; goon: usb_fill_bulk_urb(pegasus->rx_urb, pegasus->usb, usb_rcvbulkpipe(pegasus->usb, 1), pegasus->rx_skb->data, PEGASUS_MTU, read_bulk_callback, pegasus); rx_status = usb_submit_urb(pegasus->rx_urb, GFP_ATOMIC); if (rx_status == -ENODEV) netif_device_detach(pegasus->net); else if (rx_status) { pegasus->flags |= PEGASUS_RX_URB_FAIL; goto tl_sched; } else { pegasus->flags &= ~PEGASUS_RX_URB_FAIL; } return; tl_sched: tasklet_schedule(&pegasus->rx_tl); } static void rx_fixup(unsigned long data) { pegasus_t *pegasus; int status; pegasus = (pegasus_t *) data; if (pegasus->flags & PEGASUS_UNPLUG) return; if (pegasus->flags & PEGASUS_RX_URB_FAIL) if (pegasus->rx_skb) goto try_again; if (pegasus->rx_skb == NULL) pegasus->rx_skb = __netdev_alloc_skb_ip_align(pegasus->net, PEGASUS_MTU, GFP_ATOMIC); if (pegasus->rx_skb == NULL) { netif_warn(pegasus, rx_err, pegasus->net, "low on memory\n"); tasklet_schedule(&pegasus->rx_tl); return; } usb_fill_bulk_urb(pegasus->rx_urb, pegasus->usb, usb_rcvbulkpipe(pegasus->usb, 1), pegasus->rx_skb->data, PEGASUS_MTU, read_bulk_callback, pegasus); try_again: status = usb_submit_urb(pegasus->rx_urb, GFP_ATOMIC); if (status == -ENODEV) netif_device_detach(pegasus->net); else if (status) { pegasus->flags |= PEGASUS_RX_URB_FAIL; tasklet_schedule(&pegasus->rx_tl); } else { pegasus->flags &= ~PEGASUS_RX_URB_FAIL; } } static void write_bulk_callback(struct urb *urb) { pegasus_t *pegasus = urb->context; struct net_device *net; int status = urb->status; if (!pegasus) return; net = pegasus->net; if (!netif_device_present(net) || !netif_running(net)) return; switch (status) { case -EPIPE: /* FIXME schedule_work() to clear the tx halt */ netif_stop_queue(net); netif_warn(pegasus, tx_err, net, "no tx stall recovery\n"); return; case -ENOENT: case -ECONNRESET: case -ESHUTDOWN: netif_dbg(pegasus, ifdown, net, "tx unlink, %d\n", status); return; default: netif_info(pegasus, tx_err, net, "TX status %d\n", status); /* FALL THROUGH */ case 0: break; } netif_trans_update(net); /* prevent tx timeout */ netif_wake_queue(net); } static void intr_callback(struct urb *urb) { pegasus_t *pegasus = urb->context; struct net_device *net; int res, status = urb->status; if (!pegasus) return; net = pegasus->net; switch (status) { case 0: break; case -ECONNRESET: /* unlink */ case -ENOENT: case -ESHUTDOWN: return; default: /* some Pegasus-I products report LOTS of data * toggle errors... avoid log spamming */ netif_dbg(pegasus, timer, net, "intr status %d\n", status); } if (urb->actual_length >= 6) { u8 *d = urb->transfer_buffer; /* byte 0 == tx_status1, reg 2B */ if (d[0] & (TX_UNDERRUN|EXCESSIVE_COL |LATE_COL|JABBER_TIMEOUT)) { pegasus->stats.tx_errors++; if (d[0] & TX_UNDERRUN) pegasus->stats.tx_fifo_errors++; if (d[0] & (EXCESSIVE_COL | JABBER_TIMEOUT)) pegasus->stats.tx_aborted_errors++; if (d[0] & LATE_COL) pegasus->stats.tx_window_errors++; } /* d[5].LINK_STATUS lies on some adapters. * d[0].NO_CARRIER kicks in only with failed TX. * ... so monitoring with MII may be safest. */ /* bytes 3-4 == rx_lostpkt, reg 2E/2F */ pegasus->stats.rx_missed_errors += ((d[3] & 0x7f) << 8) | d[4]; } res = usb_submit_urb(urb, GFP_ATOMIC); if (res == -ENODEV) netif_device_detach(pegasus->net); if (res) netif_err(pegasus, timer, net, "can't resubmit interrupt urb, %d\n", res); } static void pegasus_tx_timeout(struct net_device *net) { pegasus_t *pegasus = netdev_priv(net); netif_warn(pegasus, timer, net, "tx timeout\n"); usb_unlink_urb(pegasus->tx_urb); pegasus->stats.tx_errors++; } static netdev_tx_t pegasus_start_xmit(struct sk_buff *skb, struct net_device *net) { pegasus_t *pegasus = netdev_priv(net); int count = ((skb->len + 2) & 0x3f) ? skb->len + 2 : skb->len + 3; int res; __u16 l16 = skb->len; netif_stop_queue(net); ((__le16 *) pegasus->tx_buff)[0] = cpu_to_le16(l16); skb_copy_from_linear_data(skb, pegasus->tx_buff + 2, skb->len); usb_fill_bulk_urb(pegasus->tx_urb, pegasus->usb, usb_sndbulkpipe(pegasus->usb, 2), pegasus->tx_buff, count, write_bulk_callback, pegasus); if ((res = usb_submit_urb(pegasus->tx_urb, GFP_ATOMIC))) { netif_warn(pegasus, tx_err, net, "fail tx, %d\n", res); switch (res) { case -EPIPE: /* stall, or disconnect from TT */ /* cleanup should already have been scheduled */ break; case -ENODEV: /* disconnect() upcoming */ case -EPERM: netif_device_detach(pegasus->net); break; default: pegasus->stats.tx_errors++; netif_start_queue(net); } } else { pegasus->stats.tx_packets++; pegasus->stats.tx_bytes += skb->len; } dev_kfree_skb(skb); return NETDEV_TX_OK; } static struct net_device_stats *pegasus_netdev_stats(struct net_device *dev) { return &((pegasus_t *) netdev_priv(dev))->stats; } static inline void disable_net_traffic(pegasus_t *pegasus) { __le16 tmp = cpu_to_le16(0); set_registers(pegasus, EthCtrl0, sizeof(tmp), &tmp); } static inline void get_interrupt_interval(pegasus_t *pegasus) { u16 data; u8 interval; read_eprom_word(pegasus, 4, &data); interval = data >> 8; if (pegasus->usb->speed != USB_SPEED_HIGH) { if (interval < 0x80) { netif_info(pegasus, timer, pegasus->net, "intr interval changed from %ums to %ums\n", interval, 0x80); interval = 0x80; data = (data & 0x00FF) | ((u16)interval << 8); #ifdef PEGASUS_WRITE_EEPROM write_eprom_word(pegasus, 4, data); #endif } } pegasus->intr_interval = interval; } static void set_carrier(struct net_device *net) { pegasus_t *pegasus = netdev_priv(net); u16 tmp; if (read_mii_word(pegasus, pegasus->phy, MII_BMSR, &tmp)) return; if (tmp & BMSR_LSTATUS) netif_carrier_on(net); else netif_carrier_off(net); } static void free_all_urbs(pegasus_t *pegasus) { usb_free_urb(pegasus->intr_urb); usb_free_urb(pegasus->tx_urb); usb_free_urb(pegasus->rx_urb); } static void unlink_all_urbs(pegasus_t *pegasus) { usb_kill_urb(pegasus->intr_urb); usb_kill_urb(pegasus->tx_urb); usb_kill_urb(pegasus->rx_urb); } static int alloc_urbs(pegasus_t *pegasus) { int res = -ENOMEM; pegasus->rx_urb = usb_alloc_urb(0, GFP_KERNEL); if (!pegasus->rx_urb) { return res; } pegasus->tx_urb = usb_alloc_urb(0, GFP_KERNEL); if (!pegasus->tx_urb) { usb_free_urb(pegasus->rx_urb); return res; } pegasus->intr_urb = usb_alloc_urb(0, GFP_KERNEL); if (!pegasus->intr_urb) { usb_free_urb(pegasus->tx_urb); usb_free_urb(pegasus->rx_urb); return res; } return 0; } static int pegasus_open(struct net_device *net) { pegasus_t *pegasus = netdev_priv(net); int res=-ENOMEM; if (pegasus->rx_skb == NULL) pegasus->rx_skb = __netdev_alloc_skb_ip_align(pegasus->net, PEGASUS_MTU, GFP_KERNEL); if (!pegasus->rx_skb) goto exit; res = set_registers(pegasus, EthID, 6, net->dev_addr); usb_fill_bulk_urb(pegasus->rx_urb, pegasus->usb, usb_rcvbulkpipe(pegasus->usb, 1), pegasus->rx_skb->data, PEGASUS_MTU, read_bulk_callback, pegasus); if ((res = usb_submit_urb(pegasus->rx_urb, GFP_KERNEL))) { if (res == -ENODEV) netif_device_detach(pegasus->net); netif_dbg(pegasus, ifup, net, "failed rx_urb, %d\n", res); goto exit; } usb_fill_int_urb(pegasus->intr_urb, pegasus->usb, usb_rcvintpipe(pegasus->usb, 3), pegasus->intr_buff, sizeof(pegasus->intr_buff), intr_callback, pegasus, pegasus->intr_interval); if ((res = usb_submit_urb(pegasus->intr_urb, GFP_KERNEL))) { if (res == -ENODEV) netif_device_detach(pegasus->net); netif_dbg(pegasus, ifup, net, "failed intr_urb, %d\n", res); usb_kill_urb(pegasus->rx_urb); goto exit; } res = enable_net_traffic(net, pegasus->usb); if (res < 0) { netif_dbg(pegasus, ifup, net, "can't enable_net_traffic() - %d\n", res); res = -EIO; usb_kill_urb(pegasus->rx_urb); usb_kill_urb(pegasus->intr_urb); goto exit; } set_carrier(net); netif_start_queue(net); netif_dbg(pegasus, ifup, net, "open\n"); res = 0; exit: return res; } static int pegasus_close(struct net_device *net) { pegasus_t *pegasus = netdev_priv(net); netif_stop_queue(net); if (!(pegasus->flags & PEGASUS_UNPLUG)) disable_net_traffic(pegasus); tasklet_kill(&pegasus->rx_tl); unlink_all_urbs(pegasus); return 0; } static void pegasus_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info) { pegasus_t *pegasus = netdev_priv(dev); strlcpy(info->driver, driver_name, sizeof(info->driver)); strlcpy(info->version, DRIVER_VERSION, sizeof(info->version)); usb_make_path(pegasus->usb, info->bus_info, sizeof(info->bus_info)); } /* also handles three patterns of some kind in hardware */ #define WOL_SUPPORTED (WAKE_MAGIC|WAKE_PHY) static void pegasus_get_wol(struct net_device *dev, struct ethtool_wolinfo *wol) { pegasus_t *pegasus = netdev_priv(dev); wol->supported = WAKE_MAGIC | WAKE_PHY; wol->wolopts = pegasus->wolopts; } static int pegasus_set_wol(struct net_device *dev, struct ethtool_wolinfo *wol) { pegasus_t *pegasus = netdev_priv(dev); u8 reg78 = 0x04; int ret; if (wol->wolopts & ~WOL_SUPPORTED) return -EINVAL; if (wol->wolopts & WAKE_MAGIC) reg78 |= 0x80; if (wol->wolopts & WAKE_PHY) reg78 |= 0x40; /* FIXME this 0x10 bit still needs to get set in the chip... */ if (wol->wolopts) pegasus->eth_regs[0] |= 0x10; else pegasus->eth_regs[0] &= ~0x10; pegasus->wolopts = wol->wolopts; ret = set_register(pegasus, WakeupControl, reg78); if (!ret) ret = device_set_wakeup_enable(&pegasus->usb->dev, wol->wolopts); return ret; } static inline void pegasus_reset_wol(struct net_device *dev) { struct ethtool_wolinfo wol; memset(&wol, 0, sizeof wol); (void) pegasus_set_wol(dev, &wol); } static int pegasus_get_settings(struct net_device *dev, struct ethtool_cmd *ecmd) { pegasus_t *pegasus; pegasus = netdev_priv(dev); mii_ethtool_gset(&pegasus->mii, ecmd); return 0; } static int pegasus_set_settings(struct net_device *dev, struct ethtool_cmd *ecmd) { pegasus_t *pegasus = netdev_priv(dev); return mii_ethtool_sset(&pegasus->mii, ecmd); } static int pegasus_nway_reset(struct net_device *dev) { pegasus_t *pegasus = netdev_priv(dev); return mii_nway_restart(&pegasus->mii); } static u32 pegasus_get_link(struct net_device *dev) { pegasus_t *pegasus = netdev_priv(dev); return mii_link_ok(&pegasus->mii); } static u32 pegasus_get_msglevel(struct net_device *dev) { pegasus_t *pegasus = netdev_priv(dev); return pegasus->msg_enable; } static void pegasus_set_msglevel(struct net_device *dev, u32 v) { pegasus_t *pegasus = netdev_priv(dev); pegasus->msg_enable = v; } static const struct ethtool_ops ops = { .get_drvinfo = pegasus_get_drvinfo, .get_settings = pegasus_get_settings, .set_settings = pegasus_set_settings, .nway_reset = pegasus_nway_reset, .get_link = pegasus_get_link, .get_msglevel = pegasus_get_msglevel, .set_msglevel = pegasus_set_msglevel, .get_wol = pegasus_get_wol, .set_wol = pegasus_set_wol, }; static int pegasus_ioctl(struct net_device *net, struct ifreq *rq, int cmd) { __u16 *data = (__u16 *) &rq->ifr_ifru; pegasus_t *pegasus = netdev_priv(net); int res; switch (cmd) { case SIOCDEVPRIVATE: data[0] = pegasus->phy; case SIOCDEVPRIVATE + 1: read_mii_word(pegasus, data[0], data[1] & 0x1f, &data[3]); res = 0; break; case SIOCDEVPRIVATE + 2: if (!capable(CAP_NET_ADMIN)) return -EPERM; write_mii_word(pegasus, pegasus->phy, data[1] & 0x1f, &data[2]); res = 0; break; default: res = -EOPNOTSUPP; } return res; } static void pegasus_set_multicast(struct net_device *net) { pegasus_t *pegasus = netdev_priv(net); if (net->flags & IFF_PROMISC) { pegasus->eth_regs[EthCtrl2] |= RX_PROMISCUOUS; netif_info(pegasus, link, net, "Promiscuous mode enabled\n"); } else if (!netdev_mc_empty(net) || (net->flags & IFF_ALLMULTI)) { pegasus->eth_regs[EthCtrl0] |= RX_MULTICAST; pegasus->eth_regs[EthCtrl2] &= ~RX_PROMISCUOUS; netif_dbg(pegasus, link, net, "set allmulti\n"); } else { pegasus->eth_regs[EthCtrl0] &= ~RX_MULTICAST; pegasus->eth_regs[EthCtrl2] &= ~RX_PROMISCUOUS; } update_eth_regs_async(pegasus); } static __u8 mii_phy_probe(pegasus_t *pegasus) { int i; __u16 tmp; for (i = 0; i < 32; i++) { read_mii_word(pegasus, i, MII_BMSR, &tmp); if (tmp == 0 || tmp == 0xffff || (tmp & BMSR_MEDIA) == 0) continue; else return i; } return 0xff; } static inline void setup_pegasus_II(pegasus_t *pegasus) { __u8 data = 0xa5; set_register(pegasus, Reg1d, 0); set_register(pegasus, Reg7b, 1); mdelay(100); if ((pegasus->features & HAS_HOME_PNA) && mii_mode) set_register(pegasus, Reg7b, 0); else set_register(pegasus, Reg7b, 2); set_register(pegasus, 0x83, data); get_registers(pegasus, 0x83, 1, &data); if (data == 0xa5) pegasus->chip = 0x8513; else pegasus->chip = 0; set_register(pegasus, 0x80, 0xc0); set_register(pegasus, 0x83, 0xff); set_register(pegasus, 0x84, 0x01); if (pegasus->features & HAS_HOME_PNA && mii_mode) set_register(pegasus, Reg81, 6); else set_register(pegasus, Reg81, 2); } static int pegasus_count; static struct workqueue_struct *pegasus_workqueue; #define CARRIER_CHECK_DELAY (2 * HZ) static void check_carrier(struct work_struct *work) { pegasus_t *pegasus = container_of(work, pegasus_t, carrier_check.work); set_carrier(pegasus->net); if (!(pegasus->flags & PEGASUS_UNPLUG)) { queue_delayed_work(pegasus_workqueue, &pegasus->carrier_check, CARRIER_CHECK_DELAY); } } static int pegasus_blacklisted(struct usb_device *udev) { struct usb_device_descriptor *udd = &udev->descriptor; /* Special quirk to keep the driver from handling the Belkin Bluetooth * dongle which happens to have the same ID. */ if ((udd->idVendor == cpu_to_le16(VENDOR_BELKIN)) && (udd->idProduct == cpu_to_le16(0x0121)) && (udd->bDeviceClass == USB_CLASS_WIRELESS_CONTROLLER) && (udd->bDeviceProtocol == 1)) return 1; return 0; } /* we rely on probe() and remove() being serialized so we * don't need extra locking on pegasus_count. */ static void pegasus_dec_workqueue(void) { pegasus_count--; if (pegasus_count == 0) { destroy_workqueue(pegasus_workqueue); pegasus_workqueue = NULL; } } static int pegasus_probe(struct usb_interface *intf, const struct usb_device_id *id) { struct usb_device *dev = interface_to_usbdev(intf); struct net_device *net; pegasus_t *pegasus; int dev_index = id - pegasus_ids; int res = -ENOMEM; if (pegasus_blacklisted(dev)) return -ENODEV; if (pegasus_count == 0) { pegasus_workqueue = alloc_workqueue("pegasus", WQ_MEM_RECLAIM, 0); if (!pegasus_workqueue) return -ENOMEM; } pegasus_count++; net = alloc_etherdev(sizeof(struct pegasus)); if (!net) goto out; pegasus = netdev_priv(net); pegasus->dev_index = dev_index; res = alloc_urbs(pegasus); if (res < 0) { dev_err(&intf->dev, "can't allocate %s\n", "urbs"); goto out1; } tasklet_init(&pegasus->rx_tl, rx_fixup, (unsigned long) pegasus); INIT_DELAYED_WORK(&pegasus->carrier_check, check_carrier); pegasus->intf = intf; pegasus->usb = dev; pegasus->net = net; net->watchdog_timeo = PEGASUS_TX_TIMEOUT; net->netdev_ops = &pegasus_netdev_ops; net->ethtool_ops = &ops; pegasus->mii.dev = net; pegasus->mii.mdio_read = mdio_read; pegasus->mii.mdio_write = mdio_write; pegasus->mii.phy_id_mask = 0x1f; pegasus->mii.reg_num_mask = 0x1f; pegasus->msg_enable = netif_msg_init(msg_level, NETIF_MSG_DRV | NETIF_MSG_PROBE | NETIF_MSG_LINK); pegasus->features = usb_dev_id[dev_index].private; get_interrupt_interval(pegasus); if (reset_mac(pegasus)) { dev_err(&intf->dev, "can't reset MAC\n"); res = -EIO; goto out2; } set_ethernet_addr(pegasus); if (pegasus->features & PEGASUS_II) { dev_info(&intf->dev, "setup Pegasus II specific registers\n"); setup_pegasus_II(pegasus); } pegasus->phy = mii_phy_probe(pegasus); if (pegasus->phy == 0xff) { dev_warn(&intf->dev, "can't locate MII phy, using default\n"); pegasus->phy = 1; } pegasus->mii.phy_id = pegasus->phy; usb_set_intfdata(intf, pegasus); SET_NETDEV_DEV(net, &intf->dev); pegasus_reset_wol(net); res = register_netdev(net); if (res) goto out3; queue_delayed_work(pegasus_workqueue, &pegasus->carrier_check, CARRIER_CHECK_DELAY); dev_info(&intf->dev, "%s, %s, %pM\n", net->name, usb_dev_id[dev_index].name, net->dev_addr); return 0; out3: usb_set_intfdata(intf, NULL); out2: free_all_urbs(pegasus); out1: free_netdev(net); out: pegasus_dec_workqueue(); return res; } static void pegasus_disconnect(struct usb_interface *intf) { struct pegasus *pegasus = usb_get_intfdata(intf); usb_set_intfdata(intf, NULL); if (!pegasus) { dev_dbg(&intf->dev, "unregistering non-bound device?\n"); return; } pegasus->flags |= PEGASUS_UNPLUG; cancel_delayed_work(&pegasus->carrier_check); unregister_netdev(pegasus->net); unlink_all_urbs(pegasus); free_all_urbs(pegasus); if (pegasus->rx_skb != NULL) { dev_kfree_skb(pegasus->rx_skb); pegasus->rx_skb = NULL; } free_netdev(pegasus->net); pegasus_dec_workqueue(); } static int pegasus_suspend(struct usb_interface *intf, pm_message_t message) { struct pegasus *pegasus = usb_get_intfdata(intf); netif_device_detach(pegasus->net); cancel_delayed_work(&pegasus->carrier_check); if (netif_running(pegasus->net)) { usb_kill_urb(pegasus->rx_urb); usb_kill_urb(pegasus->intr_urb); } return 0; } static int pegasus_resume(struct usb_interface *intf) { struct pegasus *pegasus = usb_get_intfdata(intf); netif_device_attach(pegasus->net); if (netif_running(pegasus->net)) { pegasus->rx_urb->status = 0; pegasus->rx_urb->actual_length = 0; read_bulk_callback(pegasus->rx_urb); pegasus->intr_urb->status = 0; pegasus->intr_urb->actual_length = 0; intr_callback(pegasus->intr_urb); } queue_delayed_work(pegasus_workqueue, &pegasus->carrier_check, CARRIER_CHECK_DELAY); return 0; } static const struct net_device_ops pegasus_netdev_ops = { .ndo_open = pegasus_open, .ndo_stop = pegasus_close, .ndo_do_ioctl = pegasus_ioctl, .ndo_start_xmit = pegasus_start_xmit, .ndo_set_rx_mode = pegasus_set_multicast, .ndo_get_stats = pegasus_netdev_stats, .ndo_tx_timeout = pegasus_tx_timeout, .ndo_set_mac_address = eth_mac_addr, .ndo_validate_addr = eth_validate_addr, }; static struct usb_driver pegasus_driver = { .name = driver_name, .probe = pegasus_probe, .disconnect = pegasus_disconnect, .id_table = pegasus_ids, .suspend = pegasus_suspend, .resume = pegasus_resume, .disable_hub_initiated_lpm = 1, }; static void __init parse_id(char *id) { unsigned int vendor_id = 0, device_id = 0, flags = 0, i = 0; char *token, *name = NULL; if ((token = strsep(&id, ":")) != NULL) name = token; /* name now points to a null terminated string*/ if ((token = strsep(&id, ":")) != NULL) vendor_id = simple_strtoul(token, NULL, 16); if ((token = strsep(&id, ":")) != NULL) device_id = simple_strtoul(token, NULL, 16); flags = simple_strtoul(id, NULL, 16); pr_info("%s: new device %s, vendor ID 0x%04x, device ID 0x%04x, flags: 0x%x\n", driver_name, name, vendor_id, device_id, flags); if (vendor_id > 0x10000 || vendor_id == 0) return; if (device_id > 0x10000 || device_id == 0) return; for (i = 0; usb_dev_id[i].name; i++); usb_dev_id[i].name = name; usb_dev_id[i].vendor = vendor_id; usb_dev_id[i].device = device_id; usb_dev_id[i].private = flags; pegasus_ids[i].match_flags = USB_DEVICE_ID_MATCH_DEVICE; pegasus_ids[i].idVendor = vendor_id; pegasus_ids[i].idProduct = device_id; } static int __init pegasus_init(void) { pr_info("%s: %s, " DRIVER_DESC "\n", driver_name, DRIVER_VERSION); if (devid) parse_id(devid); return usb_register(&pegasus_driver); } static void __exit pegasus_exit(void) { usb_deregister(&pegasus_driver); } module_init(pegasus_init); module_exit(pegasus_exit);
./CrossVul/dataset_final_sorted/CWE-119/c/bad_3317_0
crossvul-cpp_data_good_4787_23
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % H H AAA L DDDD % % H H A A L D D % % HHHHH AAAAA L D D % % H H A A L D D % % H H A A LLLLL DDDD % % % % % % Create Identity Hald CLUT Image Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2015 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/colorspace.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/module.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/pixel-accessor.h" #include "magick/quantum-private.h" #include "magick/resource_.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/thread-private.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d H A L D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadHALDImage() creates a Hald color lookup table image 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 ReadHALDImage method is: % % Image *ReadHALDImage(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 *ReadHALDImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; MagickBooleanType status; size_t cube_size, level; ssize_t y; /* Create HALD color lookup table image. */ 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); level=0; if (*image_info->filename != '\0') level=StringToUnsignedLong(image_info->filename); if (level < 2) level=8; status=MagickTrue; cube_size=level*level; image->columns=(size_t) (level*cube_size); image->rows=(size_t) (level*cube_size); status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } for (y=0; y < (ssize_t) image->rows; y+=(ssize_t) level) { ssize_t blue, green, red; register PixelPacket *restrict q; if (status == MagickFalse) continue; q=QueueAuthenticPixels(image,0,y,image->columns,(size_t) level,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } blue=y/(ssize_t) level; for (green=0; green < (ssize_t) cube_size; green++) { for (red=0; red < (ssize_t) cube_size; red++) { SetPixelRed(q,ClampToQuantum((MagickRealType) (QuantumRange*red/(cube_size-1.0)))); SetPixelGreen(q,ClampToQuantum((MagickRealType) (QuantumRange*green/(cube_size-1.0)))); SetPixelBlue(q,ClampToQuantum((MagickRealType) (QuantumRange*blue/(cube_size-1.0)))); SetPixelOpacity(q,OpaqueOpacity); q++; } } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r H A L D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterHALDImage() adds attributes for the Hald color lookup table 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 RegisterHALDImage method is: % % size_t RegisterHALDImage(void) % */ ModuleExport size_t RegisterHALDImage(void) { MagickInfo *entry; entry=SetMagickInfo("HALD"); entry->decoder=(DecodeImageHandler *) ReadHALDImage; entry->adjoin=MagickFalse; entry->format_type=ImplicitFormatType; entry->raw=MagickTrue; entry->endian_support=MagickTrue; entry->description=ConstantString("Identity Hald color lookup table image"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r H A L D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterHALDImage() removes format registrations made by the % HALD module from the list of supported formats. % % The format of the UnregisterHALDImage method is: % % UnregisterHALDImage(void) % */ ModuleExport void UnregisterHALDImage(void) { (void) UnregisterMagickInfo("HALD"); }
./CrossVul/dataset_final_sorted/CWE-119/c/good_4787_23
crossvul-cpp_data_bad_5820_0
/* * JPEG 2000 image decoder * Copyright (c) 2007 Kamil Nowosad * Copyright (c) 2013 Nicolas Bertrand <nicoinattendu@gmail.com> * * 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 * JPEG 2000 image decoder */ #include "libavutil/avassert.h" #include "libavutil/common.h" #include "libavutil/opt.h" #include "libavutil/pixdesc.h" #include "avcodec.h" #include "bytestream.h" #include "internal.h" #include "thread.h" #include "jpeg2000.h" #define JP2_SIG_TYPE 0x6A502020 #define JP2_SIG_VALUE 0x0D0A870A #define JP2_CODESTREAM 0x6A703263 #define JP2_HEADER 0x6A703268 #define HAD_COC 0x01 #define HAD_QCC 0x02 typedef struct Jpeg2000TilePart { uint8_t tile_index; // Tile index who refers the tile-part const uint8_t *tp_end; GetByteContext tpg; // bit stream in tile-part } Jpeg2000TilePart; /* RMK: For JPEG2000 DCINEMA 3 tile-parts in a tile * one per component, so tile_part elements have a size of 3 */ typedef struct Jpeg2000Tile { Jpeg2000Component *comp; uint8_t properties[4]; Jpeg2000CodingStyle codsty[4]; Jpeg2000QuantStyle qntsty[4]; Jpeg2000TilePart tile_part[4]; uint16_t tp_idx; // Tile-part index } Jpeg2000Tile; typedef struct Jpeg2000DecoderContext { AVClass *class; AVCodecContext *avctx; GetByteContext g; int width, height; int image_offset_x, image_offset_y; int tile_offset_x, tile_offset_y; uint8_t cbps[4]; // bits per sample in particular components uint8_t sgnd[4]; // if a component is signed uint8_t properties[4]; int cdx[4], cdy[4]; int precision; int ncomponents; int colour_space; uint32_t palette[256]; int8_t pal8; int cdef[4]; int tile_width, tile_height; unsigned numXtiles, numYtiles; int maxtilelen; Jpeg2000CodingStyle codsty[4]; Jpeg2000QuantStyle qntsty[4]; int bit_index; int curtileno; Jpeg2000Tile *tile; /*options parameters*/ int reduction_factor; } Jpeg2000DecoderContext; /* get_bits functions for JPEG2000 packet bitstream * It is a get_bit function with a bit-stuffing routine. If the value of the * byte is 0xFF, the next byte includes an extra zero bit stuffed into the MSB. * cf. ISO-15444-1:2002 / B.10.1 Bit-stuffing routine */ static int get_bits(Jpeg2000DecoderContext *s, int n) { int res = 0; while (--n >= 0) { res <<= 1; if (s->bit_index == 0) { s->bit_index = 7 + (bytestream2_get_byte(&s->g) != 0xFFu); } s->bit_index--; res |= (bytestream2_peek_byte(&s->g) >> s->bit_index) & 1; } return res; } static void jpeg2000_flush(Jpeg2000DecoderContext *s) { if (bytestream2_get_byte(&s->g) == 0xff) bytestream2_skip(&s->g, 1); s->bit_index = 8; } /* decode the value stored in node */ static int tag_tree_decode(Jpeg2000DecoderContext *s, Jpeg2000TgtNode *node, int threshold) { Jpeg2000TgtNode *stack[30]; int sp = -1, curval = 0; if (!node) return AVERROR_INVALIDDATA; while (node && !node->vis) { stack[++sp] = node; node = node->parent; } if (node) curval = node->val; else curval = stack[sp]->val; while (curval < threshold && sp >= 0) { if (curval < stack[sp]->val) curval = stack[sp]->val; while (curval < threshold) { int ret; if ((ret = get_bits(s, 1)) > 0) { stack[sp]->vis++; break; } else if (!ret) curval++; else return ret; } stack[sp]->val = curval; sp--; } return curval; } static int pix_fmt_match(enum AVPixelFormat pix_fmt, int components, int bpc, uint32_t log2_chroma_wh, int pal8) { int match = 1; const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt); if (desc->nb_components != components) { return 0; } switch (components) { case 4: match = match && desc->comp[3].depth_minus1 + 1 >= bpc && (log2_chroma_wh >> 14 & 3) == 0 && (log2_chroma_wh >> 12 & 3) == 0; case 3: match = match && desc->comp[2].depth_minus1 + 1 >= bpc && (log2_chroma_wh >> 10 & 3) == desc->log2_chroma_w && (log2_chroma_wh >> 8 & 3) == desc->log2_chroma_h; case 2: match = match && desc->comp[1].depth_minus1 + 1 >= bpc && (log2_chroma_wh >> 6 & 3) == desc->log2_chroma_w && (log2_chroma_wh >> 4 & 3) == desc->log2_chroma_h; case 1: match = match && desc->comp[0].depth_minus1 + 1 >= bpc && (log2_chroma_wh >> 2 & 3) == 0 && (log2_chroma_wh & 3) == 0 && (desc->flags & AV_PIX_FMT_FLAG_PAL) == pal8 * AV_PIX_FMT_FLAG_PAL; } return match; } // pix_fmts with lower bpp have to be listed before // similar pix_fmts with higher bpp. #define RGB_PIXEL_FORMATS AV_PIX_FMT_PAL8,AV_PIX_FMT_RGB24,AV_PIX_FMT_RGBA,AV_PIX_FMT_RGB48,AV_PIX_FMT_RGBA64 #define GRAY_PIXEL_FORMATS AV_PIX_FMT_GRAY8,AV_PIX_FMT_GRAY8A,AV_PIX_FMT_GRAY16 #define YUV_PIXEL_FORMATS AV_PIX_FMT_YUV410P,AV_PIX_FMT_YUV411P,AV_PIX_FMT_YUVA420P, \ AV_PIX_FMT_YUV420P,AV_PIX_FMT_YUV422P,AV_PIX_FMT_YUVA422P, \ AV_PIX_FMT_YUV440P,AV_PIX_FMT_YUV444P,AV_PIX_FMT_YUVA444P, \ AV_PIX_FMT_YUV420P9,AV_PIX_FMT_YUV422P9,AV_PIX_FMT_YUV444P9, \ AV_PIX_FMT_YUVA420P9,AV_PIX_FMT_YUVA422P9,AV_PIX_FMT_YUVA444P9, \ AV_PIX_FMT_YUV420P10,AV_PIX_FMT_YUV422P10,AV_PIX_FMT_YUV444P10, \ AV_PIX_FMT_YUVA420P10,AV_PIX_FMT_YUVA422P10,AV_PIX_FMT_YUVA444P10, \ AV_PIX_FMT_YUV420P12,AV_PIX_FMT_YUV422P12,AV_PIX_FMT_YUV444P12, \ AV_PIX_FMT_YUV420P14,AV_PIX_FMT_YUV422P14,AV_PIX_FMT_YUV444P14, \ AV_PIX_FMT_YUV420P16,AV_PIX_FMT_YUV422P16,AV_PIX_FMT_YUV444P16, \ AV_PIX_FMT_YUVA420P16,AV_PIX_FMT_YUVA422P16,AV_PIX_FMT_YUVA444P16 #define XYZ_PIXEL_FORMATS AV_PIX_FMT_XYZ12 static const enum AVPixelFormat rgb_pix_fmts[] = {RGB_PIXEL_FORMATS}; static const enum AVPixelFormat gray_pix_fmts[] = {GRAY_PIXEL_FORMATS}; static const enum AVPixelFormat yuv_pix_fmts[] = {YUV_PIXEL_FORMATS}; static const enum AVPixelFormat xyz_pix_fmts[] = {XYZ_PIXEL_FORMATS}; static const enum AVPixelFormat all_pix_fmts[] = {RGB_PIXEL_FORMATS, GRAY_PIXEL_FORMATS, YUV_PIXEL_FORMATS, XYZ_PIXEL_FORMATS}; /* marker segments */ /* get sizes and offsets of image, tiles; number of components */ static int get_siz(Jpeg2000DecoderContext *s) { int i; int ncomponents; uint32_t log2_chroma_wh = 0; const enum AVPixelFormat *possible_fmts = NULL; int possible_fmts_nb = 0; if (bytestream2_get_bytes_left(&s->g) < 36) return AVERROR_INVALIDDATA; s->avctx->profile = bytestream2_get_be16u(&s->g); // Rsiz s->width = bytestream2_get_be32u(&s->g); // Width s->height = bytestream2_get_be32u(&s->g); // Height s->image_offset_x = bytestream2_get_be32u(&s->g); // X0Siz s->image_offset_y = bytestream2_get_be32u(&s->g); // Y0Siz s->tile_width = bytestream2_get_be32u(&s->g); // XTSiz s->tile_height = bytestream2_get_be32u(&s->g); // YTSiz s->tile_offset_x = bytestream2_get_be32u(&s->g); // XT0Siz s->tile_offset_y = bytestream2_get_be32u(&s->g); // YT0Siz ncomponents = bytestream2_get_be16u(&s->g); // CSiz if (ncomponents <= 0) { av_log(s->avctx, AV_LOG_ERROR, "Invalid number of components: %d\n", s->ncomponents); return AVERROR_INVALIDDATA; } if (ncomponents > 4) { avpriv_request_sample(s->avctx, "Support for %d components", s->ncomponents); return AVERROR_PATCHWELCOME; } s->ncomponents = ncomponents; if (s->tile_width <= 0 || s->tile_height <= 0) { av_log(s->avctx, AV_LOG_ERROR, "Invalid tile dimension %dx%d.\n", s->tile_width, s->tile_height); return AVERROR_INVALIDDATA; } if (bytestream2_get_bytes_left(&s->g) < 3 * s->ncomponents) return AVERROR_INVALIDDATA; for (i = 0; i < s->ncomponents; i++) { // Ssiz_i XRsiz_i, YRsiz_i uint8_t x = bytestream2_get_byteu(&s->g); s->cbps[i] = (x & 0x7f) + 1; s->precision = FFMAX(s->cbps[i], s->precision); s->sgnd[i] = !!(x & 0x80); s->cdx[i] = bytestream2_get_byteu(&s->g); s->cdy[i] = bytestream2_get_byteu(&s->g); if (!s->cdx[i] || !s->cdy[i]) { av_log(s->avctx, AV_LOG_ERROR, "Invalid sample seperation\n"); return AVERROR_INVALIDDATA; } log2_chroma_wh |= s->cdy[i] >> 1 << i * 4 | s->cdx[i] >> 1 << i * 4 + 2; } s->numXtiles = ff_jpeg2000_ceildiv(s->width - s->tile_offset_x, s->tile_width); s->numYtiles = ff_jpeg2000_ceildiv(s->height - s->tile_offset_y, s->tile_height); if (s->numXtiles * (uint64_t)s->numYtiles > INT_MAX/sizeof(*s->tile)) { s->numXtiles = s->numYtiles = 0; return AVERROR(EINVAL); } s->tile = av_mallocz_array(s->numXtiles * s->numYtiles, sizeof(*s->tile)); if (!s->tile) { s->numXtiles = s->numYtiles = 0; return AVERROR(ENOMEM); } for (i = 0; i < s->numXtiles * s->numYtiles; i++) { Jpeg2000Tile *tile = s->tile + i; tile->comp = av_mallocz(s->ncomponents * sizeof(*tile->comp)); if (!tile->comp) return AVERROR(ENOMEM); } /* compute image size with reduction factor */ s->avctx->width = ff_jpeg2000_ceildivpow2(s->width - s->image_offset_x, s->reduction_factor); s->avctx->height = ff_jpeg2000_ceildivpow2(s->height - s->image_offset_y, s->reduction_factor); if (s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_2K || s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_4K) { possible_fmts = xyz_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(xyz_pix_fmts); } else { switch (s->colour_space) { case 16: possible_fmts = rgb_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(rgb_pix_fmts); break; case 17: possible_fmts = gray_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(gray_pix_fmts); break; case 18: possible_fmts = yuv_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(yuv_pix_fmts); break; default: possible_fmts = all_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(all_pix_fmts); break; } } for (i = 0; i < possible_fmts_nb; ++i) { if (pix_fmt_match(possible_fmts[i], ncomponents, s->precision, log2_chroma_wh, s->pal8)) { s->avctx->pix_fmt = possible_fmts[i]; break; } } if (s->avctx->pix_fmt == AV_PIX_FMT_NONE) { av_log(s->avctx, AV_LOG_ERROR, "Unknown pix_fmt, profile: %d, colour_space: %d, " "components: %d, precision: %d, " "cdx[1]: %d, cdy[1]: %d, cdx[2]: %d, cdy[2]: %d\n", s->avctx->profile, s->colour_space, ncomponents, s->precision, ncomponents > 2 ? s->cdx[1] : 0, ncomponents > 2 ? s->cdy[1] : 0, ncomponents > 2 ? s->cdx[2] : 0, ncomponents > 2 ? s->cdy[2] : 0); } return 0; } /* get common part for COD and COC segments */ static int get_cox(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c) { uint8_t byte; if (bytestream2_get_bytes_left(&s->g) < 5) return AVERROR_INVALIDDATA; /* nreslevels = number of resolution levels = number of decomposition level +1 */ c->nreslevels = bytestream2_get_byteu(&s->g) + 1; if (c->nreslevels >= JPEG2000_MAX_RESLEVELS) { av_log(s->avctx, AV_LOG_ERROR, "nreslevels %d is invalid\n", c->nreslevels); return AVERROR_INVALIDDATA; } /* compute number of resolution levels to decode */ if (c->nreslevels < s->reduction_factor) c->nreslevels2decode = 1; else c->nreslevels2decode = c->nreslevels - s->reduction_factor; c->log2_cblk_width = (bytestream2_get_byteu(&s->g) & 15) + 2; // cblk width c->log2_cblk_height = (bytestream2_get_byteu(&s->g) & 15) + 2; // cblk height if (c->log2_cblk_width > 10 || c->log2_cblk_height > 10 || c->log2_cblk_width + c->log2_cblk_height > 12) { av_log(s->avctx, AV_LOG_ERROR, "cblk size invalid\n"); return AVERROR_INVALIDDATA; } c->cblk_style = bytestream2_get_byteu(&s->g); if (c->cblk_style != 0) { // cblk style av_log(s->avctx, AV_LOG_WARNING, "extra cblk styles %X\n", c->cblk_style); } c->transform = bytestream2_get_byteu(&s->g); // DWT transformation type /* set integer 9/7 DWT in case of BITEXACT flag */ if ((s->avctx->flags & CODEC_FLAG_BITEXACT) && (c->transform == FF_DWT97)) c->transform = FF_DWT97_INT; if (c->csty & JPEG2000_CSTY_PREC) { int i; for (i = 0; i < c->nreslevels; i++) { byte = bytestream2_get_byte(&s->g); c->log2_prec_widths[i] = byte & 0x0F; // precinct PPx c->log2_prec_heights[i] = (byte >> 4) & 0x0F; // precinct PPy } } else { memset(c->log2_prec_widths , 15, sizeof(c->log2_prec_widths )); memset(c->log2_prec_heights, 15, sizeof(c->log2_prec_heights)); } return 0; } /* get coding parameters for a particular tile or whole image*/ static int get_cod(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c, uint8_t *properties) { Jpeg2000CodingStyle tmp; int compno, ret; if (bytestream2_get_bytes_left(&s->g) < 5) return AVERROR_INVALIDDATA; tmp.csty = bytestream2_get_byteu(&s->g); // get progression order tmp.prog_order = bytestream2_get_byteu(&s->g); tmp.nlayers = bytestream2_get_be16u(&s->g); tmp.mct = bytestream2_get_byteu(&s->g); // multiple component transformation if (tmp.mct && s->ncomponents < 3) { av_log(s->avctx, AV_LOG_ERROR, "MCT %d with too few components (%d)\n", tmp.mct, s->ncomponents); return AVERROR_INVALIDDATA; } if ((ret = get_cox(s, &tmp)) < 0) return ret; for (compno = 0; compno < s->ncomponents; compno++) if (!(properties[compno] & HAD_COC)) memcpy(c + compno, &tmp, sizeof(tmp)); return 0; } /* Get coding parameters for a component in the whole image or a * particular tile. */ static int get_coc(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c, uint8_t *properties) { int compno, ret; if (bytestream2_get_bytes_left(&s->g) < 2) return AVERROR_INVALIDDATA; compno = bytestream2_get_byteu(&s->g); if (compno >= s->ncomponents) { av_log(s->avctx, AV_LOG_ERROR, "Invalid compno %d. There are %d components in the image.\n", compno, s->ncomponents); return AVERROR_INVALIDDATA; } c += compno; c->csty = bytestream2_get_byteu(&s->g); if ((ret = get_cox(s, c)) < 0) return ret; properties[compno] |= HAD_COC; return 0; } /* Get common part for QCD and QCC segments. */ static int get_qcx(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q) { int i, x; if (bytestream2_get_bytes_left(&s->g) < 1) return AVERROR_INVALIDDATA; x = bytestream2_get_byteu(&s->g); // Sqcd q->nguardbits = x >> 5; q->quantsty = x & 0x1f; if (q->quantsty == JPEG2000_QSTY_NONE) { n -= 3; if (bytestream2_get_bytes_left(&s->g) < n || n > JPEG2000_MAX_DECLEVELS*3) return AVERROR_INVALIDDATA; for (i = 0; i < n; i++) q->expn[i] = bytestream2_get_byteu(&s->g) >> 3; } else if (q->quantsty == JPEG2000_QSTY_SI) { if (bytestream2_get_bytes_left(&s->g) < 2) return AVERROR_INVALIDDATA; x = bytestream2_get_be16u(&s->g); q->expn[0] = x >> 11; q->mant[0] = x & 0x7ff; for (i = 1; i < JPEG2000_MAX_DECLEVELS * 3; i++) { int curexpn = FFMAX(0, q->expn[0] - (i - 1) / 3); q->expn[i] = curexpn; q->mant[i] = q->mant[0]; } } else { n = (n - 3) >> 1; if (bytestream2_get_bytes_left(&s->g) < 2 * n || n > JPEG2000_MAX_DECLEVELS*3) return AVERROR_INVALIDDATA; for (i = 0; i < n; i++) { x = bytestream2_get_be16u(&s->g); q->expn[i] = x >> 11; q->mant[i] = x & 0x7ff; } } return 0; } /* Get quantization parameters for a particular tile or a whole image. */ static int get_qcd(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q, uint8_t *properties) { Jpeg2000QuantStyle tmp; int compno, ret; if ((ret = get_qcx(s, n, &tmp)) < 0) return ret; for (compno = 0; compno < s->ncomponents; compno++) if (!(properties[compno] & HAD_QCC)) memcpy(q + compno, &tmp, sizeof(tmp)); return 0; } /* Get quantization parameters for a component in the whole image * on in a particular tile. */ static int get_qcc(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q, uint8_t *properties) { int compno; if (bytestream2_get_bytes_left(&s->g) < 1) return AVERROR_INVALIDDATA; compno = bytestream2_get_byteu(&s->g); if (compno >= s->ncomponents) { av_log(s->avctx, AV_LOG_ERROR, "Invalid compno %d. There are %d components in the image.\n", compno, s->ncomponents); return AVERROR_INVALIDDATA; } properties[compno] |= HAD_QCC; return get_qcx(s, n - 1, q + compno); } /* Get start of tile segment. */ static int get_sot(Jpeg2000DecoderContext *s, int n) { Jpeg2000TilePart *tp; uint16_t Isot; uint32_t Psot; uint8_t TPsot; if (bytestream2_get_bytes_left(&s->g) < 8) return AVERROR_INVALIDDATA; s->curtileno = 0; Isot = bytestream2_get_be16u(&s->g); // Isot if (Isot >= s->numXtiles * s->numYtiles) return AVERROR_INVALIDDATA; s->curtileno = Isot; Psot = bytestream2_get_be32u(&s->g); // Psot TPsot = bytestream2_get_byteu(&s->g); // TPsot /* Read TNSot but not used */ bytestream2_get_byteu(&s->g); // TNsot if (Psot > bytestream2_get_bytes_left(&s->g) + n + 2) { av_log(s->avctx, AV_LOG_ERROR, "Psot %d too big\n", Psot); return AVERROR_INVALIDDATA; } if (TPsot >= FF_ARRAY_ELEMS(s->tile[Isot].tile_part)) { avpriv_request_sample(s->avctx, "Support for %d components", TPsot); return AVERROR_PATCHWELCOME; } s->tile[Isot].tp_idx = TPsot; tp = s->tile[Isot].tile_part + TPsot; tp->tile_index = Isot; tp->tp_end = s->g.buffer + Psot - n - 2; if (!TPsot) { Jpeg2000Tile *tile = s->tile + s->curtileno; /* copy defaults */ memcpy(tile->codsty, s->codsty, s->ncomponents * sizeof(Jpeg2000CodingStyle)); memcpy(tile->qntsty, s->qntsty, s->ncomponents * sizeof(Jpeg2000QuantStyle)); } return 0; } /* Tile-part lengths: see ISO 15444-1:2002, section A.7.1 * Used to know the number of tile parts and lengths. * There may be multiple TLMs in the header. * TODO: The function is not used for tile-parts management, nor anywhere else. * It can be useful to allocate memory for tile parts, before managing the SOT * markers. Parsing the TLM header is needed to increment the input header * buffer. * This marker is mandatory for DCI. */ static uint8_t get_tlm(Jpeg2000DecoderContext *s, int n) { uint8_t Stlm, ST, SP, tile_tlm, i; bytestream2_get_byte(&s->g); /* Ztlm: skipped */ Stlm = bytestream2_get_byte(&s->g); // too complex ? ST = ((Stlm >> 4) & 0x01) + ((Stlm >> 4) & 0x02); ST = (Stlm >> 4) & 0x03; // TODO: Manage case of ST = 0b11 --> raise error SP = (Stlm >> 6) & 0x01; tile_tlm = (n - 4) / ((SP + 1) * 2 + ST); for (i = 0; i < tile_tlm; i++) { switch (ST) { case 0: break; case 1: bytestream2_get_byte(&s->g); break; case 2: bytestream2_get_be16(&s->g); break; case 3: bytestream2_get_be32(&s->g); break; } if (SP == 0) { bytestream2_get_be16(&s->g); } else { bytestream2_get_be32(&s->g); } } return 0; } static int init_tile(Jpeg2000DecoderContext *s, int tileno) { int compno; int tilex = tileno % s->numXtiles; int tiley = tileno / s->numXtiles; Jpeg2000Tile *tile = s->tile + tileno; if (!tile->comp) return AVERROR(ENOMEM); for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000Component *comp = tile->comp + compno; Jpeg2000CodingStyle *codsty = tile->codsty + compno; Jpeg2000QuantStyle *qntsty = tile->qntsty + compno; int ret; // global bandno comp->coord_o[0][0] = FFMAX(tilex * s->tile_width + s->tile_offset_x, s->image_offset_x); comp->coord_o[0][1] = FFMIN((tilex + 1) * s->tile_width + s->tile_offset_x, s->width); comp->coord_o[1][0] = FFMAX(tiley * s->tile_height + s->tile_offset_y, s->image_offset_y); comp->coord_o[1][1] = FFMIN((tiley + 1) * s->tile_height + s->tile_offset_y, s->height); comp->coord[0][0] = ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], s->reduction_factor); comp->coord[0][1] = ff_jpeg2000_ceildivpow2(comp->coord_o[0][1], s->reduction_factor); comp->coord[1][0] = ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], s->reduction_factor); comp->coord[1][1] = ff_jpeg2000_ceildivpow2(comp->coord_o[1][1], s->reduction_factor); if (ret = ff_jpeg2000_init_component(comp, codsty, qntsty, s->cbps[compno], s->cdx[compno], s->cdy[compno], s->avctx)) return ret; } return 0; } /* Read the number of coding passes. */ static int getnpasses(Jpeg2000DecoderContext *s) { int num; if (!get_bits(s, 1)) return 1; if (!get_bits(s, 1)) return 2; if ((num = get_bits(s, 2)) != 3) return num < 0 ? num : 3 + num; if ((num = get_bits(s, 5)) != 31) return num < 0 ? num : 6 + num; num = get_bits(s, 7); return num < 0 ? num : 37 + num; } static int getlblockinc(Jpeg2000DecoderContext *s) { int res = 0, ret; while (ret = get_bits(s, 1)) { if (ret < 0) return ret; res++; } return res; } static int jpeg2000_decode_packet(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *codsty, Jpeg2000ResLevel *rlevel, int precno, int layno, uint8_t *expn, int numgbits) { int bandno, cblkno, ret, nb_code_blocks; if (!(ret = get_bits(s, 1))) { jpeg2000_flush(s); return 0; } else if (ret < 0) return ret; for (bandno = 0; bandno < rlevel->nbands; bandno++) { Jpeg2000Band *band = rlevel->band + bandno; Jpeg2000Prec *prec = band->prec + precno; if (band->coord[0][0] == band->coord[0][1] || band->coord[1][0] == band->coord[1][1]) continue; nb_code_blocks = prec->nb_codeblocks_height * prec->nb_codeblocks_width; for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) { Jpeg2000Cblk *cblk = prec->cblk + cblkno; int incl, newpasses, llen; if (cblk->npasses) incl = get_bits(s, 1); else incl = tag_tree_decode(s, prec->cblkincl + cblkno, layno + 1) == layno; if (!incl) continue; else if (incl < 0) return incl; if (!cblk->npasses) { int v = expn[bandno] + numgbits - 1 - tag_tree_decode(s, prec->zerobits + cblkno, 100); if (v < 0) { av_log(s->avctx, AV_LOG_ERROR, "nonzerobits %d invalid\n", v); return AVERROR_INVALIDDATA; } cblk->nonzerobits = v; } if ((newpasses = getnpasses(s)) < 0) return newpasses; if ((llen = getlblockinc(s)) < 0) return llen; cblk->lblock += llen; if ((ret = get_bits(s, av_log2(newpasses) + cblk->lblock)) < 0) return ret; if (ret > sizeof(cblk->data)) { avpriv_request_sample(s->avctx, "Block with lengthinc greater than %zu", sizeof(cblk->data)); return AVERROR_PATCHWELCOME; } cblk->lengthinc = ret; cblk->npasses += newpasses; } } jpeg2000_flush(s); if (codsty->csty & JPEG2000_CSTY_EPH) { if (bytestream2_peek_be16(&s->g) == JPEG2000_EPH) bytestream2_skip(&s->g, 2); else av_log(s->avctx, AV_LOG_ERROR, "EPH marker not found.\n"); } for (bandno = 0; bandno < rlevel->nbands; bandno++) { Jpeg2000Band *band = rlevel->band + bandno; Jpeg2000Prec *prec = band->prec + precno; nb_code_blocks = prec->nb_codeblocks_height * prec->nb_codeblocks_width; for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) { Jpeg2000Cblk *cblk = prec->cblk + cblkno; if ( bytestream2_get_bytes_left(&s->g) < cblk->lengthinc || sizeof(cblk->data) < cblk->length + cblk->lengthinc + 2 ) return AVERROR_INVALIDDATA; bytestream2_get_bufferu(&s->g, cblk->data + cblk->length, cblk->lengthinc); cblk->length += cblk->lengthinc; cblk->lengthinc = 0; } } return 0; } static int jpeg2000_decode_packets(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile) { int ret = 0; int layno, reslevelno, compno, precno, ok_reslevel; int x, y; s->bit_index = 8; switch (tile->codsty[0].prog_order) { case JPEG2000_PGOD_RLCP: avpriv_request_sample(s->avctx, "Progression order RLCP"); case JPEG2000_PGOD_LRCP: for (layno = 0; layno < tile->codsty[0].nlayers; layno++) { ok_reslevel = 1; for (reslevelno = 0; ok_reslevel; reslevelno++) { ok_reslevel = 0; for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000CodingStyle *codsty = tile->codsty + compno; Jpeg2000QuantStyle *qntsty = tile->qntsty + compno; if (reslevelno < codsty->nreslevels) { Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel + reslevelno; ok_reslevel = 1; for (precno = 0; precno < rlevel->num_precincts_x * rlevel->num_precincts_y; precno++) if ((ret = jpeg2000_decode_packet(s, codsty, rlevel, precno, layno, qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0), qntsty->nguardbits)) < 0) return ret; } } } } break; case JPEG2000_PGOD_CPRL: for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000CodingStyle *codsty = tile->codsty + compno; Jpeg2000QuantStyle *qntsty = tile->qntsty + compno; /* Set bit stream buffer address according to tile-part. * For DCinema one tile-part per component, so can be * indexed by component. */ s->g = tile->tile_part[compno].tpg; /* Position loop (y axis) * TODO: Automate computing of step 256. * Fixed here, but to be computed before entering here. */ for (y = 0; y < s->height; y += 256) { /* Position loop (y axis) * TODO: automate computing of step 256. * Fixed here, but to be computed before entering here. */ for (x = 0; x < s->width; x += 256) { for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) { uint16_t prcx, prcy; uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; // ==> N_L - r Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel + reslevelno; if (!((y % (1 << (rlevel->log2_prec_height + reducedresno)) == 0) || (y == 0))) // TODO: 2nd condition simplified as try0 always =0 for dcinema continue; if (!((x % (1 << (rlevel->log2_prec_width + reducedresno)) == 0) || (x == 0))) // TODO: 2nd condition simplified as try0 always =0 for dcinema continue; // check if a precinct exists prcx = ff_jpeg2000_ceildivpow2(x, reducedresno) >> rlevel->log2_prec_width; prcy = ff_jpeg2000_ceildivpow2(y, reducedresno) >> rlevel->log2_prec_height; precno = prcx + rlevel->num_precincts_x * prcy; for (layno = 0; layno < tile->codsty[0].nlayers; layno++) { if ((ret = jpeg2000_decode_packet(s, codsty, rlevel, precno, layno, qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0), qntsty->nguardbits)) < 0) return ret; } } } } } break; case JPEG2000_PGOD_RPCL: avpriv_request_sample(s->avctx, "Progression order RPCL"); ret = AVERROR_PATCHWELCOME; break; case JPEG2000_PGOD_PCRL: avpriv_request_sample(s->avctx, "Progression order PCRL"); ret = AVERROR_PATCHWELCOME; break; default: break; } /* EOC marker reached */ bytestream2_skip(&s->g, 2); return ret; } /* TIER-1 routines */ static void decode_sigpass(Jpeg2000T1Context *t1, int width, int height, int bpno, int bandno, int bpass_csty_symbol, int vert_causal_ctx_csty_symbol) { int mask = 3 << (bpno - 1), y0, x, y; for (y0 = 0; y0 < height; y0 += 4) for (x = 0; x < width; x++) for (y = y0; y < height && y < y0 + 4; y++) { if ((t1->flags[y+1][x+1] & JPEG2000_T1_SIG_NB) && !(t1->flags[y+1][x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))) { int flags_mask = -1; if (vert_causal_ctx_csty_symbol && y == y0 + 3) flags_mask &= ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | JPEG2000_T1_SIG_SE); if (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ff_jpeg2000_getsigctxno(t1->flags[y+1][x+1] & flags_mask, bandno))) { int xorbit, ctxno = ff_jpeg2000_getsgnctxno(t1->flags[y+1][x+1], &xorbit); if (bpass_csty_symbol) t1->data[y][x] = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ? -mask : mask; else t1->data[y][x] = (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ^ xorbit) ? -mask : mask; ff_jpeg2000_set_significance(t1, x, y, t1->data[y][x] < 0); } t1->flags[y + 1][x + 1] |= JPEG2000_T1_VIS; } } } static void decode_refpass(Jpeg2000T1Context *t1, int width, int height, int bpno) { int phalf, nhalf; int y0, x, y; phalf = 1 << (bpno - 1); nhalf = -phalf; for (y0 = 0; y0 < height; y0 += 4) for (x = 0; x < width; x++) for (y = y0; y < height && y < y0 + 4; y++) if ((t1->flags[y + 1][x + 1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS)) == JPEG2000_T1_SIG) { int ctxno = ff_jpeg2000_getrefctxno(t1->flags[y + 1][x + 1]); int r = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ? phalf : nhalf; t1->data[y][x] += t1->data[y][x] < 0 ? -r : r; t1->flags[y + 1][x + 1] |= JPEG2000_T1_REF; } } static void decode_clnpass(Jpeg2000DecoderContext *s, Jpeg2000T1Context *t1, int width, int height, int bpno, int bandno, int seg_symbols, int vert_causal_ctx_csty_symbol) { int mask = 3 << (bpno - 1), y0, x, y, runlen, dec; for (y0 = 0; y0 < height; y0 += 4) { for (x = 0; x < width; x++) { if (y0 + 3 < height && !((t1->flags[y0 + 1][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) || (t1->flags[y0 + 2][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) || (t1->flags[y0 + 3][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) || (t1->flags[y0 + 4][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)))) { if (!ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_RL)) continue; runlen = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI); runlen = (runlen << 1) | ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI); dec = 1; } else { runlen = 0; dec = 0; } for (y = y0 + runlen; y < y0 + 4 && y < height; y++) { if (!dec) { if (!(t1->flags[y+1][x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))) { int flags_mask = -1; if (vert_causal_ctx_csty_symbol && y == y0 + 3) flags_mask &= ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | JPEG2000_T1_SIG_SE); dec = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ff_jpeg2000_getsigctxno(t1->flags[y+1][x+1] & flags_mask, bandno)); } } if (dec) { int xorbit; int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[y + 1][x + 1], &xorbit); t1->data[y][x] = (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ^ xorbit) ? -mask : mask; ff_jpeg2000_set_significance(t1, x, y, t1->data[y][x] < 0); } dec = 0; t1->flags[y + 1][x + 1] &= ~JPEG2000_T1_VIS; } } } if (seg_symbols) { int val; val = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI); val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI); val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI); val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI); if (val != 0xa) av_log(s->avctx, AV_LOG_ERROR, "Segmentation symbol value incorrect\n"); } } static int decode_cblk(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *codsty, Jpeg2000T1Context *t1, Jpeg2000Cblk *cblk, int width, int height, int bandpos) { int passno = cblk->npasses, pass_t = 2, bpno = cblk->nonzerobits - 1, y; int clnpass_cnt = 0; int bpass_csty_symbol = codsty->cblk_style & JPEG2000_CBLK_BYPASS; int vert_causal_ctx_csty_symbol = codsty->cblk_style & JPEG2000_CBLK_VSC; for (y = 0; y < height; y++) memset(t1->data[y], 0, width * sizeof(**t1->data)); /* If code-block contains no compressed data: nothing to do. */ if (!cblk->length) return 0; for (y = 0; y < height + 2; y++) memset(t1->flags[y], 0, (width + 2) * sizeof(**t1->flags)); cblk->data[cblk->length] = 0xff; cblk->data[cblk->length+1] = 0xff; ff_mqc_initdec(&t1->mqc, cblk->data); while (passno--) { switch(pass_t) { case 0: decode_sigpass(t1, width, height, bpno + 1, bandpos, bpass_csty_symbol && (clnpass_cnt >= 4), vert_causal_ctx_csty_symbol); break; case 1: decode_refpass(t1, width, height, bpno + 1); if (bpass_csty_symbol && clnpass_cnt >= 4) ff_mqc_initdec(&t1->mqc, cblk->data); break; case 2: decode_clnpass(s, t1, width, height, bpno + 1, bandpos, codsty->cblk_style & JPEG2000_CBLK_SEGSYM, vert_causal_ctx_csty_symbol); clnpass_cnt = clnpass_cnt + 1; if (bpass_csty_symbol && clnpass_cnt >= 4) ff_mqc_initdec(&t1->mqc, cblk->data); break; } pass_t++; if (pass_t == 3) { bpno--; pass_t = 0; } } return 0; } /* TODO: Verify dequantization for lossless case * comp->data can be float or int * band->stepsize can be float or int * depending on the type of DWT transformation. * see ISO/IEC 15444-1:2002 A.6.1 */ /* Float dequantization of a codeblock.*/ static void dequantization_float(int x, int y, Jpeg2000Cblk *cblk, Jpeg2000Component *comp, Jpeg2000T1Context *t1, Jpeg2000Band *band) { int i, j; int w = cblk->coord[0][1] - cblk->coord[0][0]; for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j) { float *datap = &comp->f_data[(comp->coord[0][1] - comp->coord[0][0]) * (y + j) + x]; int *src = t1->data[j]; for (i = 0; i < w; ++i) datap[i] = src[i] * band->f_stepsize; } } /* Integer dequantization of a codeblock.*/ static void dequantization_int(int x, int y, Jpeg2000Cblk *cblk, Jpeg2000Component *comp, Jpeg2000T1Context *t1, Jpeg2000Band *band) { int i, j; int w = cblk->coord[0][1] - cblk->coord[0][0]; for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j) { int32_t *datap = &comp->i_data[(comp->coord[0][1] - comp->coord[0][0]) * (y + j) + x]; int *src = t1->data[j]; for (i = 0; i < w; ++i) datap[i] = (src[i] * band->i_stepsize + (1 << 14)) >> 15; } } /* Inverse ICT parameters in float and integer. * int value = (float value) * (1<<16) */ static const float f_ict_params[4] = { 1.402f, 0.34413f, 0.71414f, 1.772f }; static const int i_ict_params[4] = { 91881, 22553, 46802, 116130 }; static void mct_decode(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile) { int i, csize = 1; int32_t *src[3], i0, i1, i2; float *srcf[3], i0f, i1f, i2f; for (i = 0; i < 3; i++) if (tile->codsty[0].transform == FF_DWT97) srcf[i] = tile->comp[i].f_data; else src [i] = tile->comp[i].i_data; for (i = 0; i < 2; i++) csize *= tile->comp[0].coord[i][1] - tile->comp[0].coord[i][0]; switch (tile->codsty[0].transform) { case FF_DWT97: for (i = 0; i < csize; i++) { i0f = *srcf[0] + (f_ict_params[0] * *srcf[2]); i1f = *srcf[0] - (f_ict_params[1] * *srcf[1]) - (f_ict_params[2] * *srcf[2]); i2f = *srcf[0] + (f_ict_params[3] * *srcf[1]); *srcf[0]++ = i0f; *srcf[1]++ = i1f; *srcf[2]++ = i2f; } break; case FF_DWT97_INT: for (i = 0; i < csize; i++) { i0 = *src[0] + (((i_ict_params[0] * *src[2]) + (1 << 15)) >> 16); i1 = *src[0] - (((i_ict_params[1] * *src[1]) + (1 << 15)) >> 16) - (((i_ict_params[2] * *src[2]) + (1 << 15)) >> 16); i2 = *src[0] + (((i_ict_params[3] * *src[1]) + (1 << 15)) >> 16); *src[0]++ = i0; *src[1]++ = i1; *src[2]++ = i2; } break; case FF_DWT53: for (i = 0; i < csize; i++) { i1 = *src[0] - (*src[2] + *src[1] >> 2); i0 = i1 + *src[2]; i2 = i1 + *src[1]; *src[0]++ = i0; *src[1]++ = i1; *src[2]++ = i2; } break; } } static int jpeg2000_decode_tile(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile, AVFrame *picture) { int compno, reslevelno, bandno; int x, y; uint8_t *line; Jpeg2000T1Context t1; /* Loop on tile components */ for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000Component *comp = tile->comp + compno; Jpeg2000CodingStyle *codsty = tile->codsty + compno; /* Loop on resolution levels */ for (reslevelno = 0; reslevelno < codsty->nreslevels2decode; reslevelno++) { Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno; /* Loop on bands */ for (bandno = 0; bandno < rlevel->nbands; bandno++) { int nb_precincts, precno; Jpeg2000Band *band = rlevel->band + bandno; int cblkno = 0, bandpos; bandpos = bandno + (reslevelno > 0); if (band->coord[0][0] == band->coord[0][1] || band->coord[1][0] == band->coord[1][1]) continue; nb_precincts = rlevel->num_precincts_x * rlevel->num_precincts_y; /* Loop on precincts */ for (precno = 0; precno < nb_precincts; precno++) { Jpeg2000Prec *prec = band->prec + precno; /* Loop on codeblocks */ for (cblkno = 0; cblkno < prec->nb_codeblocks_width * prec->nb_codeblocks_height; cblkno++) { int x, y; Jpeg2000Cblk *cblk = prec->cblk + cblkno; decode_cblk(s, codsty, &t1, cblk, cblk->coord[0][1] - cblk->coord[0][0], cblk->coord[1][1] - cblk->coord[1][0], bandpos); x = cblk->coord[0][0]; y = cblk->coord[1][0]; if (codsty->transform == FF_DWT97) dequantization_float(x, y, cblk, comp, &t1, band); else dequantization_int(x, y, cblk, comp, &t1, band); } /* end cblk */ } /*end prec */ } /* end band */ } /* end reslevel */ /* inverse DWT */ ff_dwt_decode(&comp->dwt, codsty->transform == FF_DWT97 ? (void*)comp->f_data : (void*)comp->i_data); } /*end comp */ /* inverse MCT transformation */ if (tile->codsty[0].mct) mct_decode(s, tile); if (s->cdef[0] < 0) { for (x = 0; x < s->ncomponents; x++) s->cdef[x] = x + 1; if ((s->ncomponents & 1) == 0) s->cdef[s->ncomponents-1] = 0; } if (s->precision <= 8) { for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000Component *comp = tile->comp + compno; Jpeg2000CodingStyle *codsty = tile->codsty + compno; float *datap = comp->f_data; int32_t *i_datap = comp->i_data; int cbps = s->cbps[compno]; int w = tile->comp[compno].coord[0][1] - s->image_offset_x; int planar = !!picture->data[2]; int pixelsize = planar ? 1 : s->ncomponents; int plane = 0; if (planar) plane = s->cdef[compno] ? s->cdef[compno]-1 : (s->ncomponents-1); y = tile->comp[compno].coord[1][0] - s->image_offset_y; line = picture->data[plane] + y * picture->linesize[plane]; for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) { uint8_t *dst; x = tile->comp[compno].coord[0][0] - s->image_offset_x; dst = line + x * pixelsize + compno*!planar; if (codsty->transform == FF_DWT97) { for (; x < w; x += s->cdx[compno]) { int val = lrintf(*datap) + (1 << (cbps - 1)); /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */ val = av_clip(val, 0, (1 << cbps) - 1); *dst = val << (8 - cbps); datap++; dst += pixelsize; } } else { for (; x < w; x += s->cdx[compno]) { int val = *i_datap + (1 << (cbps - 1)); /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */ val = av_clip(val, 0, (1 << cbps) - 1); *dst = val << (8 - cbps); i_datap++; dst += pixelsize; } } line += picture->linesize[plane]; } } } else { for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000Component *comp = tile->comp + compno; Jpeg2000CodingStyle *codsty = tile->codsty + compno; float *datap = comp->f_data; int32_t *i_datap = comp->i_data; uint16_t *linel; int cbps = s->cbps[compno]; int w = tile->comp[compno].coord[0][1] - s->image_offset_x; int planar = !!picture->data[2]; int pixelsize = planar ? 1 : s->ncomponents; int plane = 0; if (planar) plane = s->cdef[compno] ? s->cdef[compno]-1 : (s->ncomponents-1); y = tile->comp[compno].coord[1][0] - s->image_offset_y; linel = (uint16_t *)picture->data[plane] + y * (picture->linesize[plane] >> 1); for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) { uint16_t *dst; x = tile->comp[compno].coord[0][0] - s->image_offset_x; dst = linel + (x * pixelsize + compno*!planar); if (codsty->transform == FF_DWT97) { for (; x < w; x += s-> cdx[compno]) { int val = lrintf(*datap) + (1 << (cbps - 1)); /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */ val = av_clip(val, 0, (1 << cbps) - 1); /* align 12 bit values in little-endian mode */ *dst = val << (16 - cbps); datap++; dst += pixelsize; } } else { for (; x < w; x += s-> cdx[compno]) { int val = *i_datap + (1 << (cbps - 1)); /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */ val = av_clip(val, 0, (1 << cbps) - 1); /* align 12 bit values in little-endian mode */ *dst = val << (16 - cbps); i_datap++; dst += pixelsize; } } linel += picture->linesize[plane] >> 1; } } } return 0; } static void jpeg2000_dec_cleanup(Jpeg2000DecoderContext *s) { int tileno, compno; for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) { if (s->tile[tileno].comp) { for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000Component *comp = s->tile[tileno].comp + compno; Jpeg2000CodingStyle *codsty = s->tile[tileno].codsty + compno; ff_jpeg2000_cleanup(comp, codsty); } av_freep(&s->tile[tileno].comp); } } av_freep(&s->tile); s->numXtiles = s->numYtiles = 0; } static int jpeg2000_read_main_headers(Jpeg2000DecoderContext *s) { Jpeg2000CodingStyle *codsty = s->codsty; Jpeg2000QuantStyle *qntsty = s->qntsty; uint8_t *properties = s->properties; for (;;) { int len, ret = 0; uint16_t marker; int oldpos; if (bytestream2_get_bytes_left(&s->g) < 2) { av_log(s->avctx, AV_LOG_ERROR, "Missing EOC\n"); break; } marker = bytestream2_get_be16u(&s->g); oldpos = bytestream2_tell(&s->g); if (marker == JPEG2000_SOD) { Jpeg2000Tile *tile; Jpeg2000TilePart *tp; if (s->curtileno < 0) { av_log(s->avctx, AV_LOG_ERROR, "Missing SOT\n"); return AVERROR_INVALIDDATA; } tile = s->tile + s->curtileno; tp = tile->tile_part + tile->tp_idx; if (tp->tp_end < s->g.buffer) { av_log(s->avctx, AV_LOG_ERROR, "Invalid tpend\n"); return AVERROR_INVALIDDATA; } bytestream2_init(&tp->tpg, s->g.buffer, tp->tp_end - s->g.buffer); bytestream2_skip(&s->g, tp->tp_end - s->g.buffer); continue; } if (marker == JPEG2000_EOC) break; len = bytestream2_get_be16(&s->g); if (len < 2 || bytestream2_get_bytes_left(&s->g) < len - 2) return AVERROR_INVALIDDATA; switch (marker) { case JPEG2000_SIZ: ret = get_siz(s); if (!s->tile) s->numXtiles = s->numYtiles = 0; break; case JPEG2000_COC: ret = get_coc(s, codsty, properties); break; case JPEG2000_COD: ret = get_cod(s, codsty, properties); break; case JPEG2000_QCC: ret = get_qcc(s, len, qntsty, properties); break; case JPEG2000_QCD: ret = get_qcd(s, len, qntsty, properties); break; case JPEG2000_SOT: if (!(ret = get_sot(s, len))) { av_assert1(s->curtileno >= 0); codsty = s->tile[s->curtileno].codsty; qntsty = s->tile[s->curtileno].qntsty; properties = s->tile[s->curtileno].properties; } break; case JPEG2000_COM: // the comment is ignored bytestream2_skip(&s->g, len - 2); break; case JPEG2000_TLM: // Tile-part lengths ret = get_tlm(s, len); break; default: av_log(s->avctx, AV_LOG_ERROR, "unsupported marker 0x%.4X at pos 0x%X\n", marker, bytestream2_tell(&s->g) - 4); bytestream2_skip(&s->g, len - 2); break; } if (bytestream2_tell(&s->g) - oldpos != len || ret) { av_log(s->avctx, AV_LOG_ERROR, "error during processing marker segment %.4x\n", marker); return ret ? ret : -1; } } return 0; } /* Read bit stream packets --> T2 operation. */ static int jpeg2000_read_bitstream_packets(Jpeg2000DecoderContext *s) { int ret = 0; int tileno; for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) { Jpeg2000Tile *tile = s->tile + tileno; if (ret = init_tile(s, tileno)) return ret; s->g = tile->tile_part[0].tpg; if (ret = jpeg2000_decode_packets(s, tile)) return ret; } return 0; } static int jp2_find_codestream(Jpeg2000DecoderContext *s) { uint32_t atom_size, atom, atom_end; int search_range = 10; while (search_range && bytestream2_get_bytes_left(&s->g) >= 8) { atom_size = bytestream2_get_be32u(&s->g); atom = bytestream2_get_be32u(&s->g); atom_end = bytestream2_tell(&s->g) + atom_size - 8; if (atom == JP2_CODESTREAM) return 1; if (bytestream2_get_bytes_left(&s->g) < atom_size || atom_end < atom_size) return 0; if (atom == JP2_HEADER && atom_size >= 16) { uint32_t atom2_size, atom2, atom2_end; do { atom2_size = bytestream2_get_be32u(&s->g); atom2 = bytestream2_get_be32u(&s->g); atom2_end = bytestream2_tell(&s->g) + atom2_size - 8; if (atom2_size < 8 || atom2_end > atom_end || atom2_end < atom2_size) break; if (atom2 == JP2_CODESTREAM) { return 1; } else if (atom2 == MKBETAG('c','o','l','r') && atom2_size >= 7) { int method = bytestream2_get_byteu(&s->g); bytestream2_skipu(&s->g, 2); if (method == 1) { s->colour_space = bytestream2_get_be32u(&s->g); } } else if (atom2 == MKBETAG('p','c','l','r') && atom2_size >= 6) { int i, size, colour_count, colour_channels, colour_depth[3]; uint32_t r, g, b; colour_count = bytestream2_get_be16u(&s->g); colour_channels = bytestream2_get_byteu(&s->g); // FIXME: Do not ignore channel_sign colour_depth[0] = (bytestream2_get_byteu(&s->g) & 0x7f) + 1; colour_depth[1] = (bytestream2_get_byteu(&s->g) & 0x7f) + 1; colour_depth[2] = (bytestream2_get_byteu(&s->g) & 0x7f) + 1; size = (colour_depth[0] + 7 >> 3) * colour_count + (colour_depth[1] + 7 >> 3) * colour_count + (colour_depth[2] + 7 >> 3) * colour_count; if (colour_count > 256 || colour_channels != 3 || colour_depth[0] > 16 || colour_depth[1] > 16 || colour_depth[2] > 16 || atom2_size < size) { avpriv_request_sample(s->avctx, "Unknown palette"); bytestream2_seek(&s->g, atom2_end, SEEK_SET); continue; } s->pal8 = 1; for (i = 0; i < colour_count; i++) { if (colour_depth[0] <= 8) { r = bytestream2_get_byteu(&s->g) << 8 - colour_depth[0]; r |= r >> colour_depth[0]; } else { r = bytestream2_get_be16u(&s->g) >> colour_depth[0] - 8; } if (colour_depth[1] <= 8) { g = bytestream2_get_byteu(&s->g) << 8 - colour_depth[1]; r |= r >> colour_depth[1]; } else { g = bytestream2_get_be16u(&s->g) >> colour_depth[1] - 8; } if (colour_depth[2] <= 8) { b = bytestream2_get_byteu(&s->g) << 8 - colour_depth[2]; r |= r >> colour_depth[2]; } else { b = bytestream2_get_be16u(&s->g) >> colour_depth[2] - 8; } s->palette[i] = 0xffu << 24 | r << 16 | g << 8 | b; } } else if (atom2 == MKBETAG('c','d','e','f') && atom2_size >= 2) { int n = bytestream2_get_be16u(&s->g); for (; n>0; n--) { int cn = bytestream2_get_be16(&s->g); int av_unused typ = bytestream2_get_be16(&s->g); int asoc = bytestream2_get_be16(&s->g); if (cn < 4 || asoc < 4) s->cdef[cn] = asoc; } } bytestream2_seek(&s->g, atom2_end, SEEK_SET); } while (atom_end - atom2_end >= 8); } else { search_range--; } bytestream2_seek(&s->g, atom_end, SEEK_SET); } return 0; } static int jpeg2000_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { Jpeg2000DecoderContext *s = avctx->priv_data; ThreadFrame frame = { .f = data }; AVFrame *picture = data; int tileno, ret; s->avctx = avctx; bytestream2_init(&s->g, avpkt->data, avpkt->size); s->curtileno = -1; memset(s->cdef, -1, sizeof(s->cdef)); if (bytestream2_get_bytes_left(&s->g) < 2) { ret = AVERROR_INVALIDDATA; goto end; } // check if the image is in jp2 format if (bytestream2_get_bytes_left(&s->g) >= 12 && (bytestream2_get_be32u(&s->g) == 12) && (bytestream2_get_be32u(&s->g) == JP2_SIG_TYPE) && (bytestream2_get_be32u(&s->g) == JP2_SIG_VALUE)) { if (!jp2_find_codestream(s)) { av_log(avctx, AV_LOG_ERROR, "Could not find Jpeg2000 codestream atom.\n"); ret = AVERROR_INVALIDDATA; goto end; } } else { bytestream2_seek(&s->g, 0, SEEK_SET); } if (bytestream2_get_be16u(&s->g) != JPEG2000_SOC) { av_log(avctx, AV_LOG_ERROR, "SOC marker not present\n"); ret = AVERROR_INVALIDDATA; goto end; } if (ret = jpeg2000_read_main_headers(s)) goto end; /* get picture buffer */ if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0) goto end; picture->pict_type = AV_PICTURE_TYPE_I; picture->key_frame = 1; if (ret = jpeg2000_read_bitstream_packets(s)) goto end; for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) if (ret = jpeg2000_decode_tile(s, s->tile + tileno, picture)) goto end; jpeg2000_dec_cleanup(s); *got_frame = 1; if (s->avctx->pix_fmt == AV_PIX_FMT_PAL8) memcpy(picture->data[1], s->palette, 256 * sizeof(uint32_t)); return bytestream2_tell(&s->g); end: jpeg2000_dec_cleanup(s); return ret; } static void jpeg2000_init_static_data(AVCodec *codec) { ff_jpeg2000_init_tier1_luts(); ff_mqc_init_context_tables(); } #define OFFSET(x) offsetof(Jpeg2000DecoderContext, x) #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM static const AVOption options[] = { { "lowres", "Lower the decoding resolution by a power of two", OFFSET(reduction_factor), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, JPEG2000_MAX_RESLEVELS - 1, VD }, { NULL }, }; static const AVProfile profiles[] = { { FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_0, "JPEG 2000 codestream restriction 0" }, { FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_1, "JPEG 2000 codestream restriction 1" }, { FF_PROFILE_JPEG2000_CSTREAM_NO_RESTRICTION, "JPEG 2000 no codestream restrictions" }, { FF_PROFILE_JPEG2000_DCINEMA_2K, "JPEG 2000 digital cinema 2K" }, { FF_PROFILE_JPEG2000_DCINEMA_4K, "JPEG 2000 digital cinema 4K" }, { FF_PROFILE_UNKNOWN }, }; static const AVClass jpeg2000_class = { .class_name = "jpeg2000", .item_name = av_default_item_name, .option = options, .version = LIBAVUTIL_VERSION_INT, }; AVCodec ff_jpeg2000_decoder = { .name = "jpeg2000", .long_name = NULL_IF_CONFIG_SMALL("JPEG 2000"), .type = AVMEDIA_TYPE_VIDEO, .id = AV_CODEC_ID_JPEG2000, .capabilities = CODEC_CAP_FRAME_THREADS, .priv_data_size = sizeof(Jpeg2000DecoderContext), .init_static_data = jpeg2000_init_static_data, .decode = jpeg2000_decode_frame, .priv_class = &jpeg2000_class, .max_lowres = 5, .profiles = NULL_IF_CONFIG_SMALL(profiles) };
./CrossVul/dataset_final_sorted/CWE-119/c/bad_5820_0
crossvul-cpp_data_good_1615_0
/* ----------------------------------------------------------------------------- * Copyright (c) 2011 Ozmo Inc * Released under the GNU General Public License Version 2 (GPLv2). * * This file implements the protocol specific parts of the USB service for a PD. * ----------------------------------------------------------------------------- */ #include <linux/module.h> #include <linux/timer.h> #include <linux/sched.h> #include <linux/netdevice.h> #include <linux/errno.h> #include <linux/input.h> #include <asm/unaligned.h> #include "ozdbg.h" #include "ozprotocol.h" #include "ozeltbuf.h" #include "ozpd.h" #include "ozproto.h" #include "ozusbif.h" #include "ozhcd.h" #include "ozusbsvc.h" #define MAX_ISOC_FIXED_DATA (253-sizeof(struct oz_isoc_fixed)) /* * Context: softirq */ static int oz_usb_submit_elt(struct oz_elt_buf *eb, struct oz_elt_info *ei, struct oz_usb_ctx *usb_ctx, u8 strid, u8 isoc) { int ret; struct oz_elt *elt = (struct oz_elt *)ei->data; struct oz_app_hdr *app_hdr = (struct oz_app_hdr *)(elt+1); elt->type = OZ_ELT_APP_DATA; ei->app_id = OZ_APPID_USB; ei->length = elt->length + sizeof(struct oz_elt); app_hdr->app_id = OZ_APPID_USB; spin_lock_bh(&eb->lock); if (isoc == 0) { app_hdr->elt_seq_num = usb_ctx->tx_seq_num++; if (usb_ctx->tx_seq_num == 0) usb_ctx->tx_seq_num = 1; } ret = oz_queue_elt_info(eb, isoc, strid, ei); if (ret) oz_elt_info_free(eb, ei); spin_unlock_bh(&eb->lock); return ret; } /* * Context: softirq */ int oz_usb_get_desc_req(void *hpd, u8 req_id, u8 req_type, u8 desc_type, u8 index, __le16 windex, int offset, int len) { struct oz_usb_ctx *usb_ctx = hpd; struct oz_pd *pd = usb_ctx->pd; struct oz_elt *elt; struct oz_get_desc_req *body; struct oz_elt_buf *eb = &pd->elt_buff; struct oz_elt_info *ei = oz_elt_info_alloc(&pd->elt_buff); oz_dbg(ON, " req_type = 0x%x\n", req_type); oz_dbg(ON, " desc_type = 0x%x\n", desc_type); oz_dbg(ON, " index = 0x%x\n", index); oz_dbg(ON, " windex = 0x%x\n", windex); oz_dbg(ON, " offset = 0x%x\n", offset); oz_dbg(ON, " len = 0x%x\n", len); if (len > 200) len = 200; if (ei == NULL) return -1; elt = (struct oz_elt *)ei->data; elt->length = sizeof(struct oz_get_desc_req); body = (struct oz_get_desc_req *)(elt+1); body->type = OZ_GET_DESC_REQ; body->req_id = req_id; put_unaligned(cpu_to_le16(offset), &body->offset); put_unaligned(cpu_to_le16(len), &body->size); body->req_type = req_type; body->desc_type = desc_type; body->w_index = windex; body->index = index; return oz_usb_submit_elt(eb, ei, usb_ctx, 0, 0); } /* * Context: tasklet */ static int oz_usb_set_config_req(void *hpd, u8 req_id, u8 index) { struct oz_usb_ctx *usb_ctx = hpd; struct oz_pd *pd = usb_ctx->pd; struct oz_elt *elt; struct oz_elt_buf *eb = &pd->elt_buff; struct oz_elt_info *ei = oz_elt_info_alloc(&pd->elt_buff); struct oz_set_config_req *body; if (ei == NULL) return -1; elt = (struct oz_elt *)ei->data; elt->length = sizeof(struct oz_set_config_req); body = (struct oz_set_config_req *)(elt+1); body->type = OZ_SET_CONFIG_REQ; body->req_id = req_id; body->index = index; return oz_usb_submit_elt(eb, ei, usb_ctx, 0, 0); } /* * Context: tasklet */ static int oz_usb_set_interface_req(void *hpd, u8 req_id, u8 index, u8 alt) { struct oz_usb_ctx *usb_ctx = hpd; struct oz_pd *pd = usb_ctx->pd; struct oz_elt *elt; struct oz_elt_buf *eb = &pd->elt_buff; struct oz_elt_info *ei = oz_elt_info_alloc(&pd->elt_buff); struct oz_set_interface_req *body; if (ei == NULL) return -1; elt = (struct oz_elt *)ei->data; elt->length = sizeof(struct oz_set_interface_req); body = (struct oz_set_interface_req *)(elt+1); body->type = OZ_SET_INTERFACE_REQ; body->req_id = req_id; body->index = index; body->alternative = alt; return oz_usb_submit_elt(eb, ei, usb_ctx, 0, 0); } /* * Context: tasklet */ static int oz_usb_set_clear_feature_req(void *hpd, u8 req_id, u8 type, u8 recipient, u8 index, __le16 feature) { struct oz_usb_ctx *usb_ctx = hpd; struct oz_pd *pd = usb_ctx->pd; struct oz_elt *elt; struct oz_elt_buf *eb = &pd->elt_buff; struct oz_elt_info *ei = oz_elt_info_alloc(&pd->elt_buff); struct oz_feature_req *body; if (ei == NULL) return -1; elt = (struct oz_elt *)ei->data; elt->length = sizeof(struct oz_feature_req); body = (struct oz_feature_req *)(elt+1); body->type = type; body->req_id = req_id; body->recipient = recipient; body->index = index; put_unaligned(feature, &body->feature); return oz_usb_submit_elt(eb, ei, usb_ctx, 0, 0); } /* * Context: tasklet */ static int oz_usb_vendor_class_req(void *hpd, u8 req_id, u8 req_type, u8 request, __le16 value, __le16 index, const u8 *data, int data_len) { struct oz_usb_ctx *usb_ctx = hpd; struct oz_pd *pd = usb_ctx->pd; struct oz_elt *elt; struct oz_elt_buf *eb = &pd->elt_buff; struct oz_elt_info *ei = oz_elt_info_alloc(&pd->elt_buff); struct oz_vendor_class_req *body; if (ei == NULL) return -1; elt = (struct oz_elt *)ei->data; elt->length = sizeof(struct oz_vendor_class_req) - 1 + data_len; body = (struct oz_vendor_class_req *)(elt+1); body->type = OZ_VENDOR_CLASS_REQ; body->req_id = req_id; body->req_type = req_type; body->request = request; put_unaligned(value, &body->value); put_unaligned(index, &body->index); if (data_len) memcpy(body->data, data, data_len); return oz_usb_submit_elt(eb, ei, usb_ctx, 0, 0); } /* * Context: tasklet */ int oz_usb_control_req(void *hpd, u8 req_id, struct usb_ctrlrequest *setup, const u8 *data, int data_len) { unsigned wvalue = le16_to_cpu(setup->wValue); unsigned windex = le16_to_cpu(setup->wIndex); unsigned wlength = le16_to_cpu(setup->wLength); int rc = 0; if ((setup->bRequestType & USB_TYPE_MASK) == USB_TYPE_STANDARD) { switch (setup->bRequest) { case USB_REQ_GET_DESCRIPTOR: rc = oz_usb_get_desc_req(hpd, req_id, setup->bRequestType, (u8)(wvalue>>8), (u8)wvalue, setup->wIndex, 0, wlength); break; case USB_REQ_SET_CONFIGURATION: rc = oz_usb_set_config_req(hpd, req_id, (u8)wvalue); break; case USB_REQ_SET_INTERFACE: { u8 if_num = (u8)windex; u8 alt = (u8)wvalue; rc = oz_usb_set_interface_req(hpd, req_id, if_num, alt); } break; case USB_REQ_SET_FEATURE: rc = oz_usb_set_clear_feature_req(hpd, req_id, OZ_SET_FEATURE_REQ, setup->bRequestType & 0xf, (u8)windex, setup->wValue); break; case USB_REQ_CLEAR_FEATURE: rc = oz_usb_set_clear_feature_req(hpd, req_id, OZ_CLEAR_FEATURE_REQ, setup->bRequestType & 0xf, (u8)windex, setup->wValue); break; } } else { rc = oz_usb_vendor_class_req(hpd, req_id, setup->bRequestType, setup->bRequest, setup->wValue, setup->wIndex, data, data_len); } return rc; } /* * Context: softirq */ int oz_usb_send_isoc(void *hpd, u8 ep_num, struct urb *urb) { struct oz_usb_ctx *usb_ctx = hpd; struct oz_pd *pd = usb_ctx->pd; struct oz_elt_buf *eb; int i; int hdr_size; u8 *data; struct usb_iso_packet_descriptor *desc; if (pd->mode & OZ_F_ISOC_NO_ELTS) { for (i = 0; i < urb->number_of_packets; i++) { u8 *data; desc = &urb->iso_frame_desc[i]; data = ((u8 *)urb->transfer_buffer)+desc->offset; oz_send_isoc_unit(pd, ep_num, data, desc->length); } return 0; } hdr_size = sizeof(struct oz_isoc_fixed) - 1; eb = &pd->elt_buff; i = 0; while (i < urb->number_of_packets) { struct oz_elt_info *ei = oz_elt_info_alloc(eb); struct oz_elt *elt; struct oz_isoc_fixed *body; int unit_count; int unit_size; int rem; if (ei == NULL) return -1; rem = MAX_ISOC_FIXED_DATA; elt = (struct oz_elt *)ei->data; body = (struct oz_isoc_fixed *)(elt + 1); body->type = OZ_USB_ENDPOINT_DATA; body->endpoint = ep_num; body->format = OZ_DATA_F_ISOC_FIXED; unit_size = urb->iso_frame_desc[i].length; body->unit_size = (u8)unit_size; data = ((u8 *)(elt+1)) + hdr_size; unit_count = 0; while (i < urb->number_of_packets) { desc = &urb->iso_frame_desc[i]; if ((unit_size == desc->length) && (desc->length <= rem)) { memcpy(data, ((u8 *)urb->transfer_buffer) + desc->offset, unit_size); data += unit_size; rem -= unit_size; unit_count++; desc->status = 0; desc->actual_length = desc->length; i++; } else { break; } } elt->length = hdr_size + MAX_ISOC_FIXED_DATA - rem; /* Store the number of units in body->frame_number for the * moment. This field will be correctly determined before * the element is sent. */ body->frame_number = (u8)unit_count; oz_usb_submit_elt(eb, ei, usb_ctx, ep_num, pd->mode & OZ_F_ISOC_ANYTIME); } return 0; } /* * Context: softirq-serialized */ static void oz_usb_handle_ep_data(struct oz_usb_ctx *usb_ctx, struct oz_usb_hdr *usb_hdr, int len) { struct oz_data *data_hdr = (struct oz_data *)usb_hdr; switch (data_hdr->format) { case OZ_DATA_F_MULTIPLE_FIXED: { struct oz_multiple_fixed *body = (struct oz_multiple_fixed *)data_hdr; u8 *data = body->data; int n = (len - sizeof(struct oz_multiple_fixed)+1) / body->unit_size; while (n--) { oz_hcd_data_ind(usb_ctx->hport, body->endpoint, data, body->unit_size); data += body->unit_size; } } break; case OZ_DATA_F_ISOC_FIXED: { struct oz_isoc_fixed *body = (struct oz_isoc_fixed *)data_hdr; int data_len = len-sizeof(struct oz_isoc_fixed)+1; int unit_size = body->unit_size; u8 *data = body->data; int count; int i; if (!unit_size) break; count = data_len/unit_size; for (i = 0; i < count; i++) { oz_hcd_data_ind(usb_ctx->hport, body->endpoint, data, unit_size); data += unit_size; } } break; } } /* * This is called when the PD has received a USB element. The type of element * is determined and is then passed to an appropriate handler function. * Context: softirq-serialized */ void oz_usb_rx(struct oz_pd *pd, struct oz_elt *elt) { struct oz_usb_hdr *usb_hdr = (struct oz_usb_hdr *)(elt + 1); struct oz_usb_ctx *usb_ctx; spin_lock_bh(&pd->app_lock[OZ_APPID_USB]); usb_ctx = (struct oz_usb_ctx *)pd->app_ctx[OZ_APPID_USB]; if (usb_ctx) oz_usb_get(usb_ctx); spin_unlock_bh(&pd->app_lock[OZ_APPID_USB]); if (usb_ctx == NULL) return; /* Context has gone so nothing to do. */ if (usb_ctx->stopped) goto done; /* If sequence number is non-zero then check it is not a duplicate. * Zero sequence numbers are always accepted. */ if (usb_hdr->elt_seq_num != 0) { if (((usb_ctx->rx_seq_num - usb_hdr->elt_seq_num) & 0x80) == 0) /* Reject duplicate element. */ goto done; } usb_ctx->rx_seq_num = usb_hdr->elt_seq_num; switch (usb_hdr->type) { case OZ_GET_DESC_RSP: { struct oz_get_desc_rsp *body = (struct oz_get_desc_rsp *)usb_hdr; u16 offs, total_size; u8 data_len; if (elt->length < sizeof(struct oz_get_desc_rsp) - 1) break; data_len = elt->length - (sizeof(struct oz_get_desc_rsp) - 1); offs = le16_to_cpu(get_unaligned(&body->offset)); total_size = le16_to_cpu(get_unaligned(&body->total_size)); oz_dbg(ON, "USB_REQ_GET_DESCRIPTOR - cnf\n"); oz_hcd_get_desc_cnf(usb_ctx->hport, body->req_id, body->rcode, body->data, data_len, offs, total_size); } break; case OZ_SET_CONFIG_RSP: { struct oz_set_config_rsp *body = (struct oz_set_config_rsp *)usb_hdr; oz_hcd_control_cnf(usb_ctx->hport, body->req_id, body->rcode, NULL, 0); } break; case OZ_SET_INTERFACE_RSP: { struct oz_set_interface_rsp *body = (struct oz_set_interface_rsp *)usb_hdr; oz_hcd_control_cnf(usb_ctx->hport, body->req_id, body->rcode, NULL, 0); } break; case OZ_VENDOR_CLASS_RSP: { struct oz_vendor_class_rsp *body = (struct oz_vendor_class_rsp *)usb_hdr; oz_hcd_control_cnf(usb_ctx->hport, body->req_id, body->rcode, body->data, elt->length- sizeof(struct oz_vendor_class_rsp)+1); } break; case OZ_USB_ENDPOINT_DATA: oz_usb_handle_ep_data(usb_ctx, usb_hdr, elt->length); break; } done: oz_usb_put(usb_ctx); } /* * Context: softirq, process */ void oz_usb_farewell(struct oz_pd *pd, u8 ep_num, u8 *data, u8 len) { struct oz_usb_ctx *usb_ctx; spin_lock_bh(&pd->app_lock[OZ_APPID_USB]); usb_ctx = (struct oz_usb_ctx *)pd->app_ctx[OZ_APPID_USB]; if (usb_ctx) oz_usb_get(usb_ctx); spin_unlock_bh(&pd->app_lock[OZ_APPID_USB]); if (usb_ctx == NULL) return; /* Context has gone so nothing to do. */ if (!usb_ctx->stopped) { oz_dbg(ON, "Farewell indicated ep = 0x%x\n", ep_num); oz_hcd_data_ind(usb_ctx->hport, ep_num, data, len); } oz_usb_put(usb_ctx); }
./CrossVul/dataset_final_sorted/CWE-119/c/good_1615_0
crossvul-cpp_data_bad_340_3
/* * 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 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); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, 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); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, 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_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "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; unsigned int i; 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); SC_TEST_RET(ctx, SC_LOG_DEBUG_NORMAL, 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_debug(ctx, SC_LOG_DEBUG_NORMAL, "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) SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY); *file_out = file; file->path = *in_path; for(i=2; i+1<apdu.resplen && i+1+apdu.resp[i+1]<apdu.resplen; i+=2+apdu.resp[i+1]){ int j, len=apdu.resp[i+1]; unsigned char type=apdu.resp[i], *d=apdu.resp+i+2; switch (type) { case 0x80: case 0x81: file->size=0; for(j=0; j<len; ++j) file->size = (file->size<<8) | d[j]; break; case 0x82: file->shareable = (d[0] & 0x40) ? 1 : 0; file->ef_structure = d[0] & 7; switch ((d[0]>>3) & 7) { case 0: file->type = SC_FILE_TYPE_WORKING_EF; break; case 7: file->type = SC_FILE_TYPE_DF; break; default: sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "invalid file type %02X in file descriptor\n", d[0]); SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_UNKNOWN_DATA_RECEIVED); } break; case 0x83: file->id = (d[0]<<8) | d[1]; break; case 0x84: memcpy(file->name, d, len); file->namelen = len; break; case 0x86: sc_file_set_sec_attr(file, d, len); break; default: if (len>0) sc_file_set_prop_attr(file, d, len); } } file->magic = SC_FILE_MAGIC; 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); SC_TEST_RET(ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); if (apdu.sw1==0x6A && (apdu.sw2==0x82 || apdu.sw2==0x88)) continue; r = sc_check_sw(card, apdu.sw1, apdu.sw2); SC_TEST_RET(ctx, SC_LOG_DEBUG_NORMAL, r, "List Dir failed"); if (apdu.resplen > buflen) return SC_ERROR_BUFFER_TOO_SMALL; sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "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_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "File type has to be SC_PATH_TYPE_FILE_ID\n"); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, 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); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, 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)){ SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_ARGUMENTS); } if(!(env->flags & SC_SEC_ENV_KEY_REF_PRESENT)) sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "No Key-Reference in SecEnvironment\n"); else sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "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_debug(ctx, SC_LOG_DEBUG_NORMAL, "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; *p++=0x80; *p++=0x01; *p++=tcos3 ? 0x0A : 0x10; 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_debug(ctx, SC_LOG_DEBUG_NORMAL, "%s: APDU transmit failed", sc_strerror(r)); return r; } if (apdu.sw1==0x6A && (apdu.sw2==0x81 || apdu.sw2==0x88)) { sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "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); if (datalen > 255) 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_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "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); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, 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); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, 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; SC_FUNC_CALLED(ctx, SC_LOG_DEBUG_NORMAL); sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "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); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, 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); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, 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.set_security_env = tcos_set_security_env; 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-119/c/bad_340_3
crossvul-cpp_data_bad_2397_0
/***************************************************************************** * rtpfmt.c: RTP payload formats ***************************************************************************** * Copyright (C) 2003-2004 VLC authors and VideoLAN * Copyright © 2007 Rémi Denis-Courmont * $Id$ * * Authors: Laurent Aimar <fenrir@via.ecp.fr> * * 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. *****************************************************************************/ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <vlc_common.h> #include <vlc_sout.h> #include <vlc_block.h> #include <vlc_strings.h> #include "rtp.h" #include "../demux/xiph.h" #include <assert.h> static int rtp_packetize_mpa (sout_stream_id_sys_t *, block_t *); static int rtp_packetize_mpv (sout_stream_id_sys_t *, block_t *); static int rtp_packetize_ac3 (sout_stream_id_sys_t *, block_t *); static int rtp_packetize_simple(sout_stream_id_sys_t *, block_t *); static int rtp_packetize_split(sout_stream_id_sys_t *, block_t *); static int rtp_packetize_pcm(sout_stream_id_sys_t *, block_t *); static int rtp_packetize_swab (sout_stream_id_sys_t *, block_t *); static int rtp_packetize_mp4a (sout_stream_id_sys_t *, block_t *); static int rtp_packetize_mp4a_latm (sout_stream_id_sys_t *, block_t *); static int rtp_packetize_h263 (sout_stream_id_sys_t *, block_t *); static int rtp_packetize_h264 (sout_stream_id_sys_t *, block_t *); static int rtp_packetize_amr (sout_stream_id_sys_t *, block_t *); static int rtp_packetize_spx (sout_stream_id_sys_t *, block_t *); static int rtp_packetize_t140 (sout_stream_id_sys_t *, block_t *); static int rtp_packetize_g726_16 (sout_stream_id_sys_t *, block_t *); static int rtp_packetize_g726_24 (sout_stream_id_sys_t *, block_t *); static int rtp_packetize_g726_32 (sout_stream_id_sys_t *, block_t *); static int rtp_packetize_g726_40 (sout_stream_id_sys_t *, block_t *); static int rtp_packetize_xiph (sout_stream_id_sys_t *, block_t *); static int rtp_packetize_vp8 (sout_stream_id_sys_t *, block_t *); static int rtp_packetize_jpeg (sout_stream_id_sys_t *, block_t *); #define XIPH_IDENT (0) /* Helpers common to xiph codecs (vorbis and theora) */ static int rtp_xiph_pack_headers(size_t room, void *p_extra, size_t i_extra, uint8_t **p_buffer, size_t *i_buffer, uint8_t *theora_pixel_fmt) { unsigned packet_size[XIPH_MAX_HEADER_COUNT]; void *packet[XIPH_MAX_HEADER_COUNT]; unsigned packet_count; if (xiph_SplitHeaders(packet_size, packet, &packet_count, i_extra, p_extra)) return VLC_EGENERIC;; if (packet_count < 3) return VLC_EGENERIC;; if (theora_pixel_fmt != NULL) { if (packet_size[0] < 42) return VLC_EGENERIC; *theora_pixel_fmt = (((uint8_t *)packet[0])[41] >> 3) & 0x03; } unsigned length_size[2] = { 0, 0 }; for (int i = 0; i < 2; i++) { unsigned size = packet_size[i]; while (size > 0) { length_size[i]++; size >>= 7; } } *i_buffer = room + 1 + length_size[0] + length_size[1] + packet_size[0] + packet_size[1] + packet_size[2]; *p_buffer = malloc(*i_buffer); if (*p_buffer == NULL) return VLC_ENOMEM; uint8_t *p = *p_buffer + room; /* Number of headers */ *p++ = 2; for (int i = 0; i < 2; i++) { unsigned size = length_size[i]; while (size > 0) { *p = (packet_size[i] >> (7 * (size - 1))) & 0x7f; if (--size > 0) *p |= 0x80; p++; } } for (int i = 0; i < 3; i++) { memcpy(p, packet[i], packet_size[i]); p += packet_size[i]; } return VLC_SUCCESS; } static char *rtp_xiph_b64_oob_config(void *p_extra, size_t i_extra, uint8_t *theora_pixel_fmt) { uint8_t *p_buffer; size_t i_buffer; if (rtp_xiph_pack_headers(9, p_extra, i_extra, &p_buffer, &i_buffer, theora_pixel_fmt) != VLC_SUCCESS) return NULL; /* Number of packed headers */ SetDWBE(p_buffer, 1); /* Ident */ uint32_t ident = XIPH_IDENT; SetWBE(p_buffer + 4, ident >> 8); p_buffer[6] = ident & 0xff; /* Length field */ SetWBE(p_buffer + 7, i_buffer); char *config = vlc_b64_encode_binary(p_buffer, i_buffer); free(p_buffer); return config; } static void sprintf_hexa( char *s, uint8_t *p_data, int i_data ) { static const char hex[16] = "0123456789abcdef"; for( int i = 0; i < i_data; i++ ) { s[2*i+0] = hex[(p_data[i]>>4)&0xf]; s[2*i+1] = hex[(p_data[i] )&0xf]; } s[2*i_data] = '\0'; } /* TODO: make this into something more clever than a big switch? */ int rtp_get_fmt( vlc_object_t *obj, es_format_t *p_fmt, const char *mux, rtp_format_t *rtp_fmt ) { assert( p_fmt != NULL || mux != NULL ); /* Dynamic payload type. Payload types are scoped to the RTP * session, and we put each ES in its own session, so no risk of * conflict. */ rtp_fmt->payload_type = 96; rtp_fmt->cat = mux != NULL ? VIDEO_ES : p_fmt->i_cat; if( rtp_fmt->cat == AUDIO_ES ) { rtp_fmt->clock_rate = p_fmt->audio.i_rate; rtp_fmt->channels = p_fmt->audio.i_channels; } else rtp_fmt->clock_rate = 90000; /* most common case for video */ /* Stream bitrate in kbps */ rtp_fmt->bitrate = p_fmt != NULL ? p_fmt->i_bitrate/1000 : 0; rtp_fmt->fmtp = NULL; if( mux != NULL ) { if( strncmp( mux, "ts", 2 ) == 0 ) { rtp_fmt->payload_type = 33; rtp_fmt->ptname = "MP2T"; } else rtp_fmt->ptname = "MP2P"; return VLC_SUCCESS; } switch( p_fmt->i_codec ) { case VLC_CODEC_MULAW: if( p_fmt->audio.i_channels == 1 && p_fmt->audio.i_rate == 8000 ) rtp_fmt->payload_type = 0; rtp_fmt->ptname = "PCMU"; rtp_fmt->pf_packetize = rtp_packetize_pcm; break; case VLC_CODEC_ALAW: if( p_fmt->audio.i_channels == 1 && p_fmt->audio.i_rate == 8000 ) rtp_fmt->payload_type = 8; rtp_fmt->ptname = "PCMA"; rtp_fmt->pf_packetize = rtp_packetize_pcm; break; case VLC_CODEC_S16B: case VLC_CODEC_S16L: if( p_fmt->audio.i_channels == 1 && p_fmt->audio.i_rate == 44100 ) { rtp_fmt->payload_type = 11; } else if( p_fmt->audio.i_channels == 2 && p_fmt->audio.i_rate == 44100 ) { rtp_fmt->payload_type = 10; } rtp_fmt->ptname = "L16"; if( p_fmt->i_codec == VLC_CODEC_S16B ) rtp_fmt->pf_packetize = rtp_packetize_pcm; else rtp_fmt->pf_packetize = rtp_packetize_swab; break; case VLC_CODEC_U8: rtp_fmt->ptname = "L8"; rtp_fmt->pf_packetize = rtp_packetize_pcm; break; case VLC_CODEC_S24B: rtp_fmt->ptname = "L24"; rtp_fmt->pf_packetize = rtp_packetize_pcm; break; case VLC_CODEC_MPGA: rtp_fmt->payload_type = 14; rtp_fmt->ptname = "MPA"; rtp_fmt->clock_rate = 90000; /* not 44100 */ rtp_fmt->pf_packetize = rtp_packetize_mpa; break; case VLC_CODEC_MPGV: rtp_fmt->payload_type = 32; rtp_fmt->ptname = "MPV"; rtp_fmt->pf_packetize = rtp_packetize_mpv; break; case VLC_CODEC_ADPCM_G726: switch( p_fmt->i_bitrate / 1000 ) { case 16: rtp_fmt->ptname = "G726-16"; rtp_fmt->pf_packetize = rtp_packetize_g726_16; break; case 24: rtp_fmt->ptname = "G726-24"; rtp_fmt->pf_packetize = rtp_packetize_g726_24; break; case 32: rtp_fmt->ptname = "G726-32"; rtp_fmt->pf_packetize = rtp_packetize_g726_32; break; case 40: rtp_fmt->ptname = "G726-40"; rtp_fmt->pf_packetize = rtp_packetize_g726_40; break; default: msg_Err( obj, "cannot add this stream (unsupported " "G.726 bit rate: %u)", p_fmt->i_bitrate ); return VLC_EGENERIC; } break; case VLC_CODEC_A52: rtp_fmt->ptname = "ac3"; rtp_fmt->pf_packetize = rtp_packetize_ac3; break; case VLC_CODEC_H263: rtp_fmt->ptname = "H263-1998"; rtp_fmt->pf_packetize = rtp_packetize_h263; break; case VLC_CODEC_H264: rtp_fmt->ptname = "H264"; rtp_fmt->pf_packetize = rtp_packetize_h264; rtp_fmt->fmtp = NULL; if( p_fmt->i_extra > 0 ) { uint8_t *p_buffer = p_fmt->p_extra; int i_buffer = p_fmt->i_extra; char *p_64_sps = NULL; char *p_64_pps = NULL; char hexa[6+1]; while( i_buffer > 4 ) { int i_offset = 0; int i_size = 0; while( p_buffer[0] != 0 || p_buffer[1] != 0 || p_buffer[2] != 1 ) { p_buffer++; i_buffer--; if( i_buffer == 0 ) break; } if( i_buffer < 4 || memcmp(p_buffer, "\x00\x00\x01", 3 ) ) { msg_Dbg( obj, "No startcode found.."); break; } p_buffer += 3; i_buffer -= 3; const int i_nal_type = p_buffer[0]&0x1f; msg_Dbg( obj, "we found a startcode for NAL with TYPE:%d", i_nal_type ); i_size = i_buffer; for( i_offset = 0; i_offset+2 < i_buffer ; i_offset++) { if( !memcmp(p_buffer + i_offset, "\x00\x00\x01", 3 ) ) { /* we found another startcode */ while( i_offset > 0 && 0 == p_buffer[ i_offset - 1 ] ) i_offset--; i_size = i_offset; break; } } if( i_size == 0 ) { msg_Dbg( obj, "No-info found in nal "); continue; } if( i_nal_type == 7 ) { free( p_64_sps ); p_64_sps = vlc_b64_encode_binary( p_buffer, i_size ); /* XXX: nothing ensures that i_size >= 4 ?? */ sprintf_hexa( hexa, &p_buffer[1], 3 ); } else if( i_nal_type == 8 ) { free( p_64_pps ); p_64_pps = vlc_b64_encode_binary( p_buffer, i_size ); } i_buffer -= i_size; p_buffer += i_size; } /* */ if( p_64_sps && p_64_pps && ( asprintf( &rtp_fmt->fmtp, "packetization-mode=1;profile-level-id=%s;" "sprop-parameter-sets=%s,%s;", hexa, p_64_sps, p_64_pps ) == -1 ) ) rtp_fmt->fmtp = NULL; free( p_64_sps ); free( p_64_pps ); } if( rtp_fmt->fmtp == NULL ) rtp_fmt->fmtp = strdup( "packetization-mode=1" ); break; case VLC_CODEC_MP4V: { rtp_fmt->ptname = "MP4V-ES"; rtp_fmt->pf_packetize = rtp_packetize_split; if( p_fmt->i_extra > 0 ) { char hexa[2*p_fmt->i_extra +1]; sprintf_hexa( hexa, p_fmt->p_extra, p_fmt->i_extra ); if( asprintf( &rtp_fmt->fmtp, "profile-level-id=3; config=%s;", hexa ) == -1 ) rtp_fmt->fmtp = NULL; } break; } case VLC_CODEC_MP4A: { if( ! var_InheritBool( obj, "sout-rtp-mp4a-latm" ) ) { char hexa[2*p_fmt->i_extra +1]; rtp_fmt->ptname = "mpeg4-generic"; rtp_fmt->pf_packetize = rtp_packetize_mp4a; sprintf_hexa( hexa, p_fmt->p_extra, p_fmt->i_extra ); if( asprintf( &rtp_fmt->fmtp, "streamtype=5; profile-level-id=15; " "mode=AAC-hbr; config=%s; SizeLength=13; " "IndexLength=3; IndexDeltaLength=3; Profile=1;", hexa ) == -1 ) rtp_fmt->fmtp = NULL; } else { char hexa[13]; int i; unsigned char config[6]; unsigned int aacsrates[15] = { 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350, 0, 0 }; for( i = 0; i < 15; i++ ) if( p_fmt->audio.i_rate == aacsrates[i] ) break; config[0]=0x40; config[1]=0; config[2]=0x20|i; config[3]=p_fmt->audio.i_channels<<4; config[4]=0x3f; config[5]=0xc0; rtp_fmt->ptname = "MP4A-LATM"; rtp_fmt->pf_packetize = rtp_packetize_mp4a_latm; sprintf_hexa( hexa, config, 6 ); if( asprintf( &rtp_fmt->fmtp, "profile-level-id=15; " "object=2; cpresent=0; config=%s", hexa ) == -1 ) rtp_fmt->fmtp = NULL; } break; } case VLC_CODEC_AMR_NB: rtp_fmt->ptname = "AMR"; rtp_fmt->fmtp = strdup( "octet-align=1" ); rtp_fmt->pf_packetize = rtp_packetize_amr; break; case VLC_CODEC_AMR_WB: rtp_fmt->ptname = "AMR-WB"; rtp_fmt->fmtp = strdup( "octet-align=1" ); rtp_fmt->pf_packetize = rtp_packetize_amr; break; case VLC_CODEC_SPEEX: rtp_fmt->ptname = "SPEEX"; rtp_fmt->pf_packetize = rtp_packetize_spx; break; case VLC_CODEC_VORBIS: rtp_fmt->ptname = "vorbis"; rtp_fmt->pf_packetize = rtp_packetize_xiph; if( p_fmt->i_extra > 0 ) { rtp_fmt->fmtp = NULL; char *config = rtp_xiph_b64_oob_config(p_fmt->p_extra, p_fmt->i_extra, NULL); if (config == NULL) break; if( asprintf( &rtp_fmt->fmtp, "configuration=%s;", config ) == -1 ) rtp_fmt->fmtp = NULL; free(config); } break; case VLC_CODEC_THEORA: rtp_fmt->ptname = "theora"; rtp_fmt->pf_packetize = rtp_packetize_xiph; if( p_fmt->i_extra > 0 ) { rtp_fmt->fmtp = NULL; uint8_t pixel_fmt, c1, c2; char *config = rtp_xiph_b64_oob_config(p_fmt->p_extra, p_fmt->i_extra, &pixel_fmt); if (config == NULL) break; if (pixel_fmt == 1) { /* reserved */ free(config); break; } switch (pixel_fmt) { case 0: c1 = 2; c2 = 0; break; case 2: c1 = c2 = 2; break; case 3: c1 = c2 = 4; break; default: assert(0); } if( asprintf( &rtp_fmt->fmtp, "sampling=YCbCr-4:%d:%d; width=%d; height=%d; " "delivery-method=inline; configuration=%s; " "delivery-method=in_band;", c1, c2, p_fmt->video.i_width, p_fmt->video.i_height, config ) == -1 ) rtp_fmt->fmtp = NULL; free(config); } break; case VLC_CODEC_ITU_T140: rtp_fmt->ptname = "t140" ; rtp_fmt->clock_rate = 1000; rtp_fmt->pf_packetize = rtp_packetize_t140; break; case VLC_CODEC_GSM: rtp_fmt->payload_type = 3; rtp_fmt->ptname = "GSM"; rtp_fmt->pf_packetize = rtp_packetize_split; break; case VLC_CODEC_OPUS: if (p_fmt->audio.i_channels > 2) { msg_Err( obj, "Multistream opus not supported in RTP" " (having %d channels input)", p_fmt->audio.i_channels ); return VLC_EGENERIC; } rtp_fmt->ptname = "opus"; rtp_fmt->pf_packetize = rtp_packetize_simple; rtp_fmt->clock_rate = 48000; rtp_fmt->channels = 2; if (p_fmt->audio.i_channels == 2) rtp_fmt->fmtp = strdup( "sprop-stereo=1" ); break; case VLC_CODEC_VP8: rtp_fmt->ptname = "VP8"; rtp_fmt->pf_packetize = rtp_packetize_vp8; break; case VLC_CODEC_MJPG: case VLC_CODEC_JPEG: rtp_fmt->ptname = "JPEG"; rtp_fmt->payload_type = 26; rtp_fmt->pf_packetize = rtp_packetize_jpeg; break; default: msg_Err( obj, "cannot add this stream (unsupported " "codec: %4.4s)", (char*)&p_fmt->i_codec ); return VLC_EGENERIC; } return VLC_SUCCESS; } static int rtp_packetize_h264_nal( sout_stream_id_sys_t *id, const uint8_t *p_data, int i_data, int64_t i_pts, int64_t i_dts, bool b_last, int64_t i_length ); int rtp_packetize_xiph_config( sout_stream_id_sys_t *id, const char *fmtp, int64_t i_pts ) { if (fmtp == NULL) return VLC_EGENERIC; /* extract base64 configuration from fmtp */ char *start = strstr(fmtp, "configuration="); assert(start != NULL); start += sizeof("configuration=") - 1; char *end = strchr(start, ';'); assert(end != NULL); size_t len = end - start; char b64[len + 1]; memcpy(b64, start, len); b64[len] = '\0'; int i_max = rtp_mtu (id) - 6; /* payload max in one packet */ uint8_t *p_orig, *p_data; int i_data; i_data = vlc_b64_decode_binary(&p_orig, b64); if (i_data <= 9) { free(p_orig); return VLC_EGENERIC; } p_data = p_orig + 9; i_data -= 9; int i_count = ( i_data + i_max - 1 ) / i_max; for( int i = 0; i < i_count; i++ ) { int i_payload = __MIN( i_max, i_data ); block_t *out = block_Alloc( 18 + i_payload ); unsigned fragtype, numpkts; if (i_count == 1) { fragtype = 0; numpkts = 1; } else { numpkts = 0; if (i == 0) fragtype = 1; else if (i == i_count - 1) fragtype = 3; else fragtype = 2; } /* Ident:24, Fragment type:2, Vorbis/Theora Data Type:2, # of pkts:4 */ uint32_t header = ((XIPH_IDENT & 0xffffff) << 8) | (fragtype << 6) | (1 << 4) | numpkts; /* rtp common header */ rtp_packetize_common( id, out, 0, i_pts ); SetDWBE( out->p_buffer + 12, header); SetWBE( out->p_buffer + 16, i_payload); memcpy( &out->p_buffer[18], p_data, i_payload ); out->i_dts = i_pts; rtp_packetize_send( id, out ); p_data += i_payload; i_data -= i_payload; } free(p_orig); return VLC_SUCCESS; } /* rfc5215 */ static int rtp_packetize_xiph( sout_stream_id_sys_t *id, block_t *in ) { int i_max = rtp_mtu (id) - 6; /* payload max in one packet */ int i_count = ( in->i_buffer + i_max - 1 ) / i_max; uint8_t *p_data = in->p_buffer; int i_data = in->i_buffer; for( int i = 0; i < i_count; i++ ) { int i_payload = __MIN( i_max, i_data ); block_t *out = block_Alloc( 18 + i_payload ); unsigned fragtype, numpkts; if (i_count == 1) { /* No fragmentation */ fragtype = 0; numpkts = 1; } else { /* Fragmentation */ numpkts = 0; if (i == 0) fragtype = 1; else if (i == i_count - 1) fragtype = 3; else fragtype = 2; } /* Ident:24, Fragment type:2, Vorbis/Theora Data Type:2, # of pkts:4 */ uint32_t header = ((XIPH_IDENT & 0xffffff) << 8) | (fragtype << 6) | (0 << 4) | numpkts; /* rtp common header */ rtp_packetize_common( id, out, 0, in->i_pts); SetDWBE( out->p_buffer + 12, header); SetWBE( out->p_buffer + 16, i_payload); memcpy( &out->p_buffer[18], p_data, i_payload ); out->i_dts = in->i_dts + i * in->i_length / i_count; out->i_length = in->i_length / i_count; rtp_packetize_send( id, out ); p_data += i_payload; i_data -= i_payload; } block_Release(in); return VLC_SUCCESS; } static int rtp_packetize_mpa( sout_stream_id_sys_t *id, block_t *in ) { int i_max = rtp_mtu (id) - 4; /* payload max in one packet */ int i_count = ( in->i_buffer + i_max - 1 ) / i_max; uint8_t *p_data = in->p_buffer; int i_data = in->i_buffer; int i; for( i = 0; i < i_count; i++ ) { int i_payload = __MIN( i_max, i_data ); block_t *out = block_Alloc( 16 + i_payload ); /* rtp common header */ rtp_packetize_common( id, out, (i == i_count - 1)?1:0, in->i_pts ); /* mbz set to 0 */ SetWBE( out->p_buffer + 12, 0 ); /* fragment offset in the current frame */ SetWBE( out->p_buffer + 14, i * i_max ); memcpy( &out->p_buffer[16], p_data, i_payload ); out->i_dts = in->i_dts + i * in->i_length / i_count; out->i_length = in->i_length / i_count; rtp_packetize_send( id, out ); p_data += i_payload; i_data -= i_payload; } block_Release(in); return VLC_SUCCESS; } /* rfc2250 */ static int rtp_packetize_mpv( sout_stream_id_sys_t *id, block_t *in ) { int i_max = rtp_mtu (id) - 4; /* payload max in one packet */ int i_count = ( in->i_buffer + i_max - 1 ) / i_max; uint8_t *p_data = in->p_buffer; int i_data = in->i_buffer; int i; int b_sequence_start = 0; int i_temporal_ref = 0; int i_picture_coding_type = 0; int i_fbv = 0, i_bfc = 0, i_ffv = 0, i_ffc = 0; int b_start_slice = 0; /* preparse this packet to get some info */ if( in->i_buffer > 4 ) { uint8_t *p = p_data; int i_rest = in->i_buffer; for( ;; ) { while( i_rest > 4 && ( p[0] != 0x00 || p[1] != 0x00 || p[2] != 0x01 ) ) { p++; i_rest--; } if( i_rest <= 4 ) { break; } p += 3; i_rest -= 4; if( *p == 0xb3 ) { /* sequence start code */ b_sequence_start = 1; } else if( *p == 0x00 && i_rest >= 4 ) { /* picture */ i_temporal_ref = ( p[1] << 2) |((p[2]>>6)&0x03); i_picture_coding_type = (p[2] >> 3)&0x07; if( i_rest >= 4 && ( i_picture_coding_type == 2 || i_picture_coding_type == 3 ) ) { i_ffv = (p[3] >> 2)&0x01; i_ffc = ((p[3]&0x03) << 1)|((p[4]>>7)&0x01); if( i_rest > 4 && i_picture_coding_type == 3 ) { i_fbv = (p[4]>>6)&0x01; i_bfc = (p[4]>>3)&0x07; } } } else if( *p <= 0xaf ) { b_start_slice = 1; } } } for( i = 0; i < i_count; i++ ) { int i_payload = __MIN( i_max, i_data ); block_t *out = block_Alloc( 16 + i_payload ); /* MBZ:5 T:1 TR:10 AN:1 N:1 S:1 B:1 E:1 P:3 FBV:1 BFC:3 FFV:1 FFC:3 */ uint32_t h = ( i_temporal_ref << 16 )| ( b_sequence_start << 13 )| ( b_start_slice << 12 )| ( i == i_count - 1 ? 1 << 11 : 0 )| ( i_picture_coding_type << 8 )| ( i_fbv << 7 )|( i_bfc << 4 )|( i_ffv << 3 )|i_ffc; /* rtp common header */ rtp_packetize_common( id, out, (i == i_count - 1)?1:0, in->i_pts > VLC_TS_INVALID ? in->i_pts : in->i_dts ); SetDWBE( out->p_buffer + 12, h ); memcpy( &out->p_buffer[16], p_data, i_payload ); out->i_dts = in->i_dts + i * in->i_length / i_count; out->i_length = in->i_length / i_count; rtp_packetize_send( id, out ); p_data += i_payload; i_data -= i_payload; } block_Release(in); return VLC_SUCCESS; } static int rtp_packetize_ac3( sout_stream_id_sys_t *id, block_t *in ) { int i_max = rtp_mtu (id) - 2; /* payload max in one packet */ int i_count = ( in->i_buffer + i_max - 1 ) / i_max; uint8_t *p_data = in->p_buffer; int i_data = in->i_buffer; int i; for( i = 0; i < i_count; i++ ) { int i_payload = __MIN( i_max, i_data ); block_t *out = block_Alloc( 14 + i_payload ); /* rtp common header */ rtp_packetize_common( id, out, (i == i_count - 1)?1:0, in->i_pts ); /* unit count */ out->p_buffer[12] = 1; /* unit header */ out->p_buffer[13] = 0x00; /* data */ memcpy( &out->p_buffer[14], p_data, i_payload ); out->i_dts = in->i_dts + i * in->i_length / i_count; out->i_length = in->i_length / i_count; rtp_packetize_send( id, out ); p_data += i_payload; i_data -= i_payload; } block_Release(in); return VLC_SUCCESS; } static int rtp_packetize_simple(sout_stream_id_sys_t *id, block_t *block) { bool marker = (block->i_flags & BLOCK_FLAG_DISCONTINUITY) != 0; block = block_Realloc(block, 12, block->i_buffer); if (unlikely(block == NULL)) return VLC_ENOMEM; rtp_packetize_common(id, block, marker, block->i_pts); rtp_packetize_send(id, block); return VLC_SUCCESS; } static int rtp_packetize_split( sout_stream_id_sys_t *id, block_t *in ) { int i_max = rtp_mtu (id); /* payload max in one packet */ int i_count = ( in->i_buffer + i_max - 1 ) / i_max; uint8_t *p_data = in->p_buffer; int i_data = in->i_buffer; int i; for( i = 0; i < i_count; i++ ) { int i_payload = __MIN( i_max, i_data ); block_t *out = block_Alloc( 12 + i_payload ); /* rtp common header */ rtp_packetize_common( id, out, (i == i_count - 1), (in->i_pts > VLC_TS_INVALID ? in->i_pts : in->i_dts) ); memcpy( &out->p_buffer[12], p_data, i_payload ); out->i_dts = in->i_dts + i * in->i_length / i_count; out->i_length = in->i_length / i_count; rtp_packetize_send( id, out ); p_data += i_payload; i_data -= i_payload; } block_Release(in); return VLC_SUCCESS; } static int rtp_packetize_pcm(sout_stream_id_sys_t *id, block_t *in) { unsigned max = rtp_mtu(id); while (in->i_buffer > max) { unsigned duration = (in->i_length * max) / in->i_buffer; bool marker = (in->i_flags & BLOCK_FLAG_DISCONTINUITY) != 0; block_t *out = block_Alloc(12 + max); if (unlikely(out == NULL)) { block_Release(in); return VLC_ENOMEM; } rtp_packetize_common(id, out, marker, in->i_pts); memcpy(out->p_buffer + 12, in->p_buffer, max); rtp_packetize_send(id, out); in->p_buffer += max; in->i_buffer -= max; in->i_pts += duration; in->i_length -= duration; in->i_flags &= ~BLOCK_FLAG_DISCONTINUITY; } return rtp_packetize_simple(id, in); /* zero copy for the last frame */ } /* split and convert from little endian to network byte order */ static int rtp_packetize_swab(sout_stream_id_sys_t *id, block_t *in) { unsigned max = rtp_mtu(id); while (in->i_buffer > 0) { unsigned payload = (max < in->i_buffer) ? max : in->i_buffer; unsigned duration = (in->i_length * payload) / in->i_buffer; bool marker = (in->i_flags & BLOCK_FLAG_DISCONTINUITY) != 0; block_t *out = block_Alloc(12 + payload); if (unlikely(out == NULL)) { block_Release(in); return VLC_ENOMEM; } rtp_packetize_common(id, out, marker, in->i_pts); swab(in->p_buffer, out->p_buffer + 12, payload); rtp_packetize_send(id, out); in->p_buffer += payload; in->i_buffer -= payload; in->i_pts += duration; in->i_length -= duration; in->i_flags &= ~BLOCK_FLAG_DISCONTINUITY; } block_Release(in); return VLC_SUCCESS; } /* rfc3016 */ static int rtp_packetize_mp4a_latm( sout_stream_id_sys_t *id, block_t *in ) { int i_max = rtp_mtu (id) - 2; /* payload max in one packet */ int latmhdrsize = in->i_buffer / 0xff + 1; int i_count = ( in->i_buffer + i_max - 1 ) / i_max; uint8_t *p_data = in->p_buffer, *p_header = NULL; int i_data = in->i_buffer; int i; for( i = 0; i < i_count; i++ ) { int i_payload = __MIN( i_max, i_data ); block_t *out; if( i != 0 ) latmhdrsize = 0; out = block_Alloc( 12 + latmhdrsize + i_payload ); /* rtp common header */ rtp_packetize_common( id, out, ((i == i_count - 1) ? 1 : 0), (in->i_pts > VLC_TS_INVALID ? in->i_pts : in->i_dts) ); if( i == 0 ) { int tmp = in->i_buffer; p_header=out->p_buffer+12; while( tmp > 0xfe ) { *p_header = 0xff; p_header++; tmp -= 0xff; } *p_header = tmp; } memcpy( &out->p_buffer[12+latmhdrsize], p_data, i_payload ); out->i_dts = in->i_dts + i * in->i_length / i_count; out->i_length = in->i_length / i_count; rtp_packetize_send( id, out ); p_data += i_payload; i_data -= i_payload; } block_Release(in); return VLC_SUCCESS; } static int rtp_packetize_mp4a( sout_stream_id_sys_t *id, block_t *in ) { int i_max = rtp_mtu (id) - 4; /* payload max in one packet */ int i_count = ( in->i_buffer + i_max - 1 ) / i_max; uint8_t *p_data = in->p_buffer; int i_data = in->i_buffer; int i; for( i = 0; i < i_count; i++ ) { int i_payload = __MIN( i_max, i_data ); block_t *out = block_Alloc( 16 + i_payload ); /* rtp common header */ rtp_packetize_common( id, out, ((i == i_count - 1)?1:0), (in->i_pts > VLC_TS_INVALID ? in->i_pts : in->i_dts) ); /* AU headers */ /* AU headers length (bits) */ out->p_buffer[12] = 0; out->p_buffer[13] = 2*8; /* for each AU length 13 bits + idx 3bits, */ SetWBE( out->p_buffer + 14, (in->i_buffer << 3) | 0 ); memcpy( &out->p_buffer[16], p_data, i_payload ); out->i_dts = in->i_dts + i * in->i_length / i_count; out->i_length = in->i_length / i_count; rtp_packetize_send( id, out ); p_data += i_payload; i_data -= i_payload; } block_Release(in); return VLC_SUCCESS; } /* rfc2429 */ #define RTP_H263_HEADER_SIZE (2) // plen = 0 #define RTP_H263_PAYLOAD_START (14) // plen = 0 static int rtp_packetize_h263( sout_stream_id_sys_t *id, block_t *in ) { uint8_t *p_data = in->p_buffer; int i_data = in->i_buffer; int i; int i_max = rtp_mtu (id) - RTP_H263_HEADER_SIZE; /* payload max in one packet */ int i_count; int b_p_bit; int b_v_bit = 0; // no pesky error resilience int i_plen = 0; // normally plen=0 for PSC packet int i_pebit = 0; // because plen=0 uint16_t h; if( i_data < 2 ) { block_Release(in); return VLC_EGENERIC; } if( p_data[0] || p_data[1] ) { block_Release(in); return VLC_EGENERIC; } /* remove 2 leading 0 bytes */ p_data += 2; i_data -= 2; i_count = ( i_data + i_max - 1 ) / i_max; for( i = 0; i < i_count; i++ ) { int i_payload = __MIN( i_max, i_data ); block_t *out = block_Alloc( RTP_H263_PAYLOAD_START + i_payload ); b_p_bit = (i == 0) ? 1 : 0; h = ( b_p_bit << 10 )| ( b_v_bit << 9 )| ( i_plen << 3 )| i_pebit; /* rtp common header */ //b_m_bit = 1; // always contains end of frame rtp_packetize_common( id, out, (i == i_count - 1)?1:0, in->i_pts > VLC_TS_INVALID ? in->i_pts : in->i_dts ); /* h263 header */ SetWBE( out->p_buffer + 12, h ); memcpy( &out->p_buffer[RTP_H263_PAYLOAD_START], p_data, i_payload ); out->i_dts = in->i_dts + i * in->i_length / i_count; out->i_length = in->i_length / i_count; rtp_packetize_send( id, out ); p_data += i_payload; i_data -= i_payload; } block_Release(in); return VLC_SUCCESS; } /* rfc3984 */ static int rtp_packetize_h264_nal( sout_stream_id_sys_t *id, const uint8_t *p_data, int i_data, int64_t i_pts, int64_t i_dts, bool b_last, int64_t i_length ) { const int i_max = rtp_mtu (id); /* payload max in one packet */ int i_nal_hdr; int i_nal_type; if( i_data < 5 ) return VLC_SUCCESS; i_nal_hdr = p_data[3]; i_nal_type = i_nal_hdr&0x1f; /* Skip start code */ p_data += 3; i_data -= 3; /* */ if( i_data <= i_max ) { /* Single NAL unit packet */ block_t *out = block_Alloc( 12 + i_data ); out->i_dts = i_dts; out->i_length = i_length; /* */ rtp_packetize_common( id, out, b_last, i_pts ); memcpy( &out->p_buffer[12], p_data, i_data ); rtp_packetize_send( id, out ); } else { /* FU-A Fragmentation Unit without interleaving */ const int i_count = ( i_data-1 + i_max-2 - 1 ) / (i_max-2); int i; p_data++; i_data--; for( i = 0; i < i_count; i++ ) { const int i_payload = __MIN( i_data, i_max-2 ); block_t *out = block_Alloc( 12 + 2 + i_payload ); out->i_dts = i_dts + i * i_length / i_count; out->i_length = i_length / i_count; /* */ rtp_packetize_common( id, out, (b_last && i_payload == i_data), i_pts ); /* FU indicator */ out->p_buffer[12] = 0x00 | (i_nal_hdr & 0x60) | 28; /* FU header */ out->p_buffer[13] = ( i == 0 ? 0x80 : 0x00 ) | ( (i == i_count-1) ? 0x40 : 0x00 ) | i_nal_type; memcpy( &out->p_buffer[14], p_data, i_payload ); rtp_packetize_send( id, out ); i_data -= i_payload; p_data += i_payload; } } return VLC_SUCCESS; } static int rtp_packetize_h264( sout_stream_id_sys_t *id, block_t *in ) { const uint8_t *p_buffer = in->p_buffer; int i_buffer = in->i_buffer; while( i_buffer > 4 && ( p_buffer[0] != 0 || p_buffer[1] != 0 || p_buffer[2] != 1 ) ) { i_buffer--; p_buffer++; } /* Split nal units */ while( i_buffer > 4 ) { int i_offset; int i_size = i_buffer; int i_skip = i_buffer; /* search nal end */ for( i_offset = 4; i_offset+2 < i_buffer ; i_offset++) { if( p_buffer[i_offset] == 0 && p_buffer[i_offset+1] == 0 && p_buffer[i_offset+2] == 1 ) { /* we found another startcode */ i_size = i_offset - ( p_buffer[i_offset-1] == 0 ? 1 : 0); i_skip = i_offset; break; } } /* TODO add STAP-A to remove a lot of overhead with small slice/sei/... */ rtp_packetize_h264_nal( id, p_buffer, i_size, (in->i_pts > VLC_TS_INVALID ? in->i_pts : in->i_dts), in->i_dts, (i_size >= i_buffer), in->i_length * i_size / in->i_buffer ); i_buffer -= i_skip; p_buffer += i_skip; } block_Release(in); return VLC_SUCCESS; } static int rtp_packetize_amr( sout_stream_id_sys_t *id, block_t *in ) { int i_max = rtp_mtu (id) - 2; /* payload max in one packet */ int i_count = ( in->i_buffer + i_max - 1 ) / i_max; uint8_t *p_data = in->p_buffer; int i_data = in->i_buffer; int i; /* Only supports octet-aligned mode */ for( i = 0; i < i_count; i++ ) { int i_payload = __MIN( i_max, i_data ); block_t *out = block_Alloc( 14 + i_payload ); /* rtp common header */ rtp_packetize_common( id, out, ((i == i_count - 1)?1:0), (in->i_pts > VLC_TS_INVALID ? in->i_pts : in->i_dts) ); /* Payload header */ out->p_buffer[12] = 0xF0; /* CMR */ out->p_buffer[13] = p_data[0]&0x7C; /* ToC */ /* FIXME: frame type */ /* FIXME: are we fed multiple frames ? */ memcpy( &out->p_buffer[14], p_data+1, i_payload-1 ); out->i_buffer--; /* FIXME? */ out->i_dts = in->i_dts + i * in->i_length / i_count; out->i_length = in->i_length / i_count; rtp_packetize_send( id, out ); p_data += i_payload; i_data -= i_payload; } block_Release(in); return VLC_SUCCESS; } static int rtp_packetize_t140( sout_stream_id_sys_t *id, block_t *in ) { const size_t i_max = rtp_mtu (id); const uint8_t *p_data = in->p_buffer; size_t i_data = in->i_buffer; for( unsigned i_packet = 0; i_data > 0; i_packet++ ) { size_t i_payload = i_data; /* Make sure we stop on an UTF-8 character boundary * (assuming the input is valid UTF-8) */ if( i_data > i_max ) { i_payload = i_max; while( ( p_data[i_payload] & 0xC0 ) == 0x80 ) { if( i_payload == 0 ) { block_Release(in); return VLC_SUCCESS; /* fishy input! */ } i_payload--; } } block_t *out = block_Alloc( 12 + i_payload ); if( out == NULL ) { block_Release(in); return VLC_SUCCESS; } rtp_packetize_common( id, out, 0, in->i_pts + i_packet ); memcpy( out->p_buffer + 12, p_data, i_payload ); out->i_dts = in->i_pts; out->i_length = 0; rtp_packetize_send( id, out ); p_data += i_payload; i_data -= i_payload; } block_Release(in); return VLC_SUCCESS; } static int rtp_packetize_spx( sout_stream_id_sys_t *id, block_t *in ) { uint8_t *p_buffer = in->p_buffer; int i_data_size, i_payload_size, i_payload_padding; i_data_size = i_payload_size = in->i_buffer; i_payload_padding = 0; block_t *p_out; if ( in->i_buffer > rtp_mtu (id) ) { block_Release(in); return VLC_SUCCESS; } /* RFC for Speex in RTP says that each packet must end on an octet boundary. So, we check to see if the number of bytes % 4 is zero. If not, we have to add some padding. This MAY be overkill since packetization is handled elsewhere and appears to ensure the octet boundary. However, better safe than sorry. */ if ( i_payload_size % 4 ) { i_payload_padding = 4 - ( i_payload_size % 4 ); i_payload_size += i_payload_padding; } /* Allocate a new RTP p_output block of the appropriate size. Allow for 12 extra bytes of RTP header. */ p_out = block_Alloc( 12 + i_payload_size ); if ( i_payload_padding ) { /* The padding is required to be a zero followed by all 1s. */ char c_first_pad, c_remaining_pad; c_first_pad = 0x7F; c_remaining_pad = 0xFF; /* Allow for 12 bytes before the i_data_size because of the expected RTP header added during rtp_packetize_common. */ p_out->p_buffer[12 + i_data_size] = c_first_pad; switch (i_payload_padding) { case 2: p_out->p_buffer[12 + i_data_size + 1] = c_remaining_pad; break; case 3: p_out->p_buffer[12 + i_data_size + 1] = c_remaining_pad; p_out->p_buffer[12 + i_data_size + 2] = c_remaining_pad; break; } } /* Add the RTP header to our p_output buffer. */ rtp_packetize_common( id, p_out, 0, (in->i_pts > VLC_TS_INVALID ? in->i_pts : in->i_dts) ); /* Copy the Speex payload to the p_output buffer */ memcpy( &p_out->p_buffer[12], p_buffer, i_data_size ); p_out->i_dts = in->i_dts; p_out->i_length = in->i_length; block_Release(in); /* Queue the buffer for actual transmission. */ rtp_packetize_send( id, p_out ); return VLC_SUCCESS; } static int rtp_packetize_g726( sout_stream_id_sys_t *id, block_t *in, int i_pad ) { int i_max = (rtp_mtu( id )- 12 + i_pad - 1) & ~i_pad; int i_count = ( in->i_buffer + i_max - 1 ) / i_max; uint8_t *p_data = in->p_buffer; int i_data = in->i_buffer; int i_packet = 0; while( i_data > 0 ) { int i_payload = __MIN( i_max, i_data ); block_t *out = block_Alloc( 12 + i_payload ); /* rtp common header */ rtp_packetize_common( id, out, 0, (in->i_pts > VLC_TS_INVALID ? in->i_pts : in->i_dts) ); memcpy( &out->p_buffer[12], p_data, i_payload ); out->i_dts = in->i_dts + i_packet++ * in->i_length / i_count; out->i_length = in->i_length / i_count; rtp_packetize_send( id, out ); p_data += i_payload; i_data -= i_payload; } block_Release(in); return VLC_SUCCESS; } static int rtp_packetize_g726_16( sout_stream_id_sys_t *id, block_t *in ) { return rtp_packetize_g726( id, in, 4 ); } static int rtp_packetize_g726_24( sout_stream_id_sys_t *id, block_t *in ) { return rtp_packetize_g726( id, in, 8 ); } static int rtp_packetize_g726_32( sout_stream_id_sys_t *id, block_t *in ) { return rtp_packetize_g726( id, in, 2 ); } static int rtp_packetize_g726_40( sout_stream_id_sys_t *id, block_t *in ) { return rtp_packetize_g726( id, in, 8 ); } #define RTP_VP8_HEADER_SIZE 1 #define RTP_VP8_PAYLOAD_START (12 + RTP_VP8_HEADER_SIZE) static int rtp_packetize_vp8( sout_stream_id_sys_t *id, block_t *in ) { int i_max = rtp_mtu (id) - RTP_VP8_HEADER_SIZE; int i_count = ( in->i_buffer + i_max - 1 ) / i_max; uint8_t *p_data = in->p_buffer; int i_data = in->i_buffer; if ( i_max <= 0 ) { block_Release(in); return VLC_EGENERIC; } for( int i = 0; i < i_count; i++ ) { int i_payload = __MIN( i_max, i_data ); block_t *out = block_Alloc( RTP_VP8_PAYLOAD_START + i_payload ); if ( out == NULL ) { block_Release(in); return VLC_ENOMEM; } /* VP8 payload header */ /* All frames are marked as reference ones */ if (i == 0) out->p_buffer[12] = 0x10; // partition start else out->p_buffer[12] = 0; /* rtp common header */ rtp_packetize_common( id, out, (i == i_count - 1), (in->i_pts > VLC_TS_INVALID ? in->i_pts : in->i_dts) ); memcpy( &out->p_buffer[RTP_VP8_PAYLOAD_START], p_data, i_payload ); out->i_dts = in->i_dts + i * in->i_length / i_count; out->i_length = in->i_length / i_count; rtp_packetize_send( id, out ); p_data += i_payload; i_data -= i_payload; } block_Release(in); return VLC_SUCCESS; } static int rtp_packetize_jpeg( sout_stream_id_sys_t *id, block_t *in ) { uint8_t *p_data = in->p_buffer; int i_data = in->i_buffer; uint8_t *bufend = p_data + i_data; const uint8_t *qtables = NULL; int nb_qtables = 0; int off = 0; // fragment offset in frame int y_sampling_factor; // type is set by pixel format (determined by y_sampling_factor): // 0 for yuvj422p // 1 for yuvj420p // += 64 if DRI present int type; int w = 0; // Width in multiples of 8 int h = 0; // Height in multiples of 8 int restart_interval; int dri_found = 0; // Skip SOI if (GetWBE(p_data) != 0xffd8) goto error; p_data += 2; i_data -= 2; /* parse the header to get necessary info */ int header_finished = 0; while (!header_finished && p_data + 4 <= bufend) { uint16_t marker = GetWBE(p_data); uint8_t *section = p_data + 2; int section_size = GetWBE(section); uint8_t *section_body = p_data + 4; if (section + section_size > bufend) goto error; assert((marker & 0xff00) == 0xff00); switch (marker) { case 0xffdb /*DQT*/: if (section_body[0]) goto error; // Only 8-bit precision is supported /* a quantization table is 64 bytes long */ nb_qtables = section_size / 65; qtables = section_body; break; case 0xffc0 /*SOF0*/: { int height = GetWBE(&section_body[1]); int width = GetWBE(&section_body[3]); if (width > 2040 || height > 2040) { // larger than limit supported by RFC 2435 goto error; } // Round up by 8, divide by 8 w = ((width+7)&~7) >> 3; h = ((height+7)&~7) >> 3; // Get components sampling to determine type // Y has component ID 1 // Possible configurations of sampling factors: // Y - 0x22, Cb - 0x11, Cr - 0x11 => yuvj420p // Y - 0x21, Cb - 0x11, Cr - 0x11 => yuvj422p // Only 3 components are supported by RFC 2435 if (section_body[5] != 3) // Number of components goto error; for (int j = 0; j < 3; j++) { if (section_body[6 + j * 3] == 1 /* Y */) { y_sampling_factor = section_body[6 + j * 3 + 1]; } else if (section_body[6 + j * 3 + 1] != 0x11) { // Sampling factor is unsupported by RFC 2435 goto error; } } break; } case 0xffdd /*DRI*/: restart_interval = GetWBE(section_body); dri_found = 1; break; case 0xffda /*SOS*/: /* SOS is last marker in the header */ header_finished = 1; break; } // Step over marker, 16bit length and section body p_data += 2 + section_size; i_data -= 2 + section_size; } if (!header_finished) goto error; if (!w || !h) goto error; switch (y_sampling_factor) { case 0x22: // yuvj420p type = 1; break; case 0x21: // yuvj422p type = 0; break; default: goto error; // Sampling format unsupported by RFC 2435 } if (dri_found) type += 64; while ( i_data ) { int hdr_size = 8 + dri_found * 4; if (off == 0 && nb_qtables) hdr_size += 4 + 64 * nb_qtables; int i_payload = __MIN( i_data, (int)(rtp_mtu (id) - hdr_size) ); if ( i_payload <= 0 ) return VLC_EGENERIC; block_t *out = block_Alloc( 12 + hdr_size + i_payload ); if( out == NULL ) return VLC_ENOMEM; uint8_t *p = out->p_buffer + 12; /* set main header */ /* set type-specific=0, set offset in following 24 bits: */ SetDWBE(p, off & 0x00ffffff); p += 4; *p++ = type; *p++ = 255; // Quant value *p++ = w; *p++ = h; // Write restart_marker_hdr if needed if (dri_found) { SetWBE(p, restart_interval); p += 2; // restart_count. Hardcoded same value as in gstreamer implementation SetWBE(p, 0xffff); p += 2; } if (off == 0 && nb_qtables) { /* set quantization tables header */ *p++ = 0; *p++ = 0; SetWBE (p, 64 * nb_qtables); p += 2; for (int i = 0; i < nb_qtables; i++) { memcpy (p, &qtables[65 * i + 1], 64); p += 64; } } /* rtp common header */ rtp_packetize_common( id, out, (i_payload == i_data), (in->i_pts > VLC_TS_INVALID ? in->i_pts : in->i_dts) ); memcpy( p, p_data, i_payload ); out->i_dts = in->i_dts; out->i_length = in->i_length; rtp_packetize_send( id, out ); p_data += i_payload; i_data -= i_payload; off += i_payload; } block_Release(in); return VLC_SUCCESS; error: block_Release(in); return VLC_EGENERIC; }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_2397_0
crossvul-cpp_data_bad_672_0
/** * FreeRDP: A Remote Desktop Protocol Implementation * Update Data PDUs * * Copyright 2011 Marc-Andre Moreau <marcandre.moreau@gmail.com> * Copyright 2016 Armin Novak <armin.novak@thincast.com> * Copyright 2016 Thincast Technologies GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <winpr/crt.h> #include <winpr/print.h> #include <winpr/synch.h> #include <winpr/thread.h> #include <winpr/collections.h> #include "update.h" #include "surface.h" #include "message.h" #include "info.h" #include "window.h" #include <freerdp/log.h> #include <freerdp/peer.h> #include <freerdp/codec/bitmap.h> #include "../cache/pointer.h" #include "../cache/palette.h" #include "../cache/bitmap.h" #define TAG FREERDP_TAG("core.update") static const char* const UPDATE_TYPE_STRINGS[] = { "Orders", "Bitmap", "Palette", "Synchronize" }; static const char* update_type_to_string(UINT16 updateType) { if (updateType >= ARRAYSIZE(UPDATE_TYPE_STRINGS)) return "UNKNOWN"; return UPDATE_TYPE_STRINGS[updateType]; } static BOOL update_recv_orders(rdpUpdate* update, wStream* s) { UINT16 numberOrders; if (Stream_GetRemainingLength(s) < 6) { WLog_ERR(TAG, "Stream_GetRemainingLength(s) < 6"); return FALSE; } Stream_Seek_UINT16(s); /* pad2OctetsA (2 bytes) */ Stream_Read_UINT16(s, numberOrders); /* numberOrders (2 bytes) */ Stream_Seek_UINT16(s); /* pad2OctetsB (2 bytes) */ while (numberOrders > 0) { if (!update_recv_order(update, s)) { WLog_ERR(TAG, "update_recv_order() failed"); return FALSE; } numberOrders--; } return TRUE; } static BOOL update_read_bitmap_data(rdpUpdate* update, wStream* s, BITMAP_DATA* bitmapData) { if (Stream_GetRemainingLength(s) < 18) return FALSE; Stream_Read_UINT16(s, bitmapData->destLeft); Stream_Read_UINT16(s, bitmapData->destTop); Stream_Read_UINT16(s, bitmapData->destRight); Stream_Read_UINT16(s, bitmapData->destBottom); Stream_Read_UINT16(s, bitmapData->width); Stream_Read_UINT16(s, bitmapData->height); Stream_Read_UINT16(s, bitmapData->bitsPerPixel); Stream_Read_UINT16(s, bitmapData->flags); Stream_Read_UINT16(s, bitmapData->bitmapLength); if (bitmapData->flags & BITMAP_COMPRESSION) { if (!(bitmapData->flags & NO_BITMAP_COMPRESSION_HDR)) { Stream_Read_UINT16(s, bitmapData->cbCompFirstRowSize); /* cbCompFirstRowSize (2 bytes) */ Stream_Read_UINT16(s, bitmapData->cbCompMainBodySize); /* cbCompMainBodySize (2 bytes) */ Stream_Read_UINT16(s, bitmapData->cbScanWidth); /* cbScanWidth (2 bytes) */ Stream_Read_UINT16(s, bitmapData->cbUncompressedSize); /* cbUncompressedSize (2 bytes) */ bitmapData->bitmapLength = bitmapData->cbCompMainBodySize; } bitmapData->compressed = TRUE; } else bitmapData->compressed = FALSE; if (Stream_GetRemainingLength(s) < bitmapData->bitmapLength) return FALSE; if (bitmapData->bitmapLength > 0) { bitmapData->bitmapDataStream = malloc(bitmapData->bitmapLength); if (!bitmapData->bitmapDataStream) return FALSE; memcpy(bitmapData->bitmapDataStream, Stream_Pointer(s), bitmapData->bitmapLength); Stream_Seek(s, bitmapData->bitmapLength); } return TRUE; } static BOOL update_write_bitmap_data(rdpUpdate* update, wStream* s, BITMAP_DATA* bitmapData) { if (!Stream_EnsureRemainingCapacity(s, 64 + bitmapData->bitmapLength)) return FALSE; bitmapData->flags = 0; bitmapData->cbCompFirstRowSize = 0; if (bitmapData->compressed) bitmapData->flags |= BITMAP_COMPRESSION; if (update->context->settings->NoBitmapCompressionHeader) { bitmapData->flags |= NO_BITMAP_COMPRESSION_HDR; bitmapData->cbCompMainBodySize = bitmapData->bitmapLength; } Stream_Write_UINT16(s, bitmapData->destLeft); Stream_Write_UINT16(s, bitmapData->destTop); Stream_Write_UINT16(s, bitmapData->destRight); Stream_Write_UINT16(s, bitmapData->destBottom); Stream_Write_UINT16(s, bitmapData->width); Stream_Write_UINT16(s, bitmapData->height); Stream_Write_UINT16(s, bitmapData->bitsPerPixel); Stream_Write_UINT16(s, bitmapData->flags); Stream_Write_UINT16(s, bitmapData->bitmapLength); if (bitmapData->flags & BITMAP_COMPRESSION) { if (!(bitmapData->flags & NO_BITMAP_COMPRESSION_HDR)) { Stream_Write_UINT16(s, bitmapData->cbCompFirstRowSize); /* cbCompFirstRowSize (2 bytes) */ Stream_Write_UINT16(s, bitmapData->cbCompMainBodySize); /* cbCompMainBodySize (2 bytes) */ Stream_Write_UINT16(s, bitmapData->cbScanWidth); /* cbScanWidth (2 bytes) */ Stream_Write_UINT16(s, bitmapData->cbUncompressedSize); /* cbUncompressedSize (2 bytes) */ } Stream_Write(s, bitmapData->bitmapDataStream, bitmapData->bitmapLength); } else { Stream_Write(s, bitmapData->bitmapDataStream, bitmapData->bitmapLength); } return TRUE; } BITMAP_UPDATE* update_read_bitmap_update(rdpUpdate* update, wStream* s) { UINT32 i; BITMAP_UPDATE* bitmapUpdate = calloc(1, sizeof(BITMAP_UPDATE)); if (!bitmapUpdate) goto fail; if (Stream_GetRemainingLength(s) < 2) goto fail; Stream_Read_UINT16(s, bitmapUpdate->number); /* numberRectangles (2 bytes) */ WLog_Print(update->log, WLOG_TRACE, "BitmapUpdate: %"PRIu32"", bitmapUpdate->number); if (bitmapUpdate->number > bitmapUpdate->count) { UINT16 count; BITMAP_DATA* newdata; count = bitmapUpdate->number * 2; newdata = (BITMAP_DATA*) realloc(bitmapUpdate->rectangles, sizeof(BITMAP_DATA) * count); if (!newdata) goto fail; bitmapUpdate->rectangles = newdata; ZeroMemory(&bitmapUpdate->rectangles[bitmapUpdate->count], sizeof(BITMAP_DATA) * (count - bitmapUpdate->count)); bitmapUpdate->count = count; } /* rectangles */ for (i = 0; i < bitmapUpdate->number; i++) { if (!update_read_bitmap_data(update, s, &bitmapUpdate->rectangles[i])) goto fail; } return bitmapUpdate; fail: free_bitmap_update(update->context, bitmapUpdate); return NULL; } static BOOL update_write_bitmap_update(rdpUpdate* update, wStream* s, const BITMAP_UPDATE* bitmapUpdate) { int i; if (!Stream_EnsureRemainingCapacity(s, 32)) return FALSE; Stream_Write_UINT16(s, UPDATE_TYPE_BITMAP); /* updateType */ Stream_Write_UINT16(s, bitmapUpdate->number); /* numberRectangles (2 bytes) */ /* rectangles */ for (i = 0; i < (int) bitmapUpdate->number; i++) { if (!update_write_bitmap_data(update, s, &bitmapUpdate->rectangles[i])) return FALSE; } return TRUE; } PALETTE_UPDATE* update_read_palette(rdpUpdate* update, wStream* s) { int i; PALETTE_ENTRY* entry; PALETTE_UPDATE* palette_update = calloc(1, sizeof(PALETTE_UPDATE)); if (!palette_update) goto fail; if (Stream_GetRemainingLength(s) < 6) goto fail; Stream_Seek_UINT16(s); /* pad2Octets (2 bytes) */ Stream_Read_UINT32(s, palette_update->number); /* numberColors (4 bytes), must be set to 256 */ if (palette_update->number > 256) palette_update->number = 256; if (Stream_GetRemainingLength(s) < palette_update->number * 3) goto fail; /* paletteEntries */ for (i = 0; i < (int) palette_update->number; i++) { entry = &palette_update->entries[i]; Stream_Read_UINT8(s, entry->red); Stream_Read_UINT8(s, entry->green); Stream_Read_UINT8(s, entry->blue); } return palette_update; fail: free_palette_update(update->context, palette_update); return NULL; } static void update_read_synchronize(rdpUpdate* update, wStream* s) { Stream_Seek_UINT16(s); /* pad2Octets (2 bytes) */ /** * The Synchronize Update is an artifact from the * T.128 protocol and should be ignored. */ } static BOOL update_read_play_sound(wStream* s, PLAY_SOUND_UPDATE* play_sound) { if (Stream_GetRemainingLength(s) < 8) return FALSE; Stream_Read_UINT32(s, play_sound->duration); /* duration (4 bytes) */ Stream_Read_UINT32(s, play_sound->frequency); /* frequency (4 bytes) */ return TRUE; } BOOL update_recv_play_sound(rdpUpdate* update, wStream* s) { PLAY_SOUND_UPDATE play_sound; if (!update_read_play_sound(s, &play_sound)) return FALSE; return IFCALLRESULT(FALSE, update->PlaySound, update->context, &play_sound); } POINTER_POSITION_UPDATE* update_read_pointer_position(rdpUpdate* update, wStream* s) { POINTER_POSITION_UPDATE* pointer_position = calloc(1, sizeof(POINTER_POSITION_UPDATE)); if (!pointer_position) goto fail; if (Stream_GetRemainingLength(s) < 4) goto fail; Stream_Read_UINT16(s, pointer_position->xPos); /* xPos (2 bytes) */ Stream_Read_UINT16(s, pointer_position->yPos); /* yPos (2 bytes) */ return pointer_position; fail: free_pointer_position_update(update->context, pointer_position); return NULL; } POINTER_SYSTEM_UPDATE* update_read_pointer_system(rdpUpdate* update, wStream* s) { POINTER_SYSTEM_UPDATE* pointer_system = calloc(1, sizeof(POINTER_SYSTEM_UPDATE)); if (!pointer_system) goto fail; if (Stream_GetRemainingLength(s) < 4) goto fail; Stream_Read_UINT32(s, pointer_system->type); /* systemPointerType (4 bytes) */ return pointer_system; fail: free_pointer_system_update(update->context, pointer_system); return NULL; } static BOOL _update_read_pointer_color(wStream* s, POINTER_COLOR_UPDATE* pointer_color, BYTE xorBpp) { BYTE* newMask; UINT32 scanlineSize; if (!pointer_color) goto fail; if (Stream_GetRemainingLength(s) < 14) goto fail; Stream_Read_UINT16(s, pointer_color->cacheIndex); /* cacheIndex (2 bytes) */ Stream_Read_UINT16(s, pointer_color->xPos); /* xPos (2 bytes) */ Stream_Read_UINT16(s, pointer_color->yPos); /* yPos (2 bytes) */ /** * As stated in 2.2.9.1.1.4.4 Color Pointer Update: * The maximum allowed pointer width/height is 96 pixels if the client indicated support * for large pointers by setting the LARGE_POINTER_FLAG (0x00000001) in the Large * Pointer Capability Set (section 2.2.7.2.7). If the LARGE_POINTER_FLAG was not * set, the maximum allowed pointer width/height is 32 pixels. * * So we check for a maximum of 96 for CVE-2014-0250. */ Stream_Read_UINT16(s, pointer_color->width); /* width (2 bytes) */ Stream_Read_UINT16(s, pointer_color->height); /* height (2 bytes) */ if ((pointer_color->width > 96) || (pointer_color->height > 96)) goto fail; Stream_Read_UINT16(s, pointer_color->lengthAndMask); /* lengthAndMask (2 bytes) */ Stream_Read_UINT16(s, pointer_color->lengthXorMask); /* lengthXorMask (2 bytes) */ /** * There does not seem to be any documentation on why * xPos / yPos can be larger than width / height * so it is missing in documentation or a bug in implementation * 2.2.9.1.1.4.4 Color Pointer Update (TS_COLORPOINTERATTRIBUTE) */ if (pointer_color->xPos >= pointer_color->width) pointer_color->xPos = 0; if (pointer_color->yPos >= pointer_color->height) pointer_color->yPos = 0; if (pointer_color->lengthXorMask > 0) { /** * Spec states that: * * xorMaskData (variable): A variable-length array of bytes. Contains the 24-bpp, bottom-up * XOR mask scan-line data. The XOR mask is padded to a 2-byte boundary for each encoded * scan-line. For example, if a 3x3 pixel cursor is being sent, then each scan-line will consume 10 * bytes (3 pixels per scan-line multiplied by 3 bytes per pixel, rounded up to the next even * number of bytes). * * In fact instead of 24-bpp, the bpp parameter is given by the containing packet. */ if (Stream_GetRemainingLength(s) < pointer_color->lengthXorMask) goto fail; scanlineSize = (7 + xorBpp * pointer_color->width) / 8; scanlineSize = ((scanlineSize + 1) / 2) * 2; if (scanlineSize * pointer_color->height != pointer_color->lengthXorMask) { WLog_ERR(TAG, "invalid lengthXorMask: width=%"PRIu32" height=%"PRIu32", %"PRIu32" instead of %"PRIu32"", pointer_color->width, pointer_color->height, pointer_color->lengthXorMask, scanlineSize * pointer_color->height); goto fail; } newMask = realloc(pointer_color->xorMaskData, pointer_color->lengthXorMask); if (!newMask) goto fail; pointer_color->xorMaskData = newMask; Stream_Read(s, pointer_color->xorMaskData, pointer_color->lengthXorMask); } if (pointer_color->lengthAndMask > 0) { /** * andMaskData (variable): A variable-length array of bytes. Contains the 1-bpp, bottom-up * AND mask scan-line data. The AND mask is padded to a 2-byte boundary for each encoded * scan-line. For example, if a 7x7 pixel cursor is being sent, then each scan-line will consume 2 * bytes (7 pixels per scan-line multiplied by 1 bpp, rounded up to the next even number of * bytes). */ if (Stream_GetRemainingLength(s) < pointer_color->lengthAndMask) goto fail; scanlineSize = ((7 + pointer_color->width) / 8); scanlineSize = ((1 + scanlineSize) / 2) * 2; if (scanlineSize * pointer_color->height != pointer_color->lengthAndMask) { WLog_ERR(TAG, "invalid lengthAndMask: %"PRIu32" instead of %"PRIu32"", pointer_color->lengthAndMask, scanlineSize * pointer_color->height); goto fail; } newMask = realloc(pointer_color->andMaskData, pointer_color->lengthAndMask); if (!newMask) goto fail; pointer_color->andMaskData = newMask; Stream_Read(s, pointer_color->andMaskData, pointer_color->lengthAndMask); } if (Stream_GetRemainingLength(s) > 0) Stream_Seek_UINT8(s); /* pad (1 byte) */ return TRUE; fail: return FALSE; } POINTER_COLOR_UPDATE* update_read_pointer_color(rdpUpdate* update, wStream* s, BYTE xorBpp) { POINTER_COLOR_UPDATE* pointer_color = calloc(1, sizeof(POINTER_COLOR_UPDATE)); if (!pointer_color) goto fail; if (!_update_read_pointer_color(s, pointer_color, xorBpp)) goto fail; return pointer_color; fail: free_pointer_color_update(update->context, pointer_color); return NULL; } POINTER_NEW_UPDATE* update_read_pointer_new(rdpUpdate* update, wStream* s) { POINTER_NEW_UPDATE* pointer_new = calloc(1, sizeof(POINTER_NEW_UPDATE)); if (!pointer_new) goto fail; if (Stream_GetRemainingLength(s) < 2) goto fail; Stream_Read_UINT16(s, pointer_new->xorBpp); /* xorBpp (2 bytes) */ if ((pointer_new->xorBpp < 1) || (pointer_new->xorBpp > 32)) { WLog_ERR(TAG, "invalid xorBpp %"PRIu32"", pointer_new->xorBpp); goto fail; } if (!_update_read_pointer_color(s, &pointer_new->colorPtrAttr, pointer_new->xorBpp)) /* colorPtrAttr */ goto fail; return pointer_new; fail: free_pointer_new_update(update->context, pointer_new); return NULL; } POINTER_CACHED_UPDATE* update_read_pointer_cached(rdpUpdate* update, wStream* s) { POINTER_CACHED_UPDATE* pointer = calloc(1, sizeof(POINTER_CACHED_UPDATE)); if (!pointer) goto fail; if (Stream_GetRemainingLength(s) < 2) goto fail; Stream_Read_UINT16(s, pointer->cacheIndex); /* cacheIndex (2 bytes) */ return pointer; fail: free_pointer_cached_update(update->context, pointer); return NULL; } BOOL update_recv_pointer(rdpUpdate* update, wStream* s) { BOOL rc = FALSE; UINT16 messageType; rdpContext* context = update->context; rdpPointerUpdate* pointer = update->pointer; if (Stream_GetRemainingLength(s) < 2 + 2) return FALSE; Stream_Read_UINT16(s, messageType); /* messageType (2 bytes) */ Stream_Seek_UINT16(s); /* pad2Octets (2 bytes) */ switch (messageType) { case PTR_MSG_TYPE_POSITION: { POINTER_POSITION_UPDATE* pointer_position = update_read_pointer_position(update, s); if (pointer_position) { rc = IFCALLRESULT(FALSE, pointer->PointerPosition, context, pointer_position); free_pointer_position_update(context, pointer_position); } } break; case PTR_MSG_TYPE_SYSTEM: { POINTER_SYSTEM_UPDATE* pointer_system = update_read_pointer_system(update, s); if (pointer_system) { rc = IFCALLRESULT(FALSE, pointer->PointerSystem, context, pointer_system); free_pointer_system_update(context, pointer_system); } } break; case PTR_MSG_TYPE_COLOR: { POINTER_COLOR_UPDATE* pointer_color = update_read_pointer_color(update, s, 24); if (pointer_color) { rc = IFCALLRESULT(FALSE, pointer->PointerColor, context, pointer_color); free_pointer_color_update(context, pointer_color); } } break; case PTR_MSG_TYPE_POINTER: { POINTER_NEW_UPDATE* pointer_new = update_read_pointer_new(update, s); if (pointer_new) { rc = IFCALLRESULT(FALSE, pointer->PointerNew, context, pointer_new); free_pointer_new_update(context, pointer_new); } } break; case PTR_MSG_TYPE_CACHED: { POINTER_CACHED_UPDATE* pointer_cached = update_read_pointer_cached(update, s); if (pointer_cached) { rc = IFCALLRESULT(FALSE, pointer->PointerCached, context, pointer_cached); free_pointer_cached_update(context, pointer_cached); } } break; default: break; } return rc; } BOOL update_recv(rdpUpdate* update, wStream* s) { BOOL rc = FALSE; UINT16 updateType; rdpContext* context = update->context; if (Stream_GetRemainingLength(s) < 2) { WLog_ERR(TAG, "Stream_GetRemainingLength(s) < 2"); return FALSE; } Stream_Read_UINT16(s, updateType); /* updateType (2 bytes) */ WLog_Print(update->log, WLOG_TRACE, "%s Update Data PDU", UPDATE_TYPE_STRINGS[updateType]); if (!IFCALLRESULT(TRUE, update->BeginPaint, context)) return FALSE; switch (updateType) { case UPDATE_TYPE_ORDERS: rc = update_recv_orders(update, s); break; case UPDATE_TYPE_BITMAP: { BITMAP_UPDATE* bitmap_update = update_read_bitmap_update(update, s); if (!bitmap_update) { WLog_ERR(TAG, "UPDATE_TYPE_BITMAP - update_read_bitmap_update() failed"); return FALSE; } rc = IFCALLRESULT(FALSE, update->BitmapUpdate, context, bitmap_update); free_bitmap_update(update->context, bitmap_update); } break; case UPDATE_TYPE_PALETTE: { PALETTE_UPDATE* palette_update = update_read_palette(update, s); if (!palette_update) { WLog_ERR(TAG, "UPDATE_TYPE_PALETTE - update_read_palette() failed"); return FALSE; } rc = IFCALLRESULT(FALSE, update->Palette, context, palette_update); free_palette_update(context, palette_update); } break; case UPDATE_TYPE_SYNCHRONIZE: update_read_synchronize(update, s); rc = IFCALLRESULT(TRUE, update->Synchronize, context); break; default: break; } if (!rc) { WLog_ERR(TAG, "UPDATE_TYPE %s [%"PRIu16"] failed", update_type_to_string(updateType), updateType); return FALSE; } if (!IFCALLRESULT(FALSE, update->EndPaint, context)) return FALSE; return TRUE; } void update_reset_state(rdpUpdate* update) { rdpPrimaryUpdate* primary = update->primary; rdpAltSecUpdate* altsec = update->altsec; if (primary->fast_glyph.glyphData.aj) { free(primary->fast_glyph.glyphData.aj); primary->fast_glyph.glyphData.aj = NULL; } ZeroMemory(&primary->order_info, sizeof(ORDER_INFO)); ZeroMemory(&primary->dstblt, sizeof(DSTBLT_ORDER)); ZeroMemory(&primary->patblt, sizeof(PATBLT_ORDER)); ZeroMemory(&primary->scrblt, sizeof(SCRBLT_ORDER)); ZeroMemory(&primary->opaque_rect, sizeof(OPAQUE_RECT_ORDER)); ZeroMemory(&primary->draw_nine_grid, sizeof(DRAW_NINE_GRID_ORDER)); ZeroMemory(&primary->multi_dstblt, sizeof(MULTI_DSTBLT_ORDER)); ZeroMemory(&primary->multi_patblt, sizeof(MULTI_PATBLT_ORDER)); ZeroMemory(&primary->multi_scrblt, sizeof(MULTI_SCRBLT_ORDER)); ZeroMemory(&primary->multi_opaque_rect, sizeof(MULTI_OPAQUE_RECT_ORDER)); ZeroMemory(&primary->multi_draw_nine_grid, sizeof(MULTI_DRAW_NINE_GRID_ORDER)); ZeroMemory(&primary->line_to, sizeof(LINE_TO_ORDER)); ZeroMemory(&primary->polyline, sizeof(POLYLINE_ORDER)); ZeroMemory(&primary->memblt, sizeof(MEMBLT_ORDER)); ZeroMemory(&primary->mem3blt, sizeof(MEM3BLT_ORDER)); ZeroMemory(&primary->save_bitmap, sizeof(SAVE_BITMAP_ORDER)); ZeroMemory(&primary->glyph_index, sizeof(GLYPH_INDEX_ORDER)); ZeroMemory(&primary->fast_index, sizeof(FAST_INDEX_ORDER)); ZeroMemory(&primary->fast_glyph, sizeof(FAST_GLYPH_ORDER)); ZeroMemory(&primary->polygon_sc, sizeof(POLYGON_SC_ORDER)); ZeroMemory(&primary->polygon_cb, sizeof(POLYGON_CB_ORDER)); ZeroMemory(&primary->ellipse_sc, sizeof(ELLIPSE_SC_ORDER)); ZeroMemory(&primary->ellipse_cb, sizeof(ELLIPSE_CB_ORDER)); primary->order_info.orderType = ORDER_TYPE_PATBLT; if (!update->initialState) { altsec->switch_surface.bitmapId = SCREEN_BITMAP_SURFACE; IFCALL(altsec->SwitchSurface, update->context, &(altsec->switch_surface)); } } BOOL update_post_connect(rdpUpdate* update) { update->asynchronous = update->context->settings->AsyncUpdate; if (update->asynchronous) if (!(update->proxy = update_message_proxy_new(update))) return FALSE; update->altsec->switch_surface.bitmapId = SCREEN_BITMAP_SURFACE; IFCALL(update->altsec->SwitchSurface, update->context, &(update->altsec->switch_surface)); update->initialState = FALSE; return TRUE; } void update_post_disconnect(rdpUpdate* update) { update->asynchronous = update->context->settings->AsyncUpdate; if (update->asynchronous) update_message_proxy_free(update->proxy); update->initialState = TRUE; } static BOOL update_begin_paint(rdpContext* context) { wStream* s; rdpUpdate* update = context->update; if (update->us) update->EndPaint(context); s = fastpath_update_pdu_init_new(context->rdp->fastpath); if (!s) return FALSE; Stream_SealLength(s); Stream_Seek(s, 2); /* numberOrders (2 bytes) */ update->combineUpdates = TRUE; update->numberOrders = 0; update->us = s; return TRUE; } static BOOL update_end_paint(rdpContext* context) { wStream* s; int headerLength; rdpUpdate* update = context->update; if (!update->us) return FALSE; s = update->us; headerLength = Stream_Length(s); Stream_SealLength(s); Stream_SetPosition(s, headerLength); Stream_Write_UINT16(s, update->numberOrders); /* numberOrders (2 bytes) */ Stream_SetPosition(s, Stream_Length(s)); if (update->numberOrders > 0) { WLog_ERR(TAG, "sending %"PRIu16" orders", update->numberOrders); fastpath_send_update_pdu(context->rdp->fastpath, FASTPATH_UPDATETYPE_ORDERS, s, FALSE); } update->combineUpdates = FALSE; update->numberOrders = 0; update->us = NULL; Stream_Free(s, TRUE); return TRUE; } static void update_flush(rdpContext* context) { rdpUpdate* update = context->update; if (update->numberOrders > 0) { update->EndPaint(context); update->BeginPaint(context); } } static void update_force_flush(rdpContext* context) { rdpUpdate* update = context->update; if (update->numberOrders > 0) { update->EndPaint(context); update->BeginPaint(context); } } static BOOL update_check_flush(rdpContext* context, int size) { wStream* s; rdpUpdate* update = context->update; s = update->us; if (!update->us) { update->BeginPaint(context); return FALSE; } if (Stream_GetPosition(s) + size + 64 >= 0x3FFF) { update_flush(context); return TRUE; } return FALSE; } static BOOL update_set_bounds(rdpContext* context, const rdpBounds* bounds) { rdpUpdate* update = context->update; CopyMemory(&update->previousBounds, &update->currentBounds, sizeof(rdpBounds)); if (!bounds) ZeroMemory(&update->currentBounds, sizeof(rdpBounds)); else CopyMemory(&update->currentBounds, bounds, sizeof(rdpBounds)); return TRUE; } BOOL update_bounds_is_null(rdpBounds* bounds) { if ((bounds->left == 0) && (bounds->top == 0) && (bounds->right == 0) && (bounds->bottom == 0)) return TRUE; return FALSE; } BOOL update_bounds_equals(rdpBounds* bounds1, rdpBounds* bounds2) { if ((bounds1->left == bounds2->left) && (bounds1->top == bounds2->top) && (bounds1->right == bounds2->right) && (bounds1->bottom == bounds2->bottom)) return TRUE; return FALSE; } int update_prepare_bounds(rdpContext* context, ORDER_INFO* orderInfo) { int length = 0; rdpUpdate* update = context->update; orderInfo->boundsFlags = 0; if (update_bounds_is_null(&update->currentBounds)) return 0; orderInfo->controlFlags |= ORDER_BOUNDS; if (update_bounds_equals(&update->previousBounds, &update->currentBounds)) { orderInfo->controlFlags |= ORDER_ZERO_BOUNDS_DELTAS; return 0; } else { length += 1; if (update->previousBounds.left != update->currentBounds.left) { orderInfo->bounds.left = update->currentBounds.left; orderInfo->boundsFlags |= BOUND_LEFT; length += 2; } if (update->previousBounds.top != update->currentBounds.top) { orderInfo->bounds.top = update->currentBounds.top; orderInfo->boundsFlags |= BOUND_TOP; length += 2; } if (update->previousBounds.right != update->currentBounds.right) { orderInfo->bounds.right = update->currentBounds.right; orderInfo->boundsFlags |= BOUND_RIGHT; length += 2; } if (update->previousBounds.bottom != update->currentBounds.bottom) { orderInfo->bounds.bottom = update->currentBounds.bottom; orderInfo->boundsFlags |= BOUND_BOTTOM; length += 2; } } return length; } static int update_prepare_order_info(rdpContext* context, ORDER_INFO* orderInfo, UINT32 orderType) { int length = 1; orderInfo->fieldFlags = 0; orderInfo->orderType = orderType; orderInfo->controlFlags = ORDER_STANDARD; orderInfo->controlFlags |= ORDER_TYPE_CHANGE; length += 1; length += PRIMARY_DRAWING_ORDER_FIELD_BYTES[orderInfo->orderType]; length += update_prepare_bounds(context, orderInfo); return length; } int update_write_order_info(rdpContext* context, wStream* s, ORDER_INFO* orderInfo, int offset) { size_t position; position = Stream_GetPosition(s); Stream_SetPosition(s, offset); Stream_Write_UINT8(s, orderInfo->controlFlags); /* controlFlags (1 byte) */ if (orderInfo->controlFlags & ORDER_TYPE_CHANGE) Stream_Write_UINT8(s, orderInfo->orderType); /* orderType (1 byte) */ update_write_field_flags(s, orderInfo->fieldFlags, orderInfo->controlFlags, PRIMARY_DRAWING_ORDER_FIELD_BYTES[orderInfo->orderType]); update_write_bounds(s, orderInfo); Stream_SetPosition(s, position); return 0; } static void update_write_refresh_rect(wStream* s, BYTE count, const RECTANGLE_16* areas) { int i; Stream_Write_UINT8(s, count); /* numberOfAreas (1 byte) */ Stream_Seek(s, 3); /* pad3Octets (3 bytes) */ for (i = 0; i < count; i++) { Stream_Write_UINT16(s, areas[i].left); /* left (2 bytes) */ Stream_Write_UINT16(s, areas[i].top); /* top (2 bytes) */ Stream_Write_UINT16(s, areas[i].right); /* right (2 bytes) */ Stream_Write_UINT16(s, areas[i].bottom); /* bottom (2 bytes) */ } } static BOOL update_send_refresh_rect(rdpContext* context, BYTE count, const RECTANGLE_16* areas) { rdpRdp* rdp = context->rdp; if (rdp->settings->RefreshRect) { wStream* s = rdp_data_pdu_init(rdp); if (!s) return FALSE; update_write_refresh_rect(s, count, areas); return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_REFRESH_RECT, rdp->mcs->userId); } return TRUE; } static void update_write_suppress_output(wStream* s, BYTE allow, const RECTANGLE_16* area) { Stream_Write_UINT8(s, allow); /* allowDisplayUpdates (1 byte) */ /* Use zeros for padding (like mstsc) for compatibility with legacy servers */ Stream_Zero(s, 3); /* pad3Octets (3 bytes) */ if (allow > 0) { Stream_Write_UINT16(s, area->left); /* left (2 bytes) */ Stream_Write_UINT16(s, area->top); /* top (2 bytes) */ Stream_Write_UINT16(s, area->right); /* right (2 bytes) */ Stream_Write_UINT16(s, area->bottom); /* bottom (2 bytes) */ } } static BOOL update_send_suppress_output(rdpContext* context, BYTE allow, const RECTANGLE_16* area) { rdpRdp* rdp = context->rdp; if (rdp->settings->SuppressOutput) { wStream* s = rdp_data_pdu_init(rdp); if (!s) return FALSE; update_write_suppress_output(s, allow, area); return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_SUPPRESS_OUTPUT, rdp->mcs->userId); } return TRUE; } static BOOL update_send_surface_command(rdpContext* context, wStream* s) { wStream* update; rdpRdp* rdp = context->rdp; BOOL ret; update = fastpath_update_pdu_init(rdp->fastpath); if (!update) return FALSE; if (!Stream_EnsureRemainingCapacity(update, Stream_GetPosition(s))) { ret = FALSE; goto out; } Stream_Write(update, Stream_Buffer(s), Stream_GetPosition(s)); ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_SURFCMDS, update, FALSE); out: Stream_Release(update); return ret; } static BOOL update_send_surface_bits(rdpContext* context, const SURFACE_BITS_COMMAND* surfaceBitsCommand) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; update_force_flush(context); s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!update_write_surfcmd_surface_bits(s, surfaceBitsCommand)) goto out_fail; if (!fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_SURFCMDS, s, surfaceBitsCommand->skipCompression)) goto out_fail; update_force_flush(context); ret = TRUE; out_fail: Stream_Release(s); return ret; } static BOOL update_send_surface_frame_marker(rdpContext* context, const SURFACE_FRAME_MARKER* surfaceFrameMarker) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; update_force_flush(context); s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!update_write_surfcmd_frame_marker(s, surfaceFrameMarker->frameAction, surfaceFrameMarker->frameId) || !fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_SURFCMDS, s, FALSE)) goto out_fail; update_force_flush(context); ret = TRUE; out_fail: Stream_Release(s); return ret; } static BOOL update_send_surface_frame_bits(rdpContext* context, const SURFACE_BITS_COMMAND* cmd, BOOL first, BOOL last, UINT32 frameId) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; update_force_flush(context); s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (first) { if (!update_write_surfcmd_frame_marker(s, SURFACECMD_FRAMEACTION_BEGIN, frameId)) goto out_fail; } if (!update_write_surfcmd_surface_bits(s, cmd)) goto out_fail; if (last) { if (!update_write_surfcmd_frame_marker(s, SURFACECMD_FRAMEACTION_END, frameId)) goto out_fail; } ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_SURFCMDS, s, cmd->skipCompression); update_force_flush(context); out_fail: Stream_Release(s); return ret; } static BOOL update_send_frame_acknowledge(rdpContext* context, UINT32 frameId) { rdpRdp* rdp = context->rdp; if (rdp->settings->ReceivedCapabilities[CAPSET_TYPE_FRAME_ACKNOWLEDGE]) { wStream* s = rdp_data_pdu_init(rdp); if (!s) return FALSE; Stream_Write_UINT32(s, frameId); return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_FRAME_ACKNOWLEDGE, rdp->mcs->userId); } return TRUE; } static BOOL update_send_synchronize(rdpContext* context) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; Stream_Zero(s, 2); /* pad2Octets (2 bytes) */ ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_SYNCHRONIZE, s, FALSE); Stream_Release(s); return ret; } static BOOL update_send_desktop_resize(rdpContext* context) { return rdp_server_reactivate(context->rdp); } static BOOL update_send_bitmap_update(rdpContext* context, const BITMAP_UPDATE* bitmapUpdate) { wStream* s; rdpRdp* rdp = context->rdp; rdpUpdate* update = context->update; BOOL ret = TRUE; update_force_flush(context); s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!update_write_bitmap_update(update, s, bitmapUpdate) || !fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_BITMAP, s, bitmapUpdate->skipCompression)) { ret = FALSE; goto out_fail; } update_force_flush(context); out_fail: Stream_Release(s); return ret; } static BOOL update_send_play_sound(rdpContext* context, const PLAY_SOUND_UPDATE* play_sound) { wStream* s; rdpRdp* rdp = context->rdp; if (!rdp->settings->ReceivedCapabilities[CAPSET_TYPE_SOUND]) { return TRUE; } s = rdp_data_pdu_init(rdp); if (!s) return FALSE; Stream_Write_UINT32(s, play_sound->duration); Stream_Write_UINT32(s, play_sound->frequency); return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_PLAY_SOUND, rdp->mcs->userId); } /** * Primary Drawing Orders */ static BOOL update_send_dstblt(rdpContext* context, const DSTBLT_ORDER* dstblt) { wStream* s; UINT32 offset; UINT32 headerLength; ORDER_INFO orderInfo; int inf; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_DSTBLT); inf = update_approximate_dstblt_order(&orderInfo, dstblt); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_dstblt_order(s, &orderInfo, dstblt)) return FALSE; update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_patblt(rdpContext* context, PATBLT_ORDER* patblt) { wStream* s; size_t offset; int headerLength; ORDER_INFO orderInfo; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_PATBLT); update_check_flush(context, headerLength + update_approximate_patblt_order(&orderInfo, patblt)); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_patblt_order(s, &orderInfo, patblt); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_scrblt(rdpContext* context, const SCRBLT_ORDER* scrblt) { wStream* s; UINT32 offset; UINT32 headerLength; ORDER_INFO orderInfo; int inf; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_SCRBLT); inf = update_approximate_scrblt_order(&orderInfo, scrblt); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return TRUE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_scrblt_order(s, &orderInfo, scrblt); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_opaque_rect(rdpContext* context, const OPAQUE_RECT_ORDER* opaque_rect) { wStream* s; size_t offset; int headerLength; ORDER_INFO orderInfo; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_OPAQUE_RECT); update_check_flush(context, headerLength + update_approximate_opaque_rect_order(&orderInfo, opaque_rect)); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_opaque_rect_order(s, &orderInfo, opaque_rect); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_line_to(rdpContext* context, const LINE_TO_ORDER* line_to) { wStream* s; int offset; int headerLength; ORDER_INFO orderInfo; int inf; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_LINE_TO); inf = update_approximate_line_to_order(&orderInfo, line_to); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_line_to_order(s, &orderInfo, line_to); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_memblt(rdpContext* context, MEMBLT_ORDER* memblt) { wStream* s; size_t offset; int headerLength; ORDER_INFO orderInfo; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_MEMBLT); update_check_flush(context, headerLength + update_approximate_memblt_order(&orderInfo, memblt)); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_memblt_order(s, &orderInfo, memblt); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_glyph_index(rdpContext* context, GLYPH_INDEX_ORDER* glyph_index) { wStream* s; size_t offset; int headerLength; int inf; ORDER_INFO orderInfo; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_GLYPH_INDEX); inf = update_approximate_glyph_index_order(&orderInfo, glyph_index); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_glyph_index_order(s, &orderInfo, glyph_index); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } /* * Secondary Drawing Orders */ static BOOL update_send_cache_bitmap(rdpContext* context, const CACHE_BITMAP_ORDER* cache_bitmap) { wStream* s; size_t bm, em; BYTE orderType; int headerLength; int inf; UINT16 extraFlags; INT16 orderLength; rdpUpdate* update = context->update; extraFlags = 0; headerLength = 6; orderType = cache_bitmap->compressed ? ORDER_TYPE_CACHE_BITMAP_COMPRESSED : ORDER_TYPE_BITMAP_UNCOMPRESSED; inf = update_approximate_cache_bitmap_order(cache_bitmap, cache_bitmap->compressed, &extraFlags); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_bitmap_order(s, cache_bitmap, cache_bitmap->compressed, &extraFlags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, extraFlags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, orderType); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_bitmap_v2(rdpContext* context, CACHE_BITMAP_V2_ORDER* cache_bitmap_v2) { wStream* s; size_t bm, em; BYTE orderType; int headerLength; UINT16 extraFlags; INT16 orderLength; rdpUpdate* update = context->update; extraFlags = 0; headerLength = 6; orderType = cache_bitmap_v2->compressed ? ORDER_TYPE_BITMAP_COMPRESSED_V2 : ORDER_TYPE_BITMAP_UNCOMPRESSED_V2; if (context->settings->NoBitmapCompressionHeader) cache_bitmap_v2->flags |= CBR2_NO_BITMAP_COMPRESSION_HDR; update_check_flush(context, headerLength + update_approximate_cache_bitmap_v2_order(cache_bitmap_v2, cache_bitmap_v2->compressed, &extraFlags)); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_bitmap_v2_order(s, cache_bitmap_v2, cache_bitmap_v2->compressed, &extraFlags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, extraFlags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, orderType); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_bitmap_v3(rdpContext* context, CACHE_BITMAP_V3_ORDER* cache_bitmap_v3) { wStream* s; size_t bm, em; BYTE orderType; int headerLength; UINT16 extraFlags; INT16 orderLength; rdpUpdate* update = context->update; extraFlags = 0; headerLength = 6; orderType = ORDER_TYPE_BITMAP_COMPRESSED_V3; update_check_flush(context, headerLength + update_approximate_cache_bitmap_v3_order(cache_bitmap_v3, &extraFlags)); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_bitmap_v3_order(s, cache_bitmap_v3, &extraFlags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, extraFlags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, orderType); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_color_table(rdpContext* context, const CACHE_COLOR_TABLE_ORDER* cache_color_table) { wStream* s; UINT16 flags; size_t bm, em, inf; int headerLength; INT16 orderLength; rdpUpdate* update = context->update; flags = 0; headerLength = 6; inf = update_approximate_cache_color_table_order(cache_color_table, &flags); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_color_table_order(s, cache_color_table, &flags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, flags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, ORDER_TYPE_CACHE_COLOR_TABLE); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_glyph(rdpContext* context, const CACHE_GLYPH_ORDER* cache_glyph) { wStream* s; UINT16 flags; size_t bm, em, inf; int headerLength; INT16 orderLength; rdpUpdate* update = context->update; flags = 0; headerLength = 6; inf = update_approximate_cache_glyph_order(cache_glyph, &flags); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_glyph_order(s, cache_glyph, &flags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, flags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, ORDER_TYPE_CACHE_GLYPH); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_glyph_v2(rdpContext* context, const CACHE_GLYPH_V2_ORDER* cache_glyph_v2) { wStream* s; UINT16 flags; size_t bm, em, inf; int headerLength; INT16 orderLength; rdpUpdate* update = context->update; flags = 0; headerLength = 6; inf = update_approximate_cache_glyph_v2_order(cache_glyph_v2, &flags); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_glyph_v2_order(s, cache_glyph_v2, &flags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, flags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, ORDER_TYPE_CACHE_GLYPH); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_brush(rdpContext* context, const CACHE_BRUSH_ORDER* cache_brush) { wStream* s; UINT16 flags; size_t bm, em, inf; int headerLength; INT16 orderLength; rdpUpdate* update = context->update; flags = 0; headerLength = 6; inf = update_approximate_cache_brush_order(cache_brush, &flags); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_brush_order(s, cache_brush, &flags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, flags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, ORDER_TYPE_CACHE_BRUSH); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } /** * Alternate Secondary Drawing Orders */ static BOOL update_send_create_offscreen_bitmap_order( rdpContext* context, const CREATE_OFFSCREEN_BITMAP_ORDER* create_offscreen_bitmap) { wStream* s; size_t bm, em, inf; BYTE orderType; BYTE controlFlags; int headerLength; rdpUpdate* update = context->update; headerLength = 1; orderType = ORDER_TYPE_CREATE_OFFSCREEN_BITMAP; controlFlags = ORDER_SECONDARY | (orderType << 2); inf = update_approximate_create_offscreen_bitmap_order( create_offscreen_bitmap); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_create_offscreen_bitmap_order(s, create_offscreen_bitmap)) return FALSE; em = Stream_GetPosition(s); Stream_SetPosition(s, bm); Stream_Write_UINT8(s, controlFlags); /* controlFlags (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_switch_surface_order( rdpContext* context, const SWITCH_SURFACE_ORDER* switch_surface) { wStream* s; size_t bm, em, inf; BYTE orderType; BYTE controlFlags; int headerLength; rdpUpdate* update; if (!context || !switch_surface || !context->update) return FALSE; update = context->update; headerLength = 1; orderType = ORDER_TYPE_SWITCH_SURFACE; controlFlags = ORDER_SECONDARY | (orderType << 2); inf = update_approximate_switch_surface_order(switch_surface); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_switch_surface_order(s, switch_surface)) return FALSE; em = Stream_GetPosition(s); Stream_SetPosition(s, bm); Stream_Write_UINT8(s, controlFlags); /* controlFlags (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_pointer_system(rdpContext* context, const POINTER_SYSTEM_UPDATE* pointer_system) { wStream* s; BYTE updateCode; rdpRdp* rdp = context->rdp; BOOL ret; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (pointer_system->type == SYSPTR_NULL) updateCode = FASTPATH_UPDATETYPE_PTR_NULL; else updateCode = FASTPATH_UPDATETYPE_PTR_DEFAULT; ret = fastpath_send_update_pdu(rdp->fastpath, updateCode, s, FALSE); Stream_Release(s); return ret; } static BOOL update_send_pointer_position(rdpContext* context, const POINTER_POSITION_UPDATE* pointerPosition) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!Stream_EnsureRemainingCapacity(s, 16)) goto out_fail; Stream_Write_UINT16(s, pointerPosition->xPos); /* xPos (2 bytes) */ Stream_Write_UINT16(s, pointerPosition->yPos); /* yPos (2 bytes) */ ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_PTR_POSITION, s, FALSE); out_fail: Stream_Release(s); return ret; } static BOOL update_write_pointer_color(wStream* s, const POINTER_COLOR_UPDATE* pointer_color) { if (!Stream_EnsureRemainingCapacity(s, 32 + pointer_color->lengthAndMask + pointer_color->lengthXorMask)) return FALSE; Stream_Write_UINT16(s, pointer_color->cacheIndex); Stream_Write_UINT16(s, pointer_color->xPos); Stream_Write_UINT16(s, pointer_color->yPos); Stream_Write_UINT16(s, pointer_color->width); Stream_Write_UINT16(s, pointer_color->height); Stream_Write_UINT16(s, pointer_color->lengthAndMask); Stream_Write_UINT16(s, pointer_color->lengthXorMask); if (pointer_color->lengthXorMask > 0) Stream_Write(s, pointer_color->xorMaskData, pointer_color->lengthXorMask); if (pointer_color->lengthAndMask > 0) Stream_Write(s, pointer_color->andMaskData, pointer_color->lengthAndMask); Stream_Write_UINT8(s, 0); /* pad (1 byte) */ return TRUE; } static BOOL update_send_pointer_color(rdpContext* context, const POINTER_COLOR_UPDATE* pointer_color) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!update_write_pointer_color(s, pointer_color)) goto out_fail; ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_COLOR, s, FALSE); out_fail: Stream_Release(s); return ret; } static BOOL update_send_pointer_new(rdpContext* context, const POINTER_NEW_UPDATE* pointer_new) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!Stream_EnsureRemainingCapacity(s, 16)) goto out_fail; Stream_Write_UINT16(s, pointer_new->xorBpp); /* xorBpp (2 bytes) */ update_write_pointer_color(s, &pointer_new->colorPtrAttr); ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_POINTER, s, FALSE); out_fail: Stream_Release(s); return ret; } static BOOL update_send_pointer_cached(rdpContext* context, const POINTER_CACHED_UPDATE* pointer_cached) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; Stream_Write_UINT16(s, pointer_cached->cacheIndex); /* cacheIndex (2 bytes) */ ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_CACHED, s, FALSE); Stream_Release(s); return ret; } BOOL update_read_refresh_rect(rdpUpdate* update, wStream* s) { int index; BYTE numberOfAreas; RECTANGLE_16* areas; if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT8(s, numberOfAreas); Stream_Seek(s, 3); /* pad3Octects */ if (Stream_GetRemainingLength(s) < ((size_t) numberOfAreas * 4 * 2)) return FALSE; areas = (RECTANGLE_16*) calloc(numberOfAreas, sizeof(RECTANGLE_16)); if (!areas) return FALSE; for (index = 0; index < numberOfAreas; index++) { Stream_Read_UINT16(s, areas[index].left); Stream_Read_UINT16(s, areas[index].top); Stream_Read_UINT16(s, areas[index].right); Stream_Read_UINT16(s, areas[index].bottom); } if (update->context->settings->RefreshRect) IFCALL(update->RefreshRect, update->context, numberOfAreas, areas); else WLog_Print(update->log, WLOG_WARN, "ignoring refresh rect request from client"); free(areas); return TRUE; } BOOL update_read_suppress_output(rdpUpdate* update, wStream* s) { BYTE allowDisplayUpdates; if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT8(s, allowDisplayUpdates); Stream_Seek(s, 3); /* pad3Octects */ if (allowDisplayUpdates > 0 && Stream_GetRemainingLength(s) < 8) return FALSE; if (update->context->settings->SuppressOutput) IFCALL(update->SuppressOutput, update->context, allowDisplayUpdates, allowDisplayUpdates > 0 ? (RECTANGLE_16*) Stream_Pointer(s) : NULL); else WLog_Print(update->log, WLOG_WARN, "ignoring suppress output request from client"); return TRUE; } static BOOL update_send_set_keyboard_indicators(rdpContext* context, UINT16 led_flags) { wStream* s; rdpRdp* rdp = context->rdp; s = rdp_data_pdu_init(rdp); if (!s) return FALSE; Stream_Write_UINT16(s, 0); /* unitId should be 0 according to MS-RDPBCGR 2.2.8.2.1.1 */ Stream_Write_UINT16(s, led_flags); /* ledFlags (2 bytes) */ return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_SET_KEYBOARD_INDICATORS, rdp->mcs->userId); } static BOOL update_send_set_keyboard_ime_status(rdpContext* context, UINT16 imeId, UINT32 imeState, UINT32 imeConvMode) { wStream* s; rdpRdp* rdp = context->rdp; s = rdp_data_pdu_init(rdp); if (!s) return FALSE; /* unitId should be 0 according to MS-RDPBCGR 2.2.8.2.2.1 */ Stream_Write_UINT16(s, imeId); Stream_Write_UINT32(s, imeState); Stream_Write_UINT32(s, imeConvMode); return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_SET_KEYBOARD_IME_STATUS, rdp->mcs->userId); } void update_register_server_callbacks(rdpUpdate* update) { update->BeginPaint = update_begin_paint; update->EndPaint = update_end_paint; update->SetBounds = update_set_bounds; update->Synchronize = update_send_synchronize; update->DesktopResize = update_send_desktop_resize; update->BitmapUpdate = update_send_bitmap_update; update->SurfaceBits = update_send_surface_bits; update->SurfaceFrameMarker = update_send_surface_frame_marker; update->SurfaceCommand = update_send_surface_command; update->SurfaceFrameBits = update_send_surface_frame_bits; update->PlaySound = update_send_play_sound; update->SetKeyboardIndicators = update_send_set_keyboard_indicators; update->SetKeyboardImeStatus = update_send_set_keyboard_ime_status; update->SaveSessionInfo = rdp_send_save_session_info; update->primary->DstBlt = update_send_dstblt; update->primary->PatBlt = update_send_patblt; update->primary->ScrBlt = update_send_scrblt; update->primary->OpaqueRect = update_send_opaque_rect; update->primary->LineTo = update_send_line_to; update->primary->MemBlt = update_send_memblt; update->primary->GlyphIndex = update_send_glyph_index; update->secondary->CacheBitmap = update_send_cache_bitmap; update->secondary->CacheBitmapV2 = update_send_cache_bitmap_v2; update->secondary->CacheBitmapV3 = update_send_cache_bitmap_v3; update->secondary->CacheColorTable = update_send_cache_color_table; update->secondary->CacheGlyph = update_send_cache_glyph; update->secondary->CacheGlyphV2 = update_send_cache_glyph_v2; update->secondary->CacheBrush = update_send_cache_brush; update->altsec->CreateOffscreenBitmap = update_send_create_offscreen_bitmap_order; update->altsec->SwitchSurface = update_send_switch_surface_order; update->pointer->PointerSystem = update_send_pointer_system; update->pointer->PointerPosition = update_send_pointer_position; update->pointer->PointerColor = update_send_pointer_color; update->pointer->PointerNew = update_send_pointer_new; update->pointer->PointerCached = update_send_pointer_cached; } void update_register_client_callbacks(rdpUpdate* update) { update->RefreshRect = update_send_refresh_rect; update->SuppressOutput = update_send_suppress_output; update->SurfaceFrameAcknowledge = update_send_frame_acknowledge; } int update_process_messages(rdpUpdate* update) { return update_message_queue_process_pending_messages(update); } static void update_free_queued_message(void* obj) { wMessage* msg = (wMessage*)obj; update_message_queue_free_message(msg); } static void update_free_window_state(WINDOW_STATE_ORDER* window_state) { if (!window_state) return; free(window_state->titleInfo.string); window_state->titleInfo.string = NULL; free(window_state->windowRects); window_state->windowRects = NULL; free(window_state->visibilityRects); window_state->visibilityRects = NULL; } rdpUpdate* update_new(rdpRdp* rdp) { const wObject cb = { NULL, NULL, NULL, update_free_queued_message, NULL }; rdpUpdate* update; OFFSCREEN_DELETE_LIST* deleteList; update = (rdpUpdate*) calloc(1, sizeof(rdpUpdate)); if (!update) return NULL; update->log = WLog_Get("com.freerdp.core.update"); update->pointer = (rdpPointerUpdate*) calloc(1, sizeof(rdpPointerUpdate)); if (!update->pointer) goto fail; update->primary = (rdpPrimaryUpdate*) calloc(1, sizeof(rdpPrimaryUpdate)); if (!update->primary) goto fail; update->secondary = (rdpSecondaryUpdate*) calloc(1, sizeof(rdpSecondaryUpdate)); if (!update->secondary) goto fail; update->altsec = (rdpAltSecUpdate*) calloc(1, sizeof(rdpAltSecUpdate)); if (!update->altsec) goto fail; update->window = (rdpWindowUpdate*) calloc(1, sizeof(rdpWindowUpdate)); if (!update->window) goto fail; deleteList = &(update->altsec->create_offscreen_bitmap.deleteList); deleteList->sIndices = 64; deleteList->indices = calloc(deleteList->sIndices, 2); if (!deleteList->indices) goto fail; deleteList->cIndices = 0; update->SuppressOutput = update_send_suppress_output; update->initialState = TRUE; update->queue = MessageQueue_New(&cb); if (!update->queue) goto fail; return update; fail: update_free(update); return NULL; } void update_free(rdpUpdate* update) { if (update != NULL) { OFFSCREEN_DELETE_LIST* deleteList = &(update->altsec->create_offscreen_bitmap.deleteList); if (deleteList) free(deleteList->indices); free(update->pointer); if (update->primary) { free(update->primary->polyline.points); free(update->primary->polygon_sc.points); free(update->primary->fast_glyph.glyphData.aj); free(update->primary); } free(update->secondary); free(update->altsec); if (update->window) { free(update->window->monitored_desktop.windowIds); update_free_window_state(&update->window->window_state); update_free_window_icon_info(update->window->window_icon.iconInfo); free(update->window); } MessageQueue_Free(update->queue); free(update); } }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_672_0
crossvul-cpp_data_good_627_0
/*====================================================================* - Copyright (C) 2001 Leptonica. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials - provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ANY - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *====================================================================*/ /* * htmlviewer.c * * This takes a directory of image files, optionally scales them, * and generates html files to view the scaled images (and thumbnails). * * Input: dirin: directory of input image files * dirout: directory for output files * rootname: root name for output files * thumbwidth: width of thumb images, in pixels; use 0 for default * viewwidth: max width of view images, in pixels; use 0 for default * * Example: * mkdir /tmp/lept/lion-in * mkdir /tmp/lept/lion-out * cp lion-page* /tmp/lept/lion-in * htmlviewer /tmp/lept/lion-in /tmp/lept/lion-out lion 200 600 * ==> output: * /tmp/lept/lion-out/lion.html (main html file) * /tmp/lept/lion-out/lion-links.html (html file of links) */ #include <string.h> #include "allheaders.h" #ifdef _WIN32 #include <windows.h> /* for CreateDirectory() */ #endif static const l_int32 DEFAULT_THUMB_WIDTH = 120; static const l_int32 DEFAULT_VIEW_WIDTH = 800; static const l_int32 MIN_THUMB_WIDTH = 50; static const l_int32 MIN_VIEW_WIDTH = 300; static l_int32 pixHtmlViewer(const char *dirin, const char *dirout, const char *rootname, l_int32 thumbwidth, l_int32 viewwidth); static void WriteFormattedPix(char *fname, PIX *pix); int main(int argc, char **argv) { char *dirin, *dirout, *rootname; l_int32 thumbwidth, viewwidth; static char mainName[] = "htmlviewer"; if (argc != 6) return ERROR_INT( " Syntax: htmlviewer dirin dirout rootname thumbwidth viewwidth", mainName, 1); dirin = argv[1]; dirout = argv[2]; rootname = argv[3]; thumbwidth = atoi(argv[4]); viewwidth = atoi(argv[5]); pixHtmlViewer(dirin, dirout, rootname, thumbwidth, viewwidth); return 0; } /*---------------------------------------------------------------------* * Generate smaller images for viewing and write html * *---------------------------------------------------------------------*/ /*! * \brief pixHtmlViewer() * * \param[in] dirin directory of input image files * \param[in] dirout directory for output files * \param[in] rootname root name for output files * \param[in] thumbwidth width of thumb images in pixels; use 0 for default * \param[in] viewwidth maximum width of view images no up-scaling * in pixels; use 0 for default * \return 0 if OK; 1 on error * * <pre> * Notes: * (1) The thumb and view reduced images are generated, * along with two html files: * <rootname>.html and <rootname>-links.html * (2) The thumb and view files are named * <rootname>_thumb_xxx.jpg * <rootname>_view_xxx.jpg * With this naming scheme, any number of input directories * of images can be processed into views and thumbs * and placed in the same output directory. * </pre> */ static l_int32 pixHtmlViewer(const char *dirin, const char *dirout, const char *rootname, l_int32 thumbwidth, l_int32 viewwidth) { char *fname, *fullname, *outname; char *mainname, *linkname, *linknameshort; char *viewfile, *thumbfile; char *shtml, *slink; char charbuf[512]; char htmlstring[] = "<html>"; char framestring[] = "</frameset></html>"; l_int32 i, nfiles, index, w, d, nimages, ret; l_float32 factor; PIX *pix, *pixthumb, *pixview; SARRAY *safiles, *sathumbs, *saviews, *sahtml, *salink; PROCNAME("pixHtmlViewer"); if (!dirin) return ERROR_INT("dirin not defined", procName, 1); if (!dirout) return ERROR_INT("dirout not defined", procName, 1); if (!rootname) return ERROR_INT("rootname not defined", procName, 1); if (thumbwidth == 0) thumbwidth = DEFAULT_THUMB_WIDTH; if (thumbwidth < MIN_THUMB_WIDTH) { L_WARNING("thumbwidth too small; using min value\n", procName); thumbwidth = MIN_THUMB_WIDTH; } if (viewwidth == 0) viewwidth = DEFAULT_VIEW_WIDTH; if (viewwidth < MIN_VIEW_WIDTH) { L_WARNING("viewwidth too small; using min value\n", procName); viewwidth = MIN_VIEW_WIDTH; } /* Make the output directory if it doesn't already exist */ #ifndef _WIN32 snprintf(charbuf, sizeof(charbuf), "mkdir -p %s", dirout); ret = system(charbuf); #else ret = CreateDirectory(dirout, NULL) ? 0 : 1; #endif /* !_WIN32 */ if (ret) { L_ERROR("output directory %s not made\n", procName, dirout); return 1; } /* Capture the filenames in the input directory */ if ((safiles = getFilenamesInDirectory(dirin)) == NULL) return ERROR_INT("safiles not made", procName, 1); /* Generate output text file names */ snprintf(charbuf, sizeof(charbuf), "%s/%s.html", dirout, rootname); mainname = stringNew(charbuf); snprintf(charbuf, sizeof(charbuf), "%s/%s-links.html", dirout, rootname); linkname = stringNew(charbuf); linknameshort = stringJoin(rootname, "-links.html"); /* Generate the thumbs and views */ sathumbs = sarrayCreate(0); saviews = sarrayCreate(0); nfiles = sarrayGetCount(safiles); index = 0; for (i = 0; i < nfiles; i++) { fname = sarrayGetString(safiles, i, L_NOCOPY); fullname = genPathname(dirin, fname); fprintf(stderr, "name: %s\n", fullname); if ((pix = pixRead(fullname)) == NULL) { fprintf(stderr, "file %s not a readable image\n", fullname); lept_free(fullname); continue; } lept_free(fullname); /* Make and store the thumbnail images */ pixGetDimensions(pix, &w, NULL, &d); factor = (l_float32)thumbwidth / (l_float32)w; pixthumb = pixScale(pix, factor, factor); snprintf(charbuf, sizeof(charbuf), "%s_thumb_%03d", rootname, index); sarrayAddString(sathumbs, charbuf, L_COPY); outname = genPathname(dirout, charbuf); WriteFormattedPix(outname, pixthumb); lept_free(outname); pixDestroy(&pixthumb); /* Make and store the view images */ factor = (l_float32)viewwidth / (l_float32)w; if (factor >= 1.0) pixview = pixClone(pix); /* no upscaling */ else pixview = pixScale(pix, factor, factor); snprintf(charbuf, sizeof(charbuf), "%s_view_%03d", rootname, index); sarrayAddString(saviews, charbuf, L_COPY); outname = genPathname(dirout, charbuf); WriteFormattedPix(outname, pixview); lept_free(outname); pixDestroy(&pixview); pixDestroy(&pix); index++; } /* Generate the main html file */ sahtml = sarrayCreate(0); sarrayAddString(sahtml, htmlstring, L_COPY); sprintf(charbuf, "<frameset cols=\"%d, *\">", thumbwidth + 30); sarrayAddString(sahtml, charbuf, L_COPY); sprintf(charbuf, "<frame name=\"thumbs\" src=\"%s\">", linknameshort); sarrayAddString(sahtml, charbuf, L_COPY); sprintf(charbuf, "<frame name=\"views\" src=\"%s\">", sarrayGetString(saviews, 0, L_NOCOPY)); sarrayAddString(sahtml, charbuf, L_COPY); sarrayAddString(sahtml, framestring, L_COPY); shtml = sarrayToString(sahtml, 1); l_binaryWrite(mainname, "w", shtml, strlen(shtml)); fprintf(stderr, "******************************************\n" "Writing html file: %s\n" "******************************************\n", mainname); lept_free(shtml); lept_free(mainname); /* Generate the link html file */ nimages = sarrayGetCount(saviews); fprintf(stderr, "num. images = %d\n", nimages); salink = sarrayCreate(0); for (i = 0; i < nimages; i++) { viewfile = sarrayGetString(saviews, i, L_NOCOPY); thumbfile = sarrayGetString(sathumbs, i, L_NOCOPY); sprintf(charbuf, "<a href=\"%s\" TARGET=views><img src=\"%s\"></a>", viewfile, thumbfile); sarrayAddString(salink, charbuf, L_COPY); } slink = sarrayToString(salink, 1); l_binaryWrite(linkname, "w", slink, strlen(slink)); lept_free(slink); lept_free(linkname); lept_free(linknameshort); sarrayDestroy(&safiles); sarrayDestroy(&sathumbs); sarrayDestroy(&saviews); sarrayDestroy(&sahtml); sarrayDestroy(&salink); return 0; } static void WriteFormattedPix(char *fname, PIX *pix) { l_int32 d; d = pixGetDepth(pix); if (d == 1 || pixGetColormap(pix)) pixWrite(fname, pix, IFF_PNG); else pixWrite(fname, pix, IFF_JFIF_JPEG); return; }
./CrossVul/dataset_final_sorted/CWE-119/c/good_627_0
crossvul-cpp_data_bad_150_0
// SPDX-License-Identifier: GPL-2.0 #include <linux/kernel.h> #include <linux/mm.h> #include <linux/fs.h> #include <linux/errno.h> #include <linux/string.h> #include <linux/blkdev.h> #include <linux/module.h> #include <linux/blkpg.h> #include <linux/cdrom.h> #include <linux/delay.h> #include <linux/slab.h> #include <asm/io.h> #include <linux/uaccess.h> #include <scsi/scsi.h> #include <scsi/scsi_dbg.h> #include <scsi/scsi_device.h> #include <scsi/scsi_eh.h> #include <scsi/scsi_host.h> #include <scsi/scsi_ioctl.h> #include <scsi/scsi_cmnd.h> #include "sr.h" #if 0 #define DEBUG #endif /* The sr_is_xa() seems to trigger firmware bugs with some drives :-( * It is off by default and can be turned on with this module parameter */ static int xa_test = 0; module_param(xa_test, int, S_IRUGO | S_IWUSR); /* primitive to determine whether we need to have GFP_DMA set based on * the status of the unchecked_isa_dma flag in the host structure */ #define SR_GFP_DMA(cd) (((cd)->device->host->unchecked_isa_dma) ? GFP_DMA : 0) static int sr_read_tochdr(struct cdrom_device_info *cdi, struct cdrom_tochdr *tochdr) { struct scsi_cd *cd = cdi->handle; struct packet_command cgc; int result; unsigned char *buffer; buffer = kmalloc(32, GFP_KERNEL | SR_GFP_DMA(cd)); if (!buffer) return -ENOMEM; memset(&cgc, 0, sizeof(struct packet_command)); cgc.timeout = IOCTL_TIMEOUT; cgc.cmd[0] = GPCMD_READ_TOC_PMA_ATIP; cgc.cmd[8] = 12; /* LSB of length */ cgc.buffer = buffer; cgc.buflen = 12; cgc.quiet = 1; cgc.data_direction = DMA_FROM_DEVICE; result = sr_do_ioctl(cd, &cgc); tochdr->cdth_trk0 = buffer[2]; tochdr->cdth_trk1 = buffer[3]; kfree(buffer); return result; } static int sr_read_tocentry(struct cdrom_device_info *cdi, struct cdrom_tocentry *tocentry) { struct scsi_cd *cd = cdi->handle; struct packet_command cgc; int result; unsigned char *buffer; buffer = kmalloc(32, GFP_KERNEL | SR_GFP_DMA(cd)); if (!buffer) return -ENOMEM; memset(&cgc, 0, sizeof(struct packet_command)); cgc.timeout = IOCTL_TIMEOUT; cgc.cmd[0] = GPCMD_READ_TOC_PMA_ATIP; cgc.cmd[1] |= (tocentry->cdte_format == CDROM_MSF) ? 0x02 : 0; cgc.cmd[6] = tocentry->cdte_track; cgc.cmd[8] = 12; /* LSB of length */ cgc.buffer = buffer; cgc.buflen = 12; cgc.data_direction = DMA_FROM_DEVICE; result = sr_do_ioctl(cd, &cgc); tocentry->cdte_ctrl = buffer[5] & 0xf; tocentry->cdte_adr = buffer[5] >> 4; tocentry->cdte_datamode = (tocentry->cdte_ctrl & 0x04) ? 1 : 0; if (tocentry->cdte_format == CDROM_MSF) { tocentry->cdte_addr.msf.minute = buffer[9]; tocentry->cdte_addr.msf.second = buffer[10]; tocentry->cdte_addr.msf.frame = buffer[11]; } else tocentry->cdte_addr.lba = (((((buffer[8] << 8) + buffer[9]) << 8) + buffer[10]) << 8) + buffer[11]; kfree(buffer); return result; } #define IOCTL_RETRIES 3 /* ATAPI drives don't have a SCMD_PLAYAUDIO_TI command. When these drives are emulating a SCSI device via the idescsi module, they need to have CDROMPLAYTRKIND commands translated into CDROMPLAYMSF commands for them */ static int sr_fake_playtrkind(struct cdrom_device_info *cdi, struct cdrom_ti *ti) { struct cdrom_tocentry trk0_te, trk1_te; struct cdrom_tochdr tochdr; struct packet_command cgc; int ntracks, ret; ret = sr_read_tochdr(cdi, &tochdr); if (ret) return ret; ntracks = tochdr.cdth_trk1 - tochdr.cdth_trk0 + 1; if (ti->cdti_trk1 == ntracks) ti->cdti_trk1 = CDROM_LEADOUT; else if (ti->cdti_trk1 != CDROM_LEADOUT) ti->cdti_trk1 ++; trk0_te.cdte_track = ti->cdti_trk0; trk0_te.cdte_format = CDROM_MSF; trk1_te.cdte_track = ti->cdti_trk1; trk1_te.cdte_format = CDROM_MSF; ret = sr_read_tocentry(cdi, &trk0_te); if (ret) return ret; ret = sr_read_tocentry(cdi, &trk1_te); if (ret) return ret; memset(&cgc, 0, sizeof(struct packet_command)); cgc.cmd[0] = GPCMD_PLAY_AUDIO_MSF; cgc.cmd[3] = trk0_te.cdte_addr.msf.minute; cgc.cmd[4] = trk0_te.cdte_addr.msf.second; cgc.cmd[5] = trk0_te.cdte_addr.msf.frame; cgc.cmd[6] = trk1_te.cdte_addr.msf.minute; cgc.cmd[7] = trk1_te.cdte_addr.msf.second; cgc.cmd[8] = trk1_te.cdte_addr.msf.frame; cgc.data_direction = DMA_NONE; cgc.timeout = IOCTL_TIMEOUT; return sr_do_ioctl(cdi->handle, &cgc); } static int sr_play_trkind(struct cdrom_device_info *cdi, struct cdrom_ti *ti) { struct scsi_cd *cd = cdi->handle; struct packet_command cgc; int result; memset(&cgc, 0, sizeof(struct packet_command)); cgc.timeout = IOCTL_TIMEOUT; cgc.cmd[0] = GPCMD_PLAYAUDIO_TI; cgc.cmd[4] = ti->cdti_trk0; cgc.cmd[5] = ti->cdti_ind0; cgc.cmd[7] = ti->cdti_trk1; cgc.cmd[8] = ti->cdti_ind1; cgc.data_direction = DMA_NONE; result = sr_do_ioctl(cd, &cgc); if (result == -EDRIVE_CANT_DO_THIS) result = sr_fake_playtrkind(cdi, ti); return result; } /* We do our own retries because we want to know what the specific error code is. Normally the UNIT_ATTENTION code will automatically clear after one error */ int sr_do_ioctl(Scsi_CD *cd, struct packet_command *cgc) { struct scsi_device *SDev; struct scsi_sense_hdr sshdr; int result, err = 0, retries = 0; SDev = cd->device; retry: if (!scsi_block_when_processing_errors(SDev)) { err = -ENODEV; goto out; } result = scsi_execute(SDev, cgc->cmd, cgc->data_direction, cgc->buffer, cgc->buflen, (unsigned char *)cgc->sense, &sshdr, cgc->timeout, IOCTL_RETRIES, 0, 0, NULL); /* Minimal error checking. Ignore cases we know about, and report the rest. */ if (driver_byte(result) != 0) { switch (sshdr.sense_key) { case UNIT_ATTENTION: SDev->changed = 1; if (!cgc->quiet) sr_printk(KERN_INFO, cd, "disc change detected.\n"); if (retries++ < 10) goto retry; err = -ENOMEDIUM; break; case NOT_READY: /* This happens if there is no disc in drive */ if (sshdr.asc == 0x04 && sshdr.ascq == 0x01) { /* sense: Logical unit is in process of becoming ready */ if (!cgc->quiet) sr_printk(KERN_INFO, cd, "CDROM not ready yet.\n"); if (retries++ < 10) { /* sleep 2 sec and try again */ ssleep(2); goto retry; } else { /* 20 secs are enough? */ err = -ENOMEDIUM; break; } } if (!cgc->quiet) sr_printk(KERN_INFO, cd, "CDROM not ready. Make sure there " "is a disc in the drive.\n"); err = -ENOMEDIUM; break; case ILLEGAL_REQUEST: err = -EIO; if (sshdr.asc == 0x20 && sshdr.ascq == 0x00) /* sense: Invalid command operation code */ err = -EDRIVE_CANT_DO_THIS; break; default: err = -EIO; } } /* Wake up a process waiting for device */ out: cgc->stat = err; return err; } /* ---------------------------------------------------------------------- */ /* interface to cdrom.c */ int sr_tray_move(struct cdrom_device_info *cdi, int pos) { Scsi_CD *cd = cdi->handle; struct packet_command cgc; memset(&cgc, 0, sizeof(struct packet_command)); cgc.cmd[0] = GPCMD_START_STOP_UNIT; cgc.cmd[4] = (pos == 0) ? 0x03 /* close */ : 0x02 /* eject */ ; cgc.data_direction = DMA_NONE; cgc.timeout = IOCTL_TIMEOUT; return sr_do_ioctl(cd, &cgc); } int sr_lock_door(struct cdrom_device_info *cdi, int lock) { Scsi_CD *cd = cdi->handle; return scsi_set_medium_removal(cd->device, lock ? SCSI_REMOVAL_PREVENT : SCSI_REMOVAL_ALLOW); } int sr_drive_status(struct cdrom_device_info *cdi, int slot) { struct scsi_cd *cd = cdi->handle; struct scsi_sense_hdr sshdr; struct media_event_desc med; if (CDSL_CURRENT != slot) { /* we have no changer support */ return -EINVAL; } if (!scsi_test_unit_ready(cd->device, SR_TIMEOUT, MAX_RETRIES, &sshdr)) return CDS_DISC_OK; /* SK/ASC/ASCQ of 2/4/1 means "unit is becoming ready" */ if (scsi_sense_valid(&sshdr) && sshdr.sense_key == NOT_READY && sshdr.asc == 0x04 && sshdr.ascq == 0x01) return CDS_DRIVE_NOT_READY; if (!cdrom_get_media_event(cdi, &med)) { if (med.media_present) return CDS_DISC_OK; else if (med.door_open) return CDS_TRAY_OPEN; else return CDS_NO_DISC; } /* * SK/ASC/ASCQ of 2/4/2 means "initialization required" * Using CD_TRAY_OPEN results in an START_STOP_UNIT to close * the tray, which resolves the initialization requirement. */ if (scsi_sense_valid(&sshdr) && sshdr.sense_key == NOT_READY && sshdr.asc == 0x04 && sshdr.ascq == 0x02) return CDS_TRAY_OPEN; /* * 0x04 is format in progress .. but there must be a disc present! */ if (sshdr.sense_key == NOT_READY && sshdr.asc == 0x04) return CDS_DISC_OK; /* * If not using Mt Fuji extended media tray reports, * just return TRAY_OPEN since ATAPI doesn't provide * any other way to detect this... */ if (scsi_sense_valid(&sshdr) && /* 0x3a is medium not present */ sshdr.asc == 0x3a) return CDS_NO_DISC; else return CDS_TRAY_OPEN; return CDS_DRIVE_NOT_READY; } int sr_disk_status(struct cdrom_device_info *cdi) { Scsi_CD *cd = cdi->handle; struct cdrom_tochdr toc_h; struct cdrom_tocentry toc_e; int i, rc, have_datatracks = 0; /* look for data tracks */ rc = sr_read_tochdr(cdi, &toc_h); if (rc) return (rc == -ENOMEDIUM) ? CDS_NO_DISC : CDS_NO_INFO; for (i = toc_h.cdth_trk0; i <= toc_h.cdth_trk1; i++) { toc_e.cdte_track = i; toc_e.cdte_format = CDROM_LBA; if (sr_read_tocentry(cdi, &toc_e)) return CDS_NO_INFO; if (toc_e.cdte_ctrl & CDROM_DATA_TRACK) { have_datatracks = 1; break; } } if (!have_datatracks) return CDS_AUDIO; if (cd->xa_flag) return CDS_XA_2_1; else return CDS_DATA_1; } int sr_get_last_session(struct cdrom_device_info *cdi, struct cdrom_multisession *ms_info) { Scsi_CD *cd = cdi->handle; ms_info->addr.lba = cd->ms_offset; ms_info->xa_flag = cd->xa_flag || cd->ms_offset > 0; return 0; } int sr_get_mcn(struct cdrom_device_info *cdi, struct cdrom_mcn *mcn) { Scsi_CD *cd = cdi->handle; struct packet_command cgc; char *buffer = kmalloc(32, GFP_KERNEL | SR_GFP_DMA(cd)); int result; if (!buffer) return -ENOMEM; memset(&cgc, 0, sizeof(struct packet_command)); cgc.cmd[0] = GPCMD_READ_SUBCHANNEL; cgc.cmd[2] = 0x40; /* I do want the subchannel info */ cgc.cmd[3] = 0x02; /* Give me medium catalog number info */ cgc.cmd[8] = 24; cgc.buffer = buffer; cgc.buflen = 24; cgc.data_direction = DMA_FROM_DEVICE; cgc.timeout = IOCTL_TIMEOUT; result = sr_do_ioctl(cd, &cgc); memcpy(mcn->medium_catalog_number, buffer + 9, 13); mcn->medium_catalog_number[13] = 0; kfree(buffer); return result; } int sr_reset(struct cdrom_device_info *cdi) { return 0; } int sr_select_speed(struct cdrom_device_info *cdi, int speed) { Scsi_CD *cd = cdi->handle; struct packet_command cgc; if (speed == 0) speed = 0xffff; /* set to max */ else speed *= 177; /* Nx to kbyte/s */ memset(&cgc, 0, sizeof(struct packet_command)); cgc.cmd[0] = GPCMD_SET_SPEED; /* SET CD SPEED */ cgc.cmd[2] = (speed >> 8) & 0xff; /* MSB for speed (in kbytes/sec) */ cgc.cmd[3] = speed & 0xff; /* LSB */ cgc.data_direction = DMA_NONE; cgc.timeout = IOCTL_TIMEOUT; if (sr_do_ioctl(cd, &cgc)) return -EIO; return 0; } /* ----------------------------------------------------------------------- */ /* this is called by the generic cdrom driver. arg is a _kernel_ pointer, */ /* because the generic cdrom driver does the user access stuff for us. */ /* only cdromreadtochdr and cdromreadtocentry are left - for use with the */ /* sr_disk_status interface for the generic cdrom driver. */ int sr_audio_ioctl(struct cdrom_device_info *cdi, unsigned int cmd, void *arg) { switch (cmd) { case CDROMREADTOCHDR: return sr_read_tochdr(cdi, arg); case CDROMREADTOCENTRY: return sr_read_tocentry(cdi, arg); case CDROMPLAYTRKIND: return sr_play_trkind(cdi, arg); default: return -EINVAL; } } /* ----------------------------------------------------------------------- * a function to read all sorts of funny cdrom sectors using the READ_CD * scsi-3 mmc command * * lba: linear block address * format: 0 = data (anything) * 1 = audio * 2 = data (mode 1) * 3 = data (mode 2) * 4 = data (mode 2 form1) * 5 = data (mode 2 form2) * blksize: 2048 | 2336 | 2340 | 2352 */ static int sr_read_cd(Scsi_CD *cd, unsigned char *dest, int lba, int format, int blksize) { struct packet_command cgc; #ifdef DEBUG sr_printk(KERN_INFO, cd, "sr_read_cd lba=%d format=%d blksize=%d\n", lba, format, blksize); #endif memset(&cgc, 0, sizeof(struct packet_command)); cgc.cmd[0] = GPCMD_READ_CD; /* READ_CD */ cgc.cmd[1] = ((format & 7) << 2); cgc.cmd[2] = (unsigned char) (lba >> 24) & 0xff; cgc.cmd[3] = (unsigned char) (lba >> 16) & 0xff; cgc.cmd[4] = (unsigned char) (lba >> 8) & 0xff; cgc.cmd[5] = (unsigned char) lba & 0xff; cgc.cmd[8] = 1; switch (blksize) { case 2336: cgc.cmd[9] = 0x58; break; case 2340: cgc.cmd[9] = 0x78; break; case 2352: cgc.cmd[9] = 0xf8; break; default: cgc.cmd[9] = 0x10; break; } cgc.buffer = dest; cgc.buflen = blksize; cgc.data_direction = DMA_FROM_DEVICE; cgc.timeout = IOCTL_TIMEOUT; return sr_do_ioctl(cd, &cgc); } /* * read sectors with blocksizes other than 2048 */ static int sr_read_sector(Scsi_CD *cd, int lba, int blksize, unsigned char *dest) { struct packet_command cgc; int rc; /* we try the READ CD command first... */ if (cd->readcd_known) { rc = sr_read_cd(cd, dest, lba, 0, blksize); if (-EDRIVE_CANT_DO_THIS != rc) return rc; cd->readcd_known = 0; sr_printk(KERN_INFO, cd, "CDROM does'nt support READ CD (0xbe) command\n"); /* fall & retry the other way */ } /* ... if this fails, we switch the blocksize using MODE SELECT */ if (blksize != cd->device->sector_size) { if (0 != (rc = sr_set_blocklength(cd, blksize))) return rc; } #ifdef DEBUG sr_printk(KERN_INFO, cd, "sr_read_sector lba=%d blksize=%d\n", lba, blksize); #endif memset(&cgc, 0, sizeof(struct packet_command)); cgc.cmd[0] = GPCMD_READ_10; cgc.cmd[2] = (unsigned char) (lba >> 24) & 0xff; cgc.cmd[3] = (unsigned char) (lba >> 16) & 0xff; cgc.cmd[4] = (unsigned char) (lba >> 8) & 0xff; cgc.cmd[5] = (unsigned char) lba & 0xff; cgc.cmd[8] = 1; cgc.buffer = dest; cgc.buflen = blksize; cgc.data_direction = DMA_FROM_DEVICE; cgc.timeout = IOCTL_TIMEOUT; rc = sr_do_ioctl(cd, &cgc); return rc; } /* * read a sector in raw mode to check the sector format * ret: 1 == mode2 (XA), 0 == mode1, <0 == error */ int sr_is_xa(Scsi_CD *cd) { unsigned char *raw_sector; int is_xa; if (!xa_test) return 0; raw_sector = kmalloc(2048, GFP_KERNEL | SR_GFP_DMA(cd)); if (!raw_sector) return -ENOMEM; if (0 == sr_read_sector(cd, cd->ms_offset + 16, CD_FRAMESIZE_RAW1, raw_sector)) { is_xa = (raw_sector[3] == 0x02) ? 1 : 0; } else { /* read a raw sector failed for some reason. */ is_xa = -1; } kfree(raw_sector); #ifdef DEBUG sr_printk(KERN_INFO, cd, "sr_is_xa: %d\n", is_xa); #endif return is_xa; }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_150_0
crossvul-cpp_data_good_622_4
/*====================================================================* - Copyright (C) 2001 Leptonica. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials - provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ANY - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *====================================================================*/ /*! * \file sel1.c * <pre> * * Basic ops on Sels and Selas * * Create/destroy/copy: * SELA *selaCreate() * void selaDestroy() * SEL *selCreate() * void selDestroy() * SEL *selCopy() * SEL *selCreateBrick() * SEL *selCreateComb() * * Helper proc: * l_int32 **create2dIntArray() * * Extension of sela: * SELA *selaAddSel() * static l_int32 selaExtendArray() * * Accessors: * l_int32 selaGetCount() * SEL *selaGetSel() * char *selGetName() * l_int32 selSetName() * l_int32 selaFindSelByName() * l_int32 selGetElement() * l_int32 selSetElement() * l_int32 selGetParameters() * l_int32 selSetOrigin() * l_int32 selGetTypeAtOrigin() * char *selaGetBrickName() * char *selaGetCombName() * static char *selaComputeCompositeParameters() * l_int32 getCompositeParameters() * SARRAY *selaGetSelnames() * * Max translations for erosion and hmt * l_int32 selFindMaxTranslations() * * Rotation by multiples of 90 degrees * SEL *selRotateOrth() * * Sela and Sel serialized I/O * SELA *selaRead() * SELA *selaReadStream() * SEL *selRead() * SEL *selReadStream() * l_int32 selaWrite() * l_int32 selaWriteStream() * l_int32 selWrite() * l_int32 selWriteStream() * * Building custom hit-miss sels from compiled strings * SEL *selCreateFromString() * char *selPrintToString() [for debugging] * * Building custom hit-miss sels from a simple file format * SELA *selaCreateFromFile() * static SEL *selCreateFromSArray() * * Making hit-only sels from Pta and Pix * SEL *selCreateFromPta() * SEL *selCreateFromPix() * * Making hit-miss sels from Pix and image files * SEL *selReadFromColorImage() * SEL *selCreateFromColorPix() * * Printable display of sel * PIX *selDisplayInPix() * PIX *selaDisplayInPix() * * Usage notes: * In this file we have seven functions that make sels: * (1) selCreate(), with input (h, w, [name]) * The generic function. Roll your own, using selSetElement(). * (2) selCreateBrick(), with input (h, w, cy, cx, val) * The most popular function. Makes a rectangular sel of * all hits, misses or don't-cares. We have many morphology * operations that create a sel of all hits, use it, and * destroy it. * (3) selCreateFromString() with input (text, h, w, [name]) * Adam Langley's clever function, allows you to make a hit-miss * sel from a string in code that is geometrically laid out * just like the actual sel. * (4) selaCreateFromFile() with input (filename) * This parses a simple file format to create an array of * hit-miss sels. The sel data uses the same encoding * as in (3), with geometrical layout enforced. * (5) selCreateFromPta() with input (pta, cy, cx, [name]) * Another way to make a sel with only hits. * (6) selCreateFromPix() with input (pix, cy, cx, [name]) * Yet another way to make a sel from hits. * (7) selCreateFromColorPix() with input (pix, name). * Another way to make a general hit-miss sel, starting with * an image editor. * In addition, there are three functions in selgen.c that * automatically generate a hit-miss sel from a pix and * a number of parameters. This is useful for problems like * "find all patterns that look like this one." * * Consistency, being the hobgoblin of small minds, * is adhered to here in the dimensioning and accessing of sels. * Everything is done in standard matrix (row, column) order. * When we set specific elements in a sel, we likewise use * (row, col) ordering: * selSetElement(), with input (row, col, type) * </pre> */ #include <string.h> #include "allheaders.h" static const l_int32 L_BUFSIZE = 256; /* hardcoded below in sscanf */ static const l_int32 INITIAL_PTR_ARRAYSIZE = 50; /* n'import quoi */ static const l_int32 MANY_SELS = 1000; /* Static functions */ static l_int32 selaExtendArray(SELA *sela); static SEL *selCreateFromSArray(SARRAY *sa, l_int32 first, l_int32 last); struct CompParameterMap { l_int32 size; l_int32 size1; l_int32 size2; char selnameh1[20]; char selnameh2[20]; char selnamev1[20]; char selnamev2[20]; }; static const struct CompParameterMap comp_parameter_map[] = { { 2, 2, 1, "sel_2h", "", "sel_2v", "" }, { 3, 3, 1, "sel_3h", "", "sel_3v", "" }, { 4, 2, 2, "sel_2h", "sel_comb_4h", "sel_2v", "sel_comb_4v" }, { 5, 5, 1, "sel_5h", "", "sel_5v", "" }, { 6, 3, 2, "sel_3h", "sel_comb_6h", "sel_3v", "sel_comb_6v" }, { 7, 7, 1, "sel_7h", "", "sel_7v", "" }, { 8, 4, 2, "sel_4h", "sel_comb_8h", "sel_4v", "sel_comb_8v" }, { 9, 3, 3, "sel_3h", "sel_comb_9h", "sel_3v", "sel_comb_9v" }, { 10, 5, 2, "sel_5h", "sel_comb_10h", "sel_5v", "sel_comb_10v" }, { 11, 4, 3, "sel_4h", "sel_comb_12h", "sel_4v", "sel_comb_12v" }, { 12, 4, 3, "sel_4h", "sel_comb_12h", "sel_4v", "sel_comb_12v" }, { 13, 4, 3, "sel_4h", "sel_comb_12h", "sel_4v", "sel_comb_12v" }, { 14, 7, 2, "sel_7h", "sel_comb_14h", "sel_7v", "sel_comb_14v" }, { 15, 5, 3, "sel_5h", "sel_comb_15h", "sel_5v", "sel_comb_15v" }, { 16, 4, 4, "sel_4h", "sel_comb_16h", "sel_4v", "sel_comb_16v" }, { 17, 4, 4, "sel_4h", "sel_comb_16h", "sel_4v", "sel_comb_16v" }, { 18, 6, 3, "sel_6h", "sel_comb_18h", "sel_6v", "sel_comb_18v" }, { 19, 5, 4, "sel_5h", "sel_comb_20h", "sel_5v", "sel_comb_20v" }, { 20, 5, 4, "sel_5h", "sel_comb_20h", "sel_5v", "sel_comb_20v" }, { 21, 7, 3, "sel_7h", "sel_comb_21h", "sel_7v", "sel_comb_21v" }, { 22, 11, 2, "sel_11h", "sel_comb_22h", "sel_11v", "sel_comb_22v" }, { 23, 6, 4, "sel_6h", "sel_comb_24h", "sel_6v", "sel_comb_24v" }, { 24, 6, 4, "sel_6h", "sel_comb_24h", "sel_6v", "sel_comb_24v" }, { 25, 5, 5, "sel_5h", "sel_comb_25h", "sel_5v", "sel_comb_25v" }, { 26, 5, 5, "sel_5h", "sel_comb_25h", "sel_5v", "sel_comb_25v" }, { 27, 9, 3, "sel_9h", "sel_comb_27h", "sel_9v", "sel_comb_27v" }, { 28, 7, 4, "sel_7h", "sel_comb_28h", "sel_7v", "sel_comb_28v" }, { 29, 6, 5, "sel_6h", "sel_comb_30h", "sel_6v", "sel_comb_30v" }, { 30, 6, 5, "sel_6h", "sel_comb_30h", "sel_6v", "sel_comb_30v" }, { 31, 6, 5, "sel_6h", "sel_comb_30h", "sel_6v", "sel_comb_30v" }, { 32, 8, 4, "sel_8h", "sel_comb_32h", "sel_8v", "sel_comb_32v" }, { 33, 11, 3, "sel_11h", "sel_comb_33h", "sel_11v", "sel_comb_33v" }, { 34, 7, 5, "sel_7h", "sel_comb_35h", "sel_7v", "sel_comb_35v" }, { 35, 7, 5, "sel_7h", "sel_comb_35h", "sel_7v", "sel_comb_35v" }, { 36, 6, 6, "sel_6h", "sel_comb_36h", "sel_6v", "sel_comb_36v" }, { 37, 6, 6, "sel_6h", "sel_comb_36h", "sel_6v", "sel_comb_36v" }, { 38, 6, 6, "sel_6h", "sel_comb_36h", "sel_6v", "sel_comb_36v" }, { 39, 13, 3, "sel_13h", "sel_comb_39h", "sel_13v", "sel_comb_39v" }, { 40, 8, 5, "sel_8h", "sel_comb_40h", "sel_8v", "sel_comb_40v" }, { 41, 7, 6, "sel_7h", "sel_comb_42h", "sel_7v", "sel_comb_42v" }, { 42, 7, 6, "sel_7h", "sel_comb_42h", "sel_7v", "sel_comb_42v" }, { 43, 7, 6, "sel_7h", "sel_comb_42h", "sel_7v", "sel_comb_42v" }, { 44, 11, 4, "sel_11h", "sel_comb_44h", "sel_11v", "sel_comb_44v" }, { 45, 9, 5, "sel_9h", "sel_comb_45h", "sel_9v", "sel_comb_45v" }, { 46, 9, 5, "sel_9h", "sel_comb_45h", "sel_9v", "sel_comb_45v" }, { 47, 8, 6, "sel_8h", "sel_comb_48h", "sel_8v", "sel_comb_48v" }, { 48, 8, 6, "sel_8h", "sel_comb_48h", "sel_8v", "sel_comb_48v" }, { 49, 7, 7, "sel_7h", "sel_comb_49h", "sel_7v", "sel_comb_49v" }, { 50, 10, 5, "sel_10h", "sel_comb_50h", "sel_10v", "sel_comb_50v" }, { 51, 10, 5, "sel_10h", "sel_comb_50h", "sel_10v", "sel_comb_50v" }, { 52, 13, 4, "sel_13h", "sel_comb_52h", "sel_13v", "sel_comb_52v" }, { 53, 9, 6, "sel_9h", "sel_comb_54h", "sel_9v", "sel_comb_54v" }, { 54, 9, 6, "sel_9h", "sel_comb_54h", "sel_9v", "sel_comb_54v" }, { 55, 11, 5, "sel_11h", "sel_comb_55h", "sel_11v", "sel_comb_55v" }, { 56, 8, 7, "sel_8h", "sel_comb_56h", "sel_8v", "sel_comb_56v" }, { 57, 8, 7, "sel_8h", "sel_comb_56h", "sel_8v", "sel_comb_56v" }, { 58, 8, 7, "sel_8h", "sel_comb_56h", "sel_8v", "sel_comb_56v" }, { 59, 10, 6, "sel_10h", "sel_comb_60h", "sel_10v", "sel_comb_60v" }, { 60, 10, 6, "sel_10h", "sel_comb_60h", "sel_10v", "sel_comb_60v" }, { 61, 10, 6, "sel_10h", "sel_comb_60h", "sel_10v", "sel_comb_60v" }, { 62, 9, 7, "sel_9h", "sel_comb_63h", "sel_9v", "sel_comb_63v" }, { 63, 9, 7, "sel_9h", "sel_comb_63h", "sel_9v", "sel_comb_63v" } }; /*------------------------------------------------------------------------* * Create / Destroy / Copy * *------------------------------------------------------------------------*/ /*! * \brief selaCreate() * * \param[in] n initial number of sel ptrs; use 0 for default * \return sela, or NULL on error */ SELA * selaCreate(l_int32 n) { SELA *sela; PROCNAME("selaCreate"); if (n <= 0) n = INITIAL_PTR_ARRAYSIZE; if (n > MANY_SELS) L_WARNING("%d sels\n", procName, n); if ((sela = (SELA *)LEPT_CALLOC(1, sizeof(SELA))) == NULL) return (SELA *)ERROR_PTR("sela not made", procName, NULL); sela->nalloc = n; sela->n = 0; /* make array of se ptrs */ if ((sela->sel = (SEL **)LEPT_CALLOC(n, sizeof(SEL *))) == NULL) { LEPT_FREE(sela); return (SELA *)ERROR_PTR("sel ptrs not made", procName, NULL); } return sela; } /*! * \brief selaDestroy() * * \param[in,out] psela to be nulled * \return void */ void selaDestroy(SELA **psela) { SELA *sela; l_int32 i; if (!psela) return; if ((sela = *psela) == NULL) return; for (i = 0; i < sela->n; i++) selDestroy(&sela->sel[i]); LEPT_FREE(sela->sel); LEPT_FREE(sela); *psela = NULL; return; } /*! * \brief selCreate() * * \param[in] height, width * \param[in] name [optional] sel name; can be null * \return sel, or NULL on error * * <pre> * Notes: * (1) selCreate() initializes all values to 0. * (2) After this call, (cy,cx) and nonzero data values must be * assigned. If a text name is not assigned here, it will * be needed later when the sel is put into a sela. * </pre> */ SEL * selCreate(l_int32 height, l_int32 width, const char *name) { SEL *sel; PROCNAME("selCreate"); if ((sel = (SEL *)LEPT_CALLOC(1, sizeof(SEL))) == NULL) return (SEL *)ERROR_PTR("sel not made", procName, NULL); if (name) sel->name = stringNew(name); sel->sy = height; sel->sx = width; if ((sel->data = create2dIntArray(height, width)) == NULL) { LEPT_FREE(sel->name); LEPT_FREE(sel); return (SEL *)ERROR_PTR("data not allocated", procName, NULL); } return sel; } /*! * \brief selDestroy() * * \param[in,out] psel to be nulled * \return void */ void selDestroy(SEL **psel) { l_int32 i; SEL *sel; PROCNAME("selDestroy"); if (psel == NULL) { L_WARNING("ptr address is NULL!\n", procName); return; } if ((sel = *psel) == NULL) return; for (i = 0; i < sel->sy; i++) LEPT_FREE(sel->data[i]); LEPT_FREE(sel->data); if (sel->name) LEPT_FREE(sel->name); LEPT_FREE(sel); *psel = NULL; return; } /*! * \brief selCopy() * * \param[in] sel * \return a copy of the sel, or NULL on error */ SEL * selCopy(SEL *sel) { l_int32 sx, sy, cx, cy, i, j; SEL *csel; PROCNAME("selCopy"); if (!sel) return (SEL *)ERROR_PTR("sel not defined", procName, NULL); if ((csel = (SEL *)LEPT_CALLOC(1, sizeof(SEL))) == NULL) return (SEL *)ERROR_PTR("csel not made", procName, NULL); selGetParameters(sel, &sy, &sx, &cy, &cx); csel->sy = sy; csel->sx = sx; csel->cy = cy; csel->cx = cx; if ((csel->data = create2dIntArray(sy, sx)) == NULL) { LEPT_FREE(csel); return (SEL *)ERROR_PTR("sel data not made", procName, NULL); } for (i = 0; i < sy; i++) for (j = 0; j < sx; j++) csel->data[i][j] = sel->data[i][j]; if (sel->name) csel->name = stringNew(sel->name); return csel; } /*! * \brief selCreateBrick() * * \param[in] h, w height, width * \param[in] cy, cx origin, relative to UL corner at 0,0 * \param[in] type SEL_HIT, SEL_MISS, or SEL_DONT_CARE * \return sel, or NULL on error * * <pre> * Notes: * (1) This is a rectangular sel of all hits, misses or don't cares. * </pre> */ SEL * selCreateBrick(l_int32 h, l_int32 w, l_int32 cy, l_int32 cx, l_int32 type) { l_int32 i, j; SEL *sel; PROCNAME("selCreateBrick"); if (h <= 0 || w <= 0) return (SEL *)ERROR_PTR("h and w must both be > 0", procName, NULL); if (type != SEL_HIT && type != SEL_MISS && type != SEL_DONT_CARE) return (SEL *)ERROR_PTR("invalid sel element type", procName, NULL); if ((sel = selCreate(h, w, NULL)) == NULL) return (SEL *)ERROR_PTR("sel not made", procName, NULL); selSetOrigin(sel, cy, cx); for (i = 0; i < h; i++) for (j = 0; j < w; j++) sel->data[i][j] = type; return sel; } /*! * \brief selCreateComb() * * \param[in] factor1 contiguous space between comb tines * \param[in] factor2 number of comb tines * \param[in] direction L_HORIZ, L_VERT * \return sel, or NULL on error * * <pre> * Notes: * (1) This generates a comb Sel of hits with the origin as * near the center as possible. * (2) In use, this is complemented by a brick sel of size %factor1, * Both brick and comb sels are made by selectComposableSels(). * </pre> */ SEL * selCreateComb(l_int32 factor1, l_int32 factor2, l_int32 direction) { l_int32 i, size, z; SEL *sel; PROCNAME("selCreateComb"); if (factor1 < 1 || factor2 < 1) return (SEL *)ERROR_PTR("factors must be >= 1", procName, NULL); if (direction != L_HORIZ && direction != L_VERT) return (SEL *)ERROR_PTR("invalid direction", procName, NULL); size = factor1 * factor2; if (direction == L_HORIZ) { sel = selCreate(1, size, NULL); selSetOrigin(sel, 0, size / 2); } else { sel = selCreate(size, 1, NULL); selSetOrigin(sel, size / 2, 0); } /* Lay down the elements of the comb */ for (i = 0; i < factor2; i++) { z = factor1 / 2 + i * factor1; /* fprintf(stderr, "i = %d, factor1 = %d, factor2 = %d, z = %d\n", i, factor1, factor2, z); */ if (direction == L_HORIZ) selSetElement(sel, 0, z, SEL_HIT); else selSetElement(sel, z, 0, SEL_HIT); } return sel; } /*! * \brief create2dIntArray() * * \param[in] sy rows == height * \param[in] sx columns == width * \return doubly indexed array i.e., an array of sy row pointers, * each of which points to an array of sx ints * * <pre> * Notes: * (1) The array[sy][sx] is indexed in standard "matrix notation", * with the row index first. * </pre> */ l_int32 ** create2dIntArray(l_int32 sy, l_int32 sx) { l_int32 i, j, success; l_int32 **array; PROCNAME("create2dIntArray"); if ((array = (l_int32 **)LEPT_CALLOC(sy, sizeof(l_int32 *))) == NULL) return (l_int32 **)ERROR_PTR("ptr array not made", procName, NULL); success = TRUE; for (i = 0; i < sy; i++) { if ((array[i] = (l_int32 *)LEPT_CALLOC(sx, sizeof(l_int32))) == NULL) { success = FALSE; break; } } if (success) return array; /* Cleanup after error */ for (j = 0; j < i; j++) LEPT_FREE(array[j]); LEPT_FREE(array); return (l_int32 **)ERROR_PTR("array not made", procName, NULL); } /*------------------------------------------------------------------------* * Extension of sela * *------------------------------------------------------------------------*/ /*! * \brief selaAddSel() * * \param[in] sela * \param[in] sel to be added * \param[in] selname ignored if already defined in sel; * req'd in sel when added to a sela * \param[in] copyflag L_INSERT or L_COPY * \return 0 if OK; 1 on error * * <pre> * Notes: * (1) This adds a sel, either inserting or making a copy. * (2) Because every sel in a sela must have a name, it copies * the input name if necessary. You can input NULL for * selname if the sel already has a name. * </pre> */ l_int32 selaAddSel(SELA *sela, SEL *sel, const char *selname, l_int32 copyflag) { l_int32 n; SEL *csel; PROCNAME("selaAddSel"); if (!sela) return ERROR_INT("sela not defined", procName, 1); if (!sel) return ERROR_INT("sel not defined", procName, 1); if (!sel->name && !selname) return ERROR_INT("added sel must have name", procName, 1); if (copyflag != L_INSERT && copyflag != L_COPY) return ERROR_INT("invalid copyflag", procName, 1); if (copyflag == L_COPY) { if ((csel = selCopy(sel)) == NULL) return ERROR_INT("csel not made", procName, 1); } else { /* copyflag == L_INSERT */ csel = sel; } if (!csel->name) csel->name = stringNew(selname); n = selaGetCount(sela); if (n >= sela->nalloc) selaExtendArray(sela); sela->sel[n] = csel; sela->n++; return 0; } /*! * \brief selaExtendArray() * * \param[in] sela * \return 0 if OK; 1 on error */ static l_int32 selaExtendArray(SELA *sela) { PROCNAME("selaExtendArray"); if (!sela) return ERROR_INT("sela not defined", procName, 1); if ((sela->sel = (SEL **)reallocNew((void **)&sela->sel, sizeof(SEL *) * sela->nalloc, 2 * sizeof(SEL *) * sela->nalloc)) == NULL) return ERROR_INT("new ptr array not returned", procName, 1); sela->nalloc = 2 * sela->nalloc; return 0; } /*----------------------------------------------------------------------* * Accessors * *----------------------------------------------------------------------*/ /*! * \brief selaGetCount() * * \param[in] sela * \return count, or 0 on error */ l_int32 selaGetCount(SELA *sela) { PROCNAME("selaGetCount"); if (!sela) return ERROR_INT("sela not defined", procName, 0); return sela->n; } /*! * \brief selaGetSel() * * \param[in] sela * \param[in] i index of sel to be retrieved not copied * \return sel, or NULL on error * * <pre> * Notes: * (1) This returns a ptr to the sel, not a copy, so the caller * must not destroy it! * </pre> */ SEL * selaGetSel(SELA *sela, l_int32 i) { PROCNAME("selaGetSel"); if (!sela) return (SEL *)ERROR_PTR("sela not defined", procName, NULL); if (i < 0 || i >= sela->n) return (SEL *)ERROR_PTR("invalid index", procName, NULL); return sela->sel[i]; } /*! * \brief selGetName() * * \param[in] sel * \return sel name not copied, or NULL if no name or on error */ char * selGetName(SEL *sel) { PROCNAME("selGetName"); if (!sel) return (char *)ERROR_PTR("sel not defined", procName, NULL); return sel->name; } /*! * \brief selSetName() * * \param[in] sel * \param[in] name [optional]; can be null * \return 0 if OK, 1 on error * * <pre> * Notes: * (1) Always frees the existing sel name, if defined. * (2) If name is not defined, just clears any existing sel name. * </pre> */ l_int32 selSetName(SEL *sel, const char *name) { PROCNAME("selSetName"); if (!sel) return ERROR_INT("sel not defined", procName, 1); return stringReplace(&sel->name, name); } /*! * \brief selaFindSelByName() * * \param[in] sela * \param[in] name sel name * \param[out] pindex [optional] * \param[in] psel [optional] sel (not a copy) * \return 0 if OK; 1 on error */ l_int32 selaFindSelByName(SELA *sela, const char *name, l_int32 *pindex, SEL **psel) { l_int32 i, n; char *sname; SEL *sel; PROCNAME("selaFindSelByName"); if (pindex) *pindex = -1; if (psel) *psel = NULL; if (!sela) return ERROR_INT("sela not defined", procName, 1); n = selaGetCount(sela); for (i = 0; i < n; i++) { if ((sel = selaGetSel(sela, i)) == NULL) { L_WARNING("missing sel\n", procName); continue; } sname = selGetName(sel); if (sname && (!strcmp(name, sname))) { if (pindex) *pindex = i; if (psel) *psel = sel; return 0; } } return 1; } /*! * \brief selGetElement() * * \param[in] sel * \param[in] row * \param[in] col * \param[out] ptype SEL_HIT, SEL_MISS, SEL_DONT_CARE * \return 0 if OK; 1 on error */ l_int32 selGetElement(SEL *sel, l_int32 row, l_int32 col, l_int32 *ptype) { PROCNAME("selGetElement"); if (!ptype) return ERROR_INT("&type not defined", procName, 1); *ptype = SEL_DONT_CARE; if (!sel) return ERROR_INT("sel not defined", procName, 1); if (row < 0 || row >= sel->sy) return ERROR_INT("sel row out of bounds", procName, 1); if (col < 0 || col >= sel->sx) return ERROR_INT("sel col out of bounds", procName, 1); *ptype = sel->data[row][col]; return 0; } /*! * \brief selSetElement() * * \param[in] sel * \param[in] row * \param[in] col * \param[in] type SEL_HIT, SEL_MISS, SEL_DONT_CARE * \return 0 if OK; 1 on error * * <pre> * Notes: * (1) Because we use row and column to index into an array, * they are always non-negative. The location of the origin * (and the type of operation) determine the actual * direction of the rasterop. * </pre> */ l_int32 selSetElement(SEL *sel, l_int32 row, l_int32 col, l_int32 type) { PROCNAME("selSetElement"); if (!sel) return ERROR_INT("sel not defined", procName, 1); if (type != SEL_HIT && type != SEL_MISS && type != SEL_DONT_CARE) return ERROR_INT("invalid sel element type", procName, 1); if (row < 0 || row >= sel->sy) return ERROR_INT("sel row out of bounds", procName, 1); if (col < 0 || col >= sel->sx) return ERROR_INT("sel col out of bounds", procName, 1); sel->data[row][col] = type; return 0; } /*! * \brief selGetParameters() * * \param[in] sel * \param[out] psy, psx, pcy, pcx [optional] each can be null * \return 0 if OK, 1 on error */ l_int32 selGetParameters(SEL *sel, l_int32 *psy, l_int32 *psx, l_int32 *pcy, l_int32 *pcx) { PROCNAME("selGetParameters"); if (psy) *psy = 0; if (psx) *psx = 0; if (pcy) *pcy = 0; if (pcx) *pcx = 0; if (!sel) return ERROR_INT("sel not defined", procName, 1); if (psy) *psy = sel->sy; if (psx) *psx = sel->sx; if (pcy) *pcy = sel->cy; if (pcx) *pcx = sel->cx; return 0; } /*! * \brief selSetOrigin() * * \param[in] sel * \param[in] cy, cx * \return 0 if OK; 1 on error */ l_int32 selSetOrigin(SEL *sel, l_int32 cy, l_int32 cx) { PROCNAME("selSetOrigin"); if (!sel) return ERROR_INT("sel not defined", procName, 1); sel->cy = cy; sel->cx = cx; return 0; } /*! * \brief selGetTypeAtOrigin() * * \param[in] sel * \param[out] ptype SEL_HIT, SEL_MISS, SEL_DONT_CARE * \return 0 if OK; 1 on error or if origin is not found */ l_int32 selGetTypeAtOrigin(SEL *sel, l_int32 *ptype) { l_int32 sx, sy, cx, cy, i, j; PROCNAME("selGetTypeAtOrigin"); if (!ptype) return ERROR_INT("&type not defined", procName, 1); *ptype = SEL_DONT_CARE; /* init */ if (!sel) return ERROR_INT("sel not defined", procName, 1); selGetParameters(sel, &sy, &sx, &cy, &cx); for (i = 0; i < sy; i++) { for (j = 0; j < sx; j++) { if (i == cy && j == cx) { selGetElement(sel, i, j, ptype); return 0; } } } return ERROR_INT("sel origin not found", procName, 1); } /*! * \brief selaGetBrickName() * * \param[in] sela * \param[in] hsize, vsize of brick sel * \return sel name new string, or NULL if no name or on error */ char * selaGetBrickName(SELA *sela, l_int32 hsize, l_int32 vsize) { l_int32 i, nsels, sx, sy; SEL *sel; PROCNAME("selaGetBrickName"); if (!sela) return (char *)ERROR_PTR("sela not defined", procName, NULL); nsels = selaGetCount(sela); for (i = 0; i < nsels; i++) { sel = selaGetSel(sela, i); selGetParameters(sel, &sy, &sx, NULL, NULL); if (hsize == sx && vsize == sy) return stringNew(selGetName(sel)); } return (char *)ERROR_PTR("sel not found", procName, NULL); } /*! * \brief selaGetCombName() * * \param[in] sela * \param[in] size the product of sizes of the brick and comb parts * \param[in] direction L_HORIZ, L_VERT * \return sel name new string, or NULL if name not found or on error * * <pre> * Notes: * (1) Combs are by definition 1-dimensional, either horiz or vert. * (2) Use this with comb Sels; e.g., from selaAddDwaCombs(). * </pre> */ char * selaGetCombName(SELA *sela, l_int32 size, l_int32 direction) { char *selname; char combname[L_BUFSIZE]; l_int32 i, nsels, sx, sy, found; SEL *sel; PROCNAME("selaGetCombName"); if (!sela) return (char *)ERROR_PTR("sela not defined", procName, NULL); if (direction != L_HORIZ && direction != L_VERT) return (char *)ERROR_PTR("invalid direction", procName, NULL); /* Derive the comb name we're looking for */ if (direction == L_HORIZ) snprintf(combname, L_BUFSIZE, "sel_comb_%dh", size); else /* direction == L_VERT */ snprintf(combname, L_BUFSIZE, "sel_comb_%dv", size); found = FALSE; nsels = selaGetCount(sela); for (i = 0; i < nsels; i++) { sel = selaGetSel(sela, i); selGetParameters(sel, &sy, &sx, NULL, NULL); if (sy != 1 && sx != 1) /* 2-D; not a comb */ continue; selname = selGetName(sel); if (!strcmp(selname, combname)) { found = TRUE; break; } } if (found) return stringNew(selname); else return (char *)ERROR_PTR("sel not found", procName, NULL); } /* --------- Function used to generate code in this file ---------- */ #if 0 static void selaComputeCompositeParameters(const char *fileout); /*! * \brief selaComputeCompParameters() * * \param[in] output filename * \return void * * <pre> * Notes: * (1) This static function was used to construct the comp_parameter_map[] * array at the top of this file. It is static because it does * not need to be called again. It remains here to show how * the composite parameter map was computed. * (2) The output file was pasted directly into comp_parameter_map[]. * The composite parameter map is used to quickly determine * the linear decomposition parameters and sel names. * </pre> */ static void selaComputeCompositeParameters(const char *fileout) { char *str, *nameh1, *nameh2, *namev1, *namev2; char buf[L_BUFSIZE]; l_int32 size, size1, size2, len; SARRAY *sa; SELA *selabasic, *selacomb; selabasic = selaAddBasic(NULL); selacomb = selaAddDwaCombs(NULL); sa = sarrayCreate(64); for (size = 2; size < 64; size++) { selectComposableSizes(size, &size1, &size2); nameh1 = selaGetBrickName(selabasic, size1, 1); namev1 = selaGetBrickName(selabasic, 1, size1); if (size2 > 1) { nameh2 = selaGetCombName(selacomb, size1 * size2, L_HORIZ); namev2 = selaGetCombName(selacomb, size1 * size2, L_VERT); } else { nameh2 = stringNew(""); namev2 = stringNew(""); } snprintf(buf, L_BUFSIZE, " { %d, %d, %d, \"%s\", \"%s\", \"%s\", \"%s\" },", size, size1, size2, nameh1, nameh2, namev1, namev2); sarrayAddString(sa, buf, L_COPY); LEPT_FREE(nameh1); LEPT_FREE(nameh2); LEPT_FREE(namev1); LEPT_FREE(namev2); } str = sarrayToString(sa, 1); len = strlen(str); l_binaryWrite(fileout, "w", str, len + 1); LEPT_FREE(str); sarrayDestroy(&sa); selaDestroy(&selabasic); selaDestroy(&selacomb); return; } #endif /* -------------------------------------------------------------------- */ /*! * \brief getCompositeParameters() * * \param[in] size * \param[out] psize1 [optional] brick factor size * \param[out] psize2 [optional] comb factor size * \param[out] pnameh1 [optional] name of horiz brick * \param[out] pnameh2 [optional] name of horiz comb * \param[out] pnamev1 [optional] name of vert brick * \param[out] pnamev2 [optional] name of vert comb * \return 0 if OK, 1 on error * * <pre> * Notes: * (1) This uses the big lookup table at the top of this file. * (2) All returned strings are copies that must be freed. * </pre> */ l_int32 getCompositeParameters(l_int32 size, l_int32 *psize1, l_int32 *psize2, char **pnameh1, char **pnameh2, char **pnamev1, char **pnamev2) { l_int32 index; PROCNAME("selaGetSelnames"); if (psize1) *psize1 = 0; if (psize2) *psize2 = 0; if (pnameh1) *pnameh1 = NULL; if (pnameh2) *pnameh2 = NULL; if (pnamev1) *pnamev1 = NULL; if (pnamev2) *pnamev2 = NULL; if (size < 2 || size > 63) return ERROR_INT("valid size range is {2 ... 63}", procName, 1); index = size - 2; if (psize1) *psize1 = comp_parameter_map[index].size1; if (psize2) *psize2 = comp_parameter_map[index].size2; if (pnameh1) *pnameh1 = stringNew(comp_parameter_map[index].selnameh1); if (pnameh2) *pnameh2 = stringNew(comp_parameter_map[index].selnameh2); if (pnamev1) *pnamev1 = stringNew(comp_parameter_map[index].selnamev1); if (pnamev2) *pnamev2 = stringNew(comp_parameter_map[index].selnamev2); return 0; } /*! * \brief selaGetSelnames() * * \param[in] sela * \return sa of all sel names, or NULL on error */ SARRAY * selaGetSelnames(SELA *sela) { char *selname; l_int32 i, n; SEL *sel; SARRAY *sa; PROCNAME("selaGetSelnames"); if (!sela) return (SARRAY *)ERROR_PTR("sela not defined", procName, NULL); if ((n = selaGetCount(sela)) == 0) return (SARRAY *)ERROR_PTR("no sels in sela", procName, NULL); if ((sa = sarrayCreate(n)) == NULL) return (SARRAY *)ERROR_PTR("sa not made", procName, NULL); for (i = 0; i < n; i++) { sel = selaGetSel(sela, i); selname = selGetName(sel); sarrayAddString(sa, selname, L_COPY); } return sa; } /*----------------------------------------------------------------------* * Max translations for erosion and hmt * *----------------------------------------------------------------------*/ /*! * \brief selFindMaxTranslations() * * \param[in] sel * \param[out] pxp, pyp, pxn, pyn max shifts * \return 0 if OK; 1 on error * * <pre> * Notes: These are the maximum shifts for the erosion operation. * For example, when j < cx, the shift of the image * is +x to the cx. This is a positive xp shift. * </pre> */ l_int32 selFindMaxTranslations(SEL *sel, l_int32 *pxp, l_int32 *pyp, l_int32 *pxn, l_int32 *pyn) { l_int32 sx, sy, cx, cy, i, j; l_int32 maxxp, maxyp, maxxn, maxyn; PROCNAME("selaFindMaxTranslations"); if (!pxp || !pyp || !pxn || !pyn) return ERROR_INT("&xp (etc) defined", procName, 1); *pxp = *pyp = *pxn = *pyn = 0; if (!sel) return ERROR_INT("sel not defined", procName, 1); selGetParameters(sel, &sy, &sx, &cy, &cx); maxxp = maxyp = maxxn = maxyn = 0; for (i = 0; i < sy; i++) { for (j = 0; j < sx; j++) { if (sel->data[i][j] == 1) { maxxp = L_MAX(maxxp, cx - j); maxyp = L_MAX(maxyp, cy - i); maxxn = L_MAX(maxxn, j - cx); maxyn = L_MAX(maxyn, i - cy); } } } *pxp = maxxp; *pyp = maxyp; *pxn = maxxn; *pyn = maxyn; return 0; } /*----------------------------------------------------------------------* * Rotation by multiples of 90 degrees * *----------------------------------------------------------------------*/ /*! * \brief selRotateOrth() * * \param[in] sel * \param[in] quads 0 - 4; number of 90 degree cw rotations * \return seld, or NULL on error */ SEL * selRotateOrth(SEL *sel, l_int32 quads) { l_int32 i, j, ni, nj, sx, sy, cx, cy, nsx, nsy, ncx, ncy, type; SEL *seld; PROCNAME("selRotateOrth"); if (!sel) return (SEL *)ERROR_PTR("sel not defined", procName, NULL); if (quads < 0 || quads > 4) return (SEL *)ERROR_PTR("quads not in {0,1,2,3,4}", procName, NULL); if (quads == 0 || quads == 4) return selCopy(sel); selGetParameters(sel, &sy, &sx, &cy, &cx); if (quads == 1) { /* 90 degrees cw */ nsx = sy; nsy = sx; ncx = sy - cy - 1; ncy = cx; } else if (quads == 2) { /* 180 degrees cw */ nsx = sx; nsy = sy; ncx = sx - cx - 1; ncy = sy - cy - 1; } else { /* 270 degrees cw */ nsx = sy; nsy = sx; ncx = cy; ncy = sx - cx - 1; } seld = selCreateBrick(nsy, nsx, ncy, ncx, SEL_DONT_CARE); if (sel->name) seld->name = stringNew(sel->name); for (i = 0; i < sy; i++) { for (j = 0; j < sx; j++) { selGetElement(sel, i, j, &type); if (quads == 1) { ni = j; nj = sy - i - 1; } else if (quads == 2) { ni = sy - i - 1; nj = sx - j - 1; } else { /* quads == 3 */ ni = sx - j - 1; nj = i; } selSetElement(seld, ni, nj, type); } } return seld; } /*----------------------------------------------------------------------* * Sela and Sel serialized I/O * *----------------------------------------------------------------------*/ /*! * \brief selaRead() * * \param[in] fname filename * \return sela, or NULL on error */ SELA * selaRead(const char *fname) { FILE *fp; SELA *sela; PROCNAME("selaRead"); if (!fname) return (SELA *)ERROR_PTR("fname not defined", procName, NULL); if ((fp = fopenReadStream(fname)) == NULL) return (SELA *)ERROR_PTR("stream not opened", procName, NULL); if ((sela = selaReadStream(fp)) == NULL) { fclose(fp); return (SELA *)ERROR_PTR("sela not returned", procName, NULL); } fclose(fp); return sela; } /*! * \brief selaReadStream() * * \param[in] fp file stream * \return sela, or NULL on error */ SELA * selaReadStream(FILE *fp) { l_int32 i, n, version; SEL *sel; SELA *sela; PROCNAME("selaReadStream"); if (!fp) return (SELA *)ERROR_PTR("stream not defined", procName, NULL); if (fscanf(fp, "\nSela Version %d\n", &version) != 1) return (SELA *)ERROR_PTR("not a sela file", procName, NULL); if (version != SEL_VERSION_NUMBER) return (SELA *)ERROR_PTR("invalid sel version", procName, NULL); if (fscanf(fp, "Number of Sels = %d\n\n", &n) != 1) return (SELA *)ERROR_PTR("not a sela file", procName, NULL); if ((sela = selaCreate(n)) == NULL) return (SELA *)ERROR_PTR("sela not made", procName, NULL); sela->nalloc = n; for (i = 0; i < n; i++) { if ((sel = selReadStream(fp)) == NULL) { selaDestroy(&sela); return (SELA *)ERROR_PTR("sel not read", procName, NULL); } selaAddSel(sela, sel, NULL, 0); } return sela; } /*! * \brief selRead() * * \param[in] fname filename * \return sel, or NULL on error */ SEL * selRead(const char *fname) { FILE *fp; SEL *sel; PROCNAME("selRead"); if (!fname) return (SEL *)ERROR_PTR("fname not defined", procName, NULL); if ((fp = fopenReadStream(fname)) == NULL) return (SEL *)ERROR_PTR("stream not opened", procName, NULL); if ((sel = selReadStream(fp)) == NULL) { fclose(fp); return (SEL *)ERROR_PTR("sela not returned", procName, NULL); } fclose(fp); return sel; } /*! * \brief selReadStream() * * \param[in] fp file stream * \return sel, or NULL on error */ SEL * selReadStream(FILE *fp) { char *selname; char linebuf[L_BUFSIZE]; l_int32 sy, sx, cy, cx, i, j, version, ignore; SEL *sel; PROCNAME("selReadStream"); if (!fp) return (SEL *)ERROR_PTR("stream not defined", procName, NULL); if (fscanf(fp, " Sel Version %d\n", &version) != 1) return (SEL *)ERROR_PTR("not a sel file", procName, NULL); if (version != SEL_VERSION_NUMBER) return (SEL *)ERROR_PTR("invalid sel version", procName, NULL); if (fgets(linebuf, L_BUFSIZE, fp) == NULL) return (SEL *)ERROR_PTR("error reading into linebuf", procName, NULL); selname = stringNew(linebuf); sscanf(linebuf, " ------ %200s ------", selname); if (fscanf(fp, " sy = %d, sx = %d, cy = %d, cx = %d\n", &sy, &sx, &cy, &cx) != 4) { LEPT_FREE(selname); return (SEL *)ERROR_PTR("dimensions not read", procName, NULL); } if ((sel = selCreate(sy, sx, selname)) == NULL) { LEPT_FREE(selname); return (SEL *)ERROR_PTR("sel not made", procName, NULL); } selSetOrigin(sel, cy, cx); for (i = 0; i < sy; i++) { ignore = fscanf(fp, " "); for (j = 0; j < sx; j++) ignore = fscanf(fp, "%1d", &sel->data[i][j]); ignore = fscanf(fp, "\n"); } ignore = fscanf(fp, "\n"); LEPT_FREE(selname); return sel; } /*! * \brief selaWrite() * * \param[in] fname filename * \param[in] sela * \return 0 if OK, 1 on error */ l_int32 selaWrite(const char *fname, SELA *sela) { FILE *fp; PROCNAME("selaWrite"); if (!fname) return ERROR_INT("fname not defined", procName, 1); if (!sela) return ERROR_INT("sela not defined", procName, 1); if ((fp = fopenWriteStream(fname, "wb")) == NULL) return ERROR_INT("stream not opened", procName, 1); selaWriteStream(fp, sela); fclose(fp); return 0; } /*! * \brief selaWriteStream() * * \param[in] fp file stream * \param[in] sela * \return 0 if OK, 1 on error */ l_int32 selaWriteStream(FILE *fp, SELA *sela) { l_int32 i, n; SEL *sel; PROCNAME("selaWriteStream"); if (!fp) return ERROR_INT("stream not defined", procName, 1); if (!sela) return ERROR_INT("sela not defined", procName, 1); n = selaGetCount(sela); fprintf(fp, "\nSela Version %d\n", SEL_VERSION_NUMBER); fprintf(fp, "Number of Sels = %d\n\n", n); for (i = 0; i < n; i++) { if ((sel = selaGetSel(sela, i)) == NULL) continue; selWriteStream(fp, sel); } return 0; } /*! * \brief selWrite() * * \param[in] fname filename * \param[in] sel * \return 0 if OK, 1 on error */ l_int32 selWrite(const char *fname, SEL *sel) { FILE *fp; PROCNAME("selWrite"); if (!fname) return ERROR_INT("fname not defined", procName, 1); if (!sel) return ERROR_INT("sel not defined", procName, 1); if ((fp = fopenWriteStream(fname, "wb")) == NULL) return ERROR_INT("stream not opened", procName, 1); selWriteStream(fp, sel); fclose(fp); return 0; } /*! * \brief selWriteStream() * * \param[in] fp file stream * \param[in] sel * \return 0 if OK, 1 on error */ l_int32 selWriteStream(FILE *fp, SEL *sel) { l_int32 sx, sy, cx, cy, i, j; PROCNAME("selWriteStream"); if (!fp) return ERROR_INT("stream not defined", procName, 1); if (!sel) return ERROR_INT("sel not defined", procName, 1); selGetParameters(sel, &sy, &sx, &cy, &cx); fprintf(fp, " Sel Version %d\n", SEL_VERSION_NUMBER); fprintf(fp, " ------ %s ------\n", selGetName(sel)); fprintf(fp, " sy = %d, sx = %d, cy = %d, cx = %d\n", sy, sx, cy, cx); for (i = 0; i < sy; i++) { fprintf(fp, " "); for (j = 0; j < sx; j++) fprintf(fp, "%d", sel->data[i][j]); fprintf(fp, "\n"); } fprintf(fp, "\n"); return 0; } /*----------------------------------------------------------------------* * Building custom hit-miss sels from compiled strings * *----------------------------------------------------------------------*/ /*! * \brief selCreateFromString() * * \param[in] text * \param[in] h, w height, width * \param[in] name [optional] sel name; can be null * \return sel of the given size, or NULL on error * * <pre> * Notes: * (1) The text is an array of chars (in row-major order) where * each char can be one of the following: * 'x': hit * 'o': miss * ' ': don't-care * (2) When the origin falls on a hit or miss, use an upper case * char (e.g., 'X' or 'O') to indicate it. When the origin * falls on a don't-care, indicate this with a 'C'. * The string must have exactly one origin specified. * (3) The advantage of this method is that the text can be input * in a format that shows the 2D layout of the Sel; e.g., * \code * static const char *seltext = "x " * "x Oo " * "x " * "xxxxx"; * \endcode * </pre> */ SEL * selCreateFromString(const char *text, l_int32 h, l_int32 w, const char *name) { SEL *sel; l_int32 y, x, norig; char ch; PROCNAME("selCreateFromString"); if (h < 1) return (SEL *)ERROR_PTR("height must be > 0", procName, NULL); if (w < 1) return (SEL *)ERROR_PTR("width must be > 0", procName, NULL); sel = selCreate(h, w, name); norig = 0; for (y = 0; y < h; ++y) { for (x = 0; x < w; ++x) { ch = *(text++); switch (ch) { case 'X': norig++; selSetOrigin(sel, y, x); case 'x': selSetElement(sel, y, x, SEL_HIT); break; case 'O': norig++; selSetOrigin(sel, y, x); case 'o': selSetElement(sel, y, x, SEL_MISS); break; case 'C': norig++; selSetOrigin(sel, y, x); case ' ': selSetElement(sel, y, x, SEL_DONT_CARE); break; case '\n': /* ignored */ continue; default: selDestroy(&sel); return (SEL *)ERROR_PTR("unknown char", procName, NULL); } } } if (norig != 1) { L_ERROR("Exactly one origin must be specified; this string has %d\n", procName, norig); selDestroy(&sel); } return sel; } /*! * \brief selPrintToString() * * \param[in] sel * \return str string; caller must free * * <pre> * Notes: * (1) This is an inverse function of selCreateFromString. * It prints a textual representation of the SEL to a malloc'd * string. The format is the same as selCreateFromString * except that newlines are inserted into the output * between rows. * (2) This is useful for debugging. However, if you want to * save some Sels in a file, put them in a Sela and write * them out with selaWrite(). They can then be read in * with selaRead(). * </pre> */ char * selPrintToString(SEL *sel) { char is_center; char *str, *strptr; l_int32 type; l_int32 sx, sy, cx, cy, x, y; PROCNAME("selPrintToString"); if (!sel) return (char *)ERROR_PTR("sel not defined", procName, NULL); selGetParameters(sel, &sy, &sx, &cy, &cx); if ((str = (char *)LEPT_CALLOC(1, sy * (sx + 1) + 1)) == NULL) return (char *)ERROR_PTR("calloc fail for str", procName, NULL); strptr = str; for (y = 0; y < sy; ++y) { for (x = 0; x < sx; ++x) { selGetElement(sel, y, x, &type); is_center = (x == cx && y == cy); switch (type) { case SEL_HIT: *(strptr++) = is_center ? 'X' : 'x'; break; case SEL_MISS: *(strptr++) = is_center ? 'O' : 'o'; break; case SEL_DONT_CARE: *(strptr++) = is_center ? 'C' : ' '; break; } } *(strptr++) = '\n'; } return str; } /*----------------------------------------------------------------------* * Building custom hit-miss sels from a simple file format * *----------------------------------------------------------------------*/ /*! * \brief selaCreateFromFile() * * \param[in] filename * \return sela, or NULL on error * * <pre> * Notes: * (1) The file contains a sequence of Sel descriptions. * (2) Each Sel is formatted as follows: * ~ Any number of comment lines starting with '#' are ignored * ~ The next line contains the selname * ~ The next lines contain the Sel data. They must be * formatted similarly to the string format in * selCreateFromString(), with each line beginning and * ending with a double-quote, and showing the 2D layout. * ~ Each Sel ends when a blank line, a comment line, or * the end of file is reached. * (3) See selCreateFromString() for a description of the string * format for the Sel data. As an example, here are the lines * of is a valid file for a single Sel. In the file, all lines * are left-justified: * # diagonal sel * sel_5diag * "x " * " x " * " X " * " x " * " x" * </pre> */ SELA * selaCreateFromFile(const char *filename) { char *filestr, *line; l_int32 i, n, first, last, nsel, insel; size_t nbytes; NUMA *nafirst, *nalast; SARRAY *sa; SEL *sel; SELA *sela; PROCNAME("selaCreateFromFile"); if (!filename) return (SELA *)ERROR_PTR("filename not defined", procName, NULL); filestr = (char *)l_binaryRead(filename, &nbytes); sa = sarrayCreateLinesFromString(filestr, 1); LEPT_FREE(filestr); n = sarrayGetCount(sa); sela = selaCreate(0); /* Find the start and end lines for each Sel. * We allow the "blank" lines to be null strings or * to have standard whitespace (' ','\t',\'n') or be '#'. */ nafirst = numaCreate(0); nalast = numaCreate(0); insel = FALSE; for (i = 0; i < n; i++) { line = sarrayGetString(sa, i, L_NOCOPY); if (!insel && (line[0] != '\0' && line[0] != ' ' && line[0] != '\t' && line[0] != '\n' && line[0] != '#')) { numaAddNumber(nafirst, i); insel = TRUE; continue; } if (insel && (line[0] == '\0' || line[0] == ' ' || line[0] == '\t' || line[0] == '\n' || line[0] == '#')) { numaAddNumber(nalast, i - 1); insel = FALSE; continue; } } if (insel) /* fell off the end of the file */ numaAddNumber(nalast, n - 1); /* Extract sels */ nsel = numaGetCount(nafirst); for (i = 0; i < nsel; i++) { numaGetIValue(nafirst, i, &first); numaGetIValue(nalast, i, &last); if ((sel = selCreateFromSArray(sa, first, last)) == NULL) { fprintf(stderr, "Error reading sel from %d to %d\n", first, last); selaDestroy(&sela); sarrayDestroy(&sa); numaDestroy(&nafirst); numaDestroy(&nalast); return (SELA *)ERROR_PTR("bad sela file", procName, NULL); } selaAddSel(sela, sel, NULL, 0); } numaDestroy(&nafirst); numaDestroy(&nalast); sarrayDestroy(&sa); return sela; } /*! * \brief selCreateFromSArray() * * \param[in] sa * \param[in] first line of sarray where Sel begins * \param[in] last line of sarray where Sel ends * \return sela, or NULL on error * * <pre> * Notes: * (1) The Sel contains the following lines: * ~ The first line is the selname * ~ The remaining lines contain the Sel data. They must * be formatted similarly to the string format in * selCreateFromString(), with each line beginning and * ending with a double-quote, and showing the 2D layout. * ~ 'last' gives the last line in the Sel data. * (2) See selCreateFromString() for a description of the string * format for the Sel data. As an example, here are the lines * of is a valid file for a single Sel. In the file, all lines * are left-justified: * # diagonal sel * sel_5diag * "x " * " x " * " X " * " x " * " x" * </pre> */ static SEL * selCreateFromSArray(SARRAY *sa, l_int32 first, l_int32 last) { char ch; char *name, *line; l_int32 n, len, i, w, h, y, x; SEL *sel; PROCNAME("selCreateFromSArray"); if (!sa) return (SEL *)ERROR_PTR("sa not defined", procName, NULL); n = sarrayGetCount(sa); if (first < 0 || first >= n || last <= first || last >= n) return (SEL *)ERROR_PTR("invalid range", procName, NULL); name = sarrayGetString(sa, first, L_NOCOPY); h = last - first; line = sarrayGetString(sa, first + 1, L_NOCOPY); len = strlen(line); if (line[0] != '"' || line[len - 1] != '"') return (SEL *)ERROR_PTR("invalid format", procName, NULL); w = len - 2; if ((sel = selCreate(h, w, name)) == NULL) return (SEL *)ERROR_PTR("sel not made", procName, NULL); for (i = first + 1; i <= last; i++) { line = sarrayGetString(sa, i, L_NOCOPY); y = i - first - 1; for (x = 0; x < w; ++x) { ch = line[x + 1]; /* skip the leading double-quote */ switch (ch) { case 'X': selSetOrigin(sel, y, x); /* set origin and hit */ case 'x': selSetElement(sel, y, x, SEL_HIT); break; case 'O': selSetOrigin(sel, y, x); /* set origin and miss */ case 'o': selSetElement(sel, y, x, SEL_MISS); break; case 'C': selSetOrigin(sel, y, x); /* set origin and don't-care */ case ' ': selSetElement(sel, y, x, SEL_DONT_CARE); break; default: selDestroy(&sel); return (SEL *)ERROR_PTR("unknown char", procName, NULL); } } } return sel; } /*----------------------------------------------------------------------* * Making hit-only SELs from Pta and Pix * *----------------------------------------------------------------------*/ /*! * \brief selCreateFromPta() * * \param[in] pta * \param[in] cy, cx origin of sel * \param[in] name [optional] sel name; can be null * \return sel of minimum required size, or NULL on error * * <pre> * Notes: * (1) The origin and all points in the pta must be positive. * </pre> */ SEL * selCreateFromPta(PTA *pta, l_int32 cy, l_int32 cx, const char *name) { l_int32 i, n, x, y, w, h; BOX *box; SEL *sel; PROCNAME("selCreateFromPta"); if (!pta) return (SEL *)ERROR_PTR("pta not defined", procName, NULL); if (cy < 0 || cx < 0) return (SEL *)ERROR_PTR("(cy, cx) not both >= 0", procName, NULL); n = ptaGetCount(pta); if (n == 0) return (SEL *)ERROR_PTR("no pts in pta", procName, NULL); box = ptaGetBoundingRegion(pta); boxGetGeometry(box, &x, &y, &w, &h); boxDestroy(&box); if (x < 0 || y < 0) return (SEL *)ERROR_PTR("not all x and y >= 0", procName, NULL); sel = selCreate(y + h, x + w, name); selSetOrigin(sel, cy, cx); for (i = 0; i < n; i++) { ptaGetIPt(pta, i, &x, &y); selSetElement(sel, y, x, SEL_HIT); } return sel; } /*! * \brief selCreateFromPix() * * \param[in] pix * \param[in] cy, cx origin of sel * \param[in] name [optional] sel name; can be null * \return sel, or NULL on error * * <pre> * Notes: * (1) The origin must be positive. * </pre> */ SEL * selCreateFromPix(PIX *pix, l_int32 cy, l_int32 cx, const char *name) { SEL *sel; l_int32 i, j, w, h, d; l_uint32 val; PROCNAME("selCreateFromPix"); if (!pix) return (SEL *)ERROR_PTR("pix not defined", procName, NULL); if (cy < 0 || cx < 0) return (SEL *)ERROR_PTR("(cy, cx) not both >= 0", procName, NULL); pixGetDimensions(pix, &w, &h, &d); if (d != 1) return (SEL *)ERROR_PTR("pix not 1 bpp", procName, NULL); sel = selCreate(h, w, name); selSetOrigin(sel, cy, cx); for (i = 0; i < h; i++) { for (j = 0; j < w; j++) { pixGetPixel(pix, j, i, &val); if (val) selSetElement(sel, i, j, SEL_HIT); } } return sel; } /*----------------------------------------------------------------------* * Making hit-miss sels from color Pix and image files * *----------------------------------------------------------------------*/ /*! * * selReadFromColorImage() * * \param[in] pathname * \return sel if OK; NULL on error * * <pre> * Notes: * (1) Loads an image from a file and creates a (hit-miss) sel. * (2) The sel name is taken from the pathname without the directory * and extension. * </pre> */ SEL * selReadFromColorImage(const char *pathname) { PIX *pix; SEL *sel; char *basename, *selname; PROCNAME("selReadFromColorImage"); splitPathAtExtension (pathname, &basename, NULL); splitPathAtDirectory (basename, NULL, &selname); LEPT_FREE(basename); if ((pix = pixRead(pathname)) == NULL) { LEPT_FREE(selname); return (SEL *)ERROR_PTR("pix not returned", procName, NULL); } if ((sel = selCreateFromColorPix(pix, selname)) == NULL) L_ERROR("sel not made\n", procName); LEPT_FREE(selname); pixDestroy(&pix); return sel; } /*! * * selCreateFromColorPix() * * \param[in] pixs cmapped or rgb * \param[in] selname [optional] sel name; can be null * \return sel if OK, NULL on error * * <pre> * Notes: * (1) The sel size is given by the size of pixs. * (2) In pixs, hits are represented by green pixels, misses by red * pixels, and don't-cares by white pixels. * (3) In pixs, there may be no misses, but there must be at least 1 hit. * (4) At most there can be only one origin pixel, which is optionally * specified by using a lower-intensity pixel: * if a hit: dark green * if a miss: dark red * if a don't care: gray * If there is no such pixel, the origin defaults to the approximate * center of the sel. * </pre> */ SEL * selCreateFromColorPix(PIX *pixs, char *selname) { PIXCMAP *cmap; SEL *sel; l_int32 hascolor, hasorigin, nohits; l_int32 w, h, d, i, j, red, green, blue; l_uint32 pixval; PROCNAME("selCreateFromColorPix"); if (!pixs) return (SEL *)ERROR_PTR("pixs not defined", procName, NULL); hascolor = FALSE; cmap = pixGetColormap(pixs); if (cmap) pixcmapHasColor(cmap, &hascolor); pixGetDimensions(pixs, &w, &h, &d); if (hascolor == FALSE && d != 32) return (SEL *)ERROR_PTR("pixs has no color", procName, NULL); if ((sel = selCreate (h, w, NULL)) == NULL) return (SEL *)ERROR_PTR ("sel not made", procName, NULL); selSetOrigin (sel, h / 2, w / 2); selSetName(sel, selname); hasorigin = FALSE; nohits = TRUE; for (i = 0; i < h; i++) { for (j = 0; j < w; j++) { pixGetPixel (pixs, j, i, &pixval); if (cmap) { pixcmapGetColor (cmap, pixval, &red, &green, &blue); } else { red = GET_DATA_BYTE (&pixval, COLOR_RED); green = GET_DATA_BYTE (&pixval, COLOR_GREEN); blue = GET_DATA_BYTE (&pixval, COLOR_BLUE); } if (red < 255 && green < 255 && blue < 255) { if (hasorigin) L_WARNING("multiple origins in sel image\n", procName); selSetOrigin (sel, i, j); hasorigin = TRUE; } if (!red && green && !blue) { nohits = FALSE; selSetElement (sel, i, j, SEL_HIT); } else if (red && !green && !blue) { selSetElement (sel, i, j, SEL_MISS); } else if (red && green && blue) { selSetElement (sel, i, j, SEL_DONT_CARE); } else { selDestroy(&sel); return (SEL *)ERROR_PTR("invalid color", procName, NULL); } } } if (nohits) { selDestroy(&sel); return (SEL *)ERROR_PTR("no hits in sel", procName, NULL); } return sel; } /*----------------------------------------------------------------------* * Printable display of sel * *----------------------------------------------------------------------*/ /*! * \brief selDisplayInPix() * * \param[in] sel * \param[in] size of grid interiors; odd; minimum size of 13 is enforced * \param[in] gthick grid thickness; minimum size of 2 is enforced * \return pix display of sel, or NULL on error * * <pre> * Notes: * (1) This gives a visual representation of a general (hit-miss) sel. * (2) The empty sel is represented by a grid of intersecting lines. * (3) Three different patterns are generated for the sel elements: * ~ hit (solid black circle) * ~ miss (black ring; inner radius is radius2) * ~ origin (cross, XORed with whatever is there) * </pre> */ PIX * selDisplayInPix(SEL *sel, l_int32 size, l_int32 gthick) { l_int32 i, j, w, h, sx, sy, cx, cy, type, width; l_int32 radius1, radius2, shift1, shift2, x0, y0; PIX *pixd, *pix2, *pixh, *pixm, *pixorig; PTA *pta1, *pta2, *pta1t, *pta2t; PROCNAME("selDisplayInPix"); if (!sel) return (PIX *)ERROR_PTR("sel not defined", procName, NULL); if (size < 13) { L_WARNING("size < 13; setting to 13\n", procName); size = 13; } if (size % 2 == 0) size++; if (gthick < 2) { L_WARNING("grid thickness < 2; setting to 2\n", procName); gthick = 2; } selGetParameters(sel, &sy, &sx, &cy, &cx); w = size * sx + gthick * (sx + 1); h = size * sy + gthick * (sy + 1); pixd = pixCreate(w, h, 1); /* Generate grid lines */ for (i = 0; i <= sy; i++) pixRenderLine(pixd, 0, gthick / 2 + i * (size + gthick), w - 1, gthick / 2 + i * (size + gthick), gthick, L_SET_PIXELS); for (j = 0; j <= sx; j++) pixRenderLine(pixd, gthick / 2 + j * (size + gthick), 0, gthick / 2 + j * (size + gthick), h - 1, gthick, L_SET_PIXELS); /* Generate hit and miss patterns */ radius1 = (l_int32)(0.85 * ((size - 1) / 2.0) + 0.5); /* of hit */ radius2 = (l_int32)(0.65 * ((size - 1) / 2.0) + 0.5); /* of inner miss */ pta1 = generatePtaFilledCircle(radius1); pta2 = generatePtaFilledCircle(radius2); shift1 = (size - 1) / 2 - radius1; /* center circle in square */ shift2 = (size - 1) / 2 - radius2; pta1t = ptaTransform(pta1, shift1, shift1, 1.0, 1.0); pta2t = ptaTransform(pta2, shift2, shift2, 1.0, 1.0); pixh = pixGenerateFromPta(pta1t, size, size); /* hits */ pix2 = pixGenerateFromPta(pta2t, size, size); pixm = pixSubtract(NULL, pixh, pix2); /* Generate crossed lines for origin pattern */ pixorig = pixCreate(size, size, 1); width = size / 8; pixRenderLine(pixorig, size / 2, (l_int32)(0.12 * size), size / 2, (l_int32)(0.88 * size), width, L_SET_PIXELS); pixRenderLine(pixorig, (l_int32)(0.15 * size), size / 2, (l_int32)(0.85 * size), size / 2, width, L_FLIP_PIXELS); pixRasterop(pixorig, size / 2 - width, size / 2 - width, 2 * width, 2 * width, PIX_NOT(PIX_DST), NULL, 0, 0); /* Specialize origin pattern for this sel */ selGetTypeAtOrigin(sel, &type); if (type == SEL_HIT) pixXor(pixorig, pixorig, pixh); else if (type == SEL_MISS) pixXor(pixorig, pixorig, pixm); /* Paste the patterns in */ y0 = gthick; for (i = 0; i < sy; i++) { x0 = gthick; for (j = 0; j < sx; j++) { selGetElement(sel, i, j, &type); if (i == cy && j == cx) /* origin */ pixRasterop(pixd, x0, y0, size, size, PIX_SRC, pixorig, 0, 0); else if (type == SEL_HIT) pixRasterop(pixd, x0, y0, size, size, PIX_SRC, pixh, 0, 0); else if (type == SEL_MISS) pixRasterop(pixd, x0, y0, size, size, PIX_SRC, pixm, 0, 0); x0 += size + gthick; } y0 += size + gthick; } pixDestroy(&pix2); pixDestroy(&pixh); pixDestroy(&pixm); pixDestroy(&pixorig); ptaDestroy(&pta1); ptaDestroy(&pta1t); ptaDestroy(&pta2); ptaDestroy(&pta2t); return pixd; } /*! * \brief selaDisplayInPix() * * \param[in] sela * \param[in] size of grid interiors; odd; minimum size of 13 is enforced * \param[in] gthick grid thickness; minimum size of 2 is enforced * \param[in] spacing between sels, both horizontally and vertically * \param[in] ncols number of sels per "line" * \return pix display of all sels in sela, or NULL on error * * <pre> * Notes: * (1) This gives a visual representation of all the sels in a sela. * (2) See notes in selDisplayInPix() for display params of each sel. * (3) This gives the nicest results when all sels in the sela * are the same size. * </pre> */ PIX * selaDisplayInPix(SELA *sela, l_int32 size, l_int32 gthick, l_int32 spacing, l_int32 ncols) { l_int32 nsels, i, w, width; PIX *pixt, *pixd; PIXA *pixa; SEL *sel; PROCNAME("selaDisplayInPix"); if (!sela) return (PIX *)ERROR_PTR("sela not defined", procName, NULL); if (size < 13) { L_WARNING("size < 13; setting to 13\n", procName); size = 13; } if (size % 2 == 0) size++; if (gthick < 2) { L_WARNING("grid thickness < 2; setting to 2\n", procName); gthick = 2; } if (spacing < 5) { L_WARNING("spacing < 5; setting to 5\n", procName); spacing = 5; } /* Accumulate the pix of each sel */ nsels = selaGetCount(sela); pixa = pixaCreate(nsels); for (i = 0; i < nsels; i++) { sel = selaGetSel(sela, i); pixt = selDisplayInPix(sel, size, gthick); pixaAddPix(pixa, pixt, L_INSERT); } /* Find the tiled output width, using just the first * ncols pix in the pixa. If all pix have the same width, * they will align properly in columns. */ width = 0; ncols = L_MIN(nsels, ncols); for (i = 0; i < ncols; i++) { pixt = pixaGetPix(pixa, i, L_CLONE); pixGetDimensions(pixt, &w, NULL, NULL); width += w; pixDestroy(&pixt); } width += (ncols + 1) * spacing; /* add spacing all around as well */ pixd = pixaDisplayTiledInRows(pixa, 1, width, 1.0, 0, spacing, 0); pixaDestroy(&pixa); return pixd; }
./CrossVul/dataset_final_sorted/CWE-119/c/good_622_4
crossvul-cpp_data_good_3418_1
/* * WebP (.webp) image decoder * Copyright (c) 2013 Aneesh Dogra <aneesh@sugarlabs.org> * Copyright (c) 2013 Justin Ruggles <justin.ruggles@gmail.com> * * 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 * WebP image decoder * * @author Aneesh Dogra <aneesh@sugarlabs.org> * Container and Lossy decoding * * @author Justin Ruggles <justin.ruggles@gmail.com> * Lossless decoder * Compressed alpha for lossy * * @author James Almer <jamrial@gmail.com> * Exif metadata * * Unimplemented: * - Animation * - ICC profile * - XMP metadata */ #include "libavutil/imgutils.h" #define BITSTREAM_READER_LE #include "avcodec.h" #include "bytestream.h" #include "exif.h" #include "get_bits.h" #include "internal.h" #include "thread.h" #include "vp8.h" #define VP8X_FLAG_ANIMATION 0x02 #define VP8X_FLAG_XMP_METADATA 0x04 #define VP8X_FLAG_EXIF_METADATA 0x08 #define VP8X_FLAG_ALPHA 0x10 #define VP8X_FLAG_ICC 0x20 #define MAX_PALETTE_SIZE 256 #define MAX_CACHE_BITS 11 #define NUM_CODE_LENGTH_CODES 19 #define HUFFMAN_CODES_PER_META_CODE 5 #define NUM_LITERAL_CODES 256 #define NUM_LENGTH_CODES 24 #define NUM_DISTANCE_CODES 40 #define NUM_SHORT_DISTANCES 120 #define MAX_HUFFMAN_CODE_LENGTH 15 static const uint16_t alphabet_sizes[HUFFMAN_CODES_PER_META_CODE] = { NUM_LITERAL_CODES + NUM_LENGTH_CODES, NUM_LITERAL_CODES, NUM_LITERAL_CODES, NUM_LITERAL_CODES, NUM_DISTANCE_CODES }; static const uint8_t code_length_code_order[NUM_CODE_LENGTH_CODES] = { 17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; static const int8_t lz77_distance_offsets[NUM_SHORT_DISTANCES][2] = { { 0, 1 }, { 1, 0 }, { 1, 1 }, { -1, 1 }, { 0, 2 }, { 2, 0 }, { 1, 2 }, { -1, 2 }, { 2, 1 }, { -2, 1 }, { 2, 2 }, { -2, 2 }, { 0, 3 }, { 3, 0 }, { 1, 3 }, { -1, 3 }, { 3, 1 }, { -3, 1 }, { 2, 3 }, { -2, 3 }, { 3, 2 }, { -3, 2 }, { 0, 4 }, { 4, 0 }, { 1, 4 }, { -1, 4 }, { 4, 1 }, { -4, 1 }, { 3, 3 }, { -3, 3 }, { 2, 4 }, { -2, 4 }, { 4, 2 }, { -4, 2 }, { 0, 5 }, { 3, 4 }, { -3, 4 }, { 4, 3 }, { -4, 3 }, { 5, 0 }, { 1, 5 }, { -1, 5 }, { 5, 1 }, { -5, 1 }, { 2, 5 }, { -2, 5 }, { 5, 2 }, { -5, 2 }, { 4, 4 }, { -4, 4 }, { 3, 5 }, { -3, 5 }, { 5, 3 }, { -5, 3 }, { 0, 6 }, { 6, 0 }, { 1, 6 }, { -1, 6 }, { 6, 1 }, { -6, 1 }, { 2, 6 }, { -2, 6 }, { 6, 2 }, { -6, 2 }, { 4, 5 }, { -4, 5 }, { 5, 4 }, { -5, 4 }, { 3, 6 }, { -3, 6 }, { 6, 3 }, { -6, 3 }, { 0, 7 }, { 7, 0 }, { 1, 7 }, { -1, 7 }, { 5, 5 }, { -5, 5 }, { 7, 1 }, { -7, 1 }, { 4, 6 }, { -4, 6 }, { 6, 4 }, { -6, 4 }, { 2, 7 }, { -2, 7 }, { 7, 2 }, { -7, 2 }, { 3, 7 }, { -3, 7 }, { 7, 3 }, { -7, 3 }, { 5, 6 }, { -5, 6 }, { 6, 5 }, { -6, 5 }, { 8, 0 }, { 4, 7 }, { -4, 7 }, { 7, 4 }, { -7, 4 }, { 8, 1 }, { 8, 2 }, { 6, 6 }, { -6, 6 }, { 8, 3 }, { 5, 7 }, { -5, 7 }, { 7, 5 }, { -7, 5 }, { 8, 4 }, { 6, 7 }, { -6, 7 }, { 7, 6 }, { -7, 6 }, { 8, 5 }, { 7, 7 }, { -7, 7 }, { 8, 6 }, { 8, 7 } }; enum AlphaCompression { ALPHA_COMPRESSION_NONE, ALPHA_COMPRESSION_VP8L, }; enum AlphaFilter { ALPHA_FILTER_NONE, ALPHA_FILTER_HORIZONTAL, ALPHA_FILTER_VERTICAL, ALPHA_FILTER_GRADIENT, }; enum TransformType { PREDICTOR_TRANSFORM = 0, COLOR_TRANSFORM = 1, SUBTRACT_GREEN = 2, COLOR_INDEXING_TRANSFORM = 3, }; enum PredictionMode { PRED_MODE_BLACK, PRED_MODE_L, PRED_MODE_T, PRED_MODE_TR, PRED_MODE_TL, PRED_MODE_AVG_T_AVG_L_TR, PRED_MODE_AVG_L_TL, PRED_MODE_AVG_L_T, PRED_MODE_AVG_TL_T, PRED_MODE_AVG_T_TR, PRED_MODE_AVG_AVG_L_TL_AVG_T_TR, PRED_MODE_SELECT, PRED_MODE_ADD_SUBTRACT_FULL, PRED_MODE_ADD_SUBTRACT_HALF, }; enum HuffmanIndex { HUFF_IDX_GREEN = 0, HUFF_IDX_RED = 1, HUFF_IDX_BLUE = 2, HUFF_IDX_ALPHA = 3, HUFF_IDX_DIST = 4 }; /* The structure of WebP lossless is an optional series of transformation data, * followed by the primary image. The primary image also optionally contains * an entropy group mapping if there are multiple entropy groups. There is a * basic image type called an "entropy coded image" that is used for all of * these. The type of each entropy coded image is referred to by the * specification as its role. */ enum ImageRole { /* Primary Image: Stores the actual pixels of the image. */ IMAGE_ROLE_ARGB, /* Entropy Image: Defines which Huffman group to use for different areas of * the primary image. */ IMAGE_ROLE_ENTROPY, /* Predictors: Defines which predictor type to use for different areas of * the primary image. */ IMAGE_ROLE_PREDICTOR, /* Color Transform Data: Defines the color transformation for different * areas of the primary image. */ IMAGE_ROLE_COLOR_TRANSFORM, /* Color Index: Stored as an image of height == 1. */ IMAGE_ROLE_COLOR_INDEXING, IMAGE_ROLE_NB, }; typedef struct HuffReader { VLC vlc; /* Huffman decoder context */ int simple; /* whether to use simple mode */ int nb_symbols; /* number of coded symbols */ uint16_t simple_symbols[2]; /* symbols for simple mode */ } HuffReader; typedef struct ImageContext { enum ImageRole role; /* role of this image */ AVFrame *frame; /* AVFrame for data */ int color_cache_bits; /* color cache size, log2 */ uint32_t *color_cache; /* color cache data */ int nb_huffman_groups; /* number of huffman groups */ HuffReader *huffman_groups; /* reader for each huffman group */ int size_reduction; /* relative size compared to primary image, log2 */ int is_alpha_primary; } ImageContext; typedef struct WebPContext { VP8Context v; /* VP8 Context used for lossy decoding */ GetBitContext gb; /* bitstream reader for main image chunk */ AVFrame *alpha_frame; /* AVFrame for alpha data decompressed from VP8L */ AVCodecContext *avctx; /* parent AVCodecContext */ int initialized; /* set once the VP8 context is initialized */ int has_alpha; /* has a separate alpha chunk */ enum AlphaCompression alpha_compression; /* compression type for alpha chunk */ enum AlphaFilter alpha_filter; /* filtering method for alpha chunk */ uint8_t *alpha_data; /* alpha chunk data */ int alpha_data_size; /* alpha chunk data size */ int has_exif; /* set after an EXIF chunk has been processed */ int width; /* image width */ int height; /* image height */ int lossless; /* indicates lossless or lossy */ int nb_transforms; /* number of transforms */ enum TransformType transforms[4]; /* transformations used in the image, in order */ int reduced_width; /* reduced width for index image, if applicable */ int nb_huffman_groups; /* number of huffman groups in the primary image */ ImageContext image[IMAGE_ROLE_NB]; /* image context for each role */ } WebPContext; #define GET_PIXEL(frame, x, y) \ ((frame)->data[0] + (y) * frame->linesize[0] + 4 * (x)) #define GET_PIXEL_COMP(frame, x, y, c) \ (*((frame)->data[0] + (y) * frame->linesize[0] + 4 * (x) + c)) static void image_ctx_free(ImageContext *img) { int i, j; av_free(img->color_cache); if (img->role != IMAGE_ROLE_ARGB && !img->is_alpha_primary) av_frame_free(&img->frame); if (img->huffman_groups) { for (i = 0; i < img->nb_huffman_groups; i++) { for (j = 0; j < HUFFMAN_CODES_PER_META_CODE; j++) ff_free_vlc(&img->huffman_groups[i * HUFFMAN_CODES_PER_META_CODE + j].vlc); } av_free(img->huffman_groups); } memset(img, 0, sizeof(*img)); } /* Differs from get_vlc2() in the following ways: * - codes are bit-reversed * - assumes 8-bit table to make reversal simpler * - assumes max depth of 2 since the max code length for WebP is 15 */ static av_always_inline int webp_get_vlc(GetBitContext *gb, VLC_TYPE (*table)[2]) { int n, nb_bits; unsigned int index; int code; OPEN_READER(re, gb); UPDATE_CACHE(re, gb); index = SHOW_UBITS(re, gb, 8); index = ff_reverse[index]; code = table[index][0]; n = table[index][1]; if (n < 0) { LAST_SKIP_BITS(re, gb, 8); UPDATE_CACHE(re, gb); nb_bits = -n; index = SHOW_UBITS(re, gb, nb_bits); index = (ff_reverse[index] >> (8 - nb_bits)) + code; code = table[index][0]; n = table[index][1]; } SKIP_BITS(re, gb, n); CLOSE_READER(re, gb); return code; } static int huff_reader_get_symbol(HuffReader *r, GetBitContext *gb) { if (r->simple) { if (r->nb_symbols == 1) return r->simple_symbols[0]; else return r->simple_symbols[get_bits1(gb)]; } else return webp_get_vlc(gb, r->vlc.table); } static int huff_reader_build_canonical(HuffReader *r, int *code_lengths, int alphabet_size) { int len = 0, sym, code = 0, ret; int max_code_length = 0; uint16_t *codes; /* special-case 1 symbol since the vlc reader cannot handle it */ for (sym = 0; sym < alphabet_size; sym++) { if (code_lengths[sym] > 0) { len++; code = sym; if (len > 1) break; } } if (len == 1) { r->nb_symbols = 1; r->simple_symbols[0] = code; r->simple = 1; return 0; } for (sym = 0; sym < alphabet_size; sym++) max_code_length = FFMAX(max_code_length, code_lengths[sym]); if (max_code_length == 0 || max_code_length > MAX_HUFFMAN_CODE_LENGTH) return AVERROR(EINVAL); codes = av_malloc_array(alphabet_size, sizeof(*codes)); if (!codes) return AVERROR(ENOMEM); code = 0; r->nb_symbols = 0; for (len = 1; len <= max_code_length; len++) { for (sym = 0; sym < alphabet_size; sym++) { if (code_lengths[sym] != len) continue; codes[sym] = code++; r->nb_symbols++; } code <<= 1; } if (!r->nb_symbols) { av_free(codes); return AVERROR_INVALIDDATA; } ret = init_vlc(&r->vlc, 8, alphabet_size, code_lengths, sizeof(*code_lengths), sizeof(*code_lengths), codes, sizeof(*codes), sizeof(*codes), 0); if (ret < 0) { av_free(codes); return ret; } r->simple = 0; av_free(codes); return 0; } static void read_huffman_code_simple(WebPContext *s, HuffReader *hc) { hc->nb_symbols = get_bits1(&s->gb) + 1; if (get_bits1(&s->gb)) hc->simple_symbols[0] = get_bits(&s->gb, 8); else hc->simple_symbols[0] = get_bits1(&s->gb); if (hc->nb_symbols == 2) hc->simple_symbols[1] = get_bits(&s->gb, 8); hc->simple = 1; } static int read_huffman_code_normal(WebPContext *s, HuffReader *hc, int alphabet_size) { HuffReader code_len_hc = { { 0 }, 0, 0, { 0 } }; int *code_lengths = NULL; int code_length_code_lengths[NUM_CODE_LENGTH_CODES] = { 0 }; int i, symbol, max_symbol, prev_code_len, ret; int num_codes = 4 + get_bits(&s->gb, 4); if (num_codes > NUM_CODE_LENGTH_CODES) return AVERROR_INVALIDDATA; for (i = 0; i < num_codes; i++) code_length_code_lengths[code_length_code_order[i]] = get_bits(&s->gb, 3); ret = huff_reader_build_canonical(&code_len_hc, code_length_code_lengths, NUM_CODE_LENGTH_CODES); if (ret < 0) goto finish; code_lengths = av_mallocz_array(alphabet_size, sizeof(*code_lengths)); if (!code_lengths) { ret = AVERROR(ENOMEM); goto finish; } if (get_bits1(&s->gb)) { int bits = 2 + 2 * get_bits(&s->gb, 3); max_symbol = 2 + get_bits(&s->gb, bits); if (max_symbol > alphabet_size) { av_log(s->avctx, AV_LOG_ERROR, "max symbol %d > alphabet size %d\n", max_symbol, alphabet_size); ret = AVERROR_INVALIDDATA; goto finish; } } else { max_symbol = alphabet_size; } prev_code_len = 8; symbol = 0; while (symbol < alphabet_size) { int code_len; if (!max_symbol--) break; code_len = huff_reader_get_symbol(&code_len_hc, &s->gb); if (code_len < 16) { /* Code length code [0..15] indicates literal code lengths. */ code_lengths[symbol++] = code_len; if (code_len) prev_code_len = code_len; } else { int repeat = 0, length = 0; switch (code_len) { case 16: /* Code 16 repeats the previous non-zero value [3..6] times, * i.e., 3 + ReadBits(2) times. If code 16 is used before a * non-zero value has been emitted, a value of 8 is repeated. */ repeat = 3 + get_bits(&s->gb, 2); length = prev_code_len; break; case 17: /* Code 17 emits a streak of zeros [3..10], i.e., * 3 + ReadBits(3) times. */ repeat = 3 + get_bits(&s->gb, 3); break; case 18: /* Code 18 emits a streak of zeros of length [11..138], i.e., * 11 + ReadBits(7) times. */ repeat = 11 + get_bits(&s->gb, 7); break; } if (symbol + repeat > alphabet_size) { av_log(s->avctx, AV_LOG_ERROR, "invalid symbol %d + repeat %d > alphabet size %d\n", symbol, repeat, alphabet_size); ret = AVERROR_INVALIDDATA; goto finish; } while (repeat-- > 0) code_lengths[symbol++] = length; } } ret = huff_reader_build_canonical(hc, code_lengths, alphabet_size); finish: ff_free_vlc(&code_len_hc.vlc); av_free(code_lengths); return ret; } static int decode_entropy_coded_image(WebPContext *s, enum ImageRole role, int w, int h); #define PARSE_BLOCK_SIZE(w, h) do { \ block_bits = get_bits(&s->gb, 3) + 2; \ blocks_w = FFALIGN((w), 1 << block_bits) >> block_bits; \ blocks_h = FFALIGN((h), 1 << block_bits) >> block_bits; \ } while (0) static int decode_entropy_image(WebPContext *s) { ImageContext *img; int ret, block_bits, width, blocks_w, blocks_h, x, y, max; width = s->width; if (s->reduced_width > 0) width = s->reduced_width; PARSE_BLOCK_SIZE(width, s->height); ret = decode_entropy_coded_image(s, IMAGE_ROLE_ENTROPY, blocks_w, blocks_h); if (ret < 0) return ret; img = &s->image[IMAGE_ROLE_ENTROPY]; img->size_reduction = block_bits; /* the number of huffman groups is determined by the maximum group number * coded in the entropy image */ max = 0; for (y = 0; y < img->frame->height; y++) { for (x = 0; x < img->frame->width; x++) { int p0 = GET_PIXEL_COMP(img->frame, x, y, 1); int p1 = GET_PIXEL_COMP(img->frame, x, y, 2); int p = p0 << 8 | p1; max = FFMAX(max, p); } } s->nb_huffman_groups = max + 1; return 0; } static int parse_transform_predictor(WebPContext *s) { int block_bits, blocks_w, blocks_h, ret; PARSE_BLOCK_SIZE(s->width, s->height); ret = decode_entropy_coded_image(s, IMAGE_ROLE_PREDICTOR, blocks_w, blocks_h); if (ret < 0) return ret; s->image[IMAGE_ROLE_PREDICTOR].size_reduction = block_bits; return 0; } static int parse_transform_color(WebPContext *s) { int block_bits, blocks_w, blocks_h, ret; PARSE_BLOCK_SIZE(s->width, s->height); ret = decode_entropy_coded_image(s, IMAGE_ROLE_COLOR_TRANSFORM, blocks_w, blocks_h); if (ret < 0) return ret; s->image[IMAGE_ROLE_COLOR_TRANSFORM].size_reduction = block_bits; return 0; } static int parse_transform_color_indexing(WebPContext *s) { ImageContext *img; int width_bits, index_size, ret, x; uint8_t *ct; index_size = get_bits(&s->gb, 8) + 1; if (index_size <= 2) width_bits = 3; else if (index_size <= 4) width_bits = 2; else if (index_size <= 16) width_bits = 1; else width_bits = 0; ret = decode_entropy_coded_image(s, IMAGE_ROLE_COLOR_INDEXING, index_size, 1); if (ret < 0) return ret; img = &s->image[IMAGE_ROLE_COLOR_INDEXING]; img->size_reduction = width_bits; if (width_bits > 0) s->reduced_width = (s->width + ((1 << width_bits) - 1)) >> width_bits; /* color index values are delta-coded */ ct = img->frame->data[0] + 4; for (x = 4; x < img->frame->width * 4; x++, ct++) ct[0] += ct[-4]; return 0; } static HuffReader *get_huffman_group(WebPContext *s, ImageContext *img, int x, int y) { ImageContext *gimg = &s->image[IMAGE_ROLE_ENTROPY]; int group = 0; if (gimg->size_reduction > 0) { int group_x = x >> gimg->size_reduction; int group_y = y >> gimg->size_reduction; int g0 = GET_PIXEL_COMP(gimg->frame, group_x, group_y, 1); int g1 = GET_PIXEL_COMP(gimg->frame, group_x, group_y, 2); group = g0 << 8 | g1; } return &img->huffman_groups[group * HUFFMAN_CODES_PER_META_CODE]; } static av_always_inline void color_cache_put(ImageContext *img, uint32_t c) { uint32_t cache_idx = (0x1E35A7BD * c) >> (32 - img->color_cache_bits); img->color_cache[cache_idx] = c; } static int decode_entropy_coded_image(WebPContext *s, enum ImageRole role, int w, int h) { ImageContext *img; HuffReader *hg; int i, j, ret, x, y, width; img = &s->image[role]; img->role = role; if (!img->frame) { img->frame = av_frame_alloc(); if (!img->frame) return AVERROR(ENOMEM); } img->frame->format = AV_PIX_FMT_ARGB; img->frame->width = w; img->frame->height = h; if (role == IMAGE_ROLE_ARGB && !img->is_alpha_primary) { ThreadFrame pt = { .f = img->frame }; ret = ff_thread_get_buffer(s->avctx, &pt, 0); } else ret = av_frame_get_buffer(img->frame, 1); if (ret < 0) return ret; if (get_bits1(&s->gb)) { img->color_cache_bits = get_bits(&s->gb, 4); if (img->color_cache_bits < 1 || img->color_cache_bits > 11) { av_log(s->avctx, AV_LOG_ERROR, "invalid color cache bits: %d\n", img->color_cache_bits); return AVERROR_INVALIDDATA; } img->color_cache = av_mallocz_array(1 << img->color_cache_bits, sizeof(*img->color_cache)); if (!img->color_cache) return AVERROR(ENOMEM); } else { img->color_cache_bits = 0; } img->nb_huffman_groups = 1; if (role == IMAGE_ROLE_ARGB && get_bits1(&s->gb)) { ret = decode_entropy_image(s); if (ret < 0) return ret; img->nb_huffman_groups = s->nb_huffman_groups; } img->huffman_groups = av_mallocz_array(img->nb_huffman_groups * HUFFMAN_CODES_PER_META_CODE, sizeof(*img->huffman_groups)); if (!img->huffman_groups) return AVERROR(ENOMEM); for (i = 0; i < img->nb_huffman_groups; i++) { hg = &img->huffman_groups[i * HUFFMAN_CODES_PER_META_CODE]; for (j = 0; j < HUFFMAN_CODES_PER_META_CODE; j++) { int alphabet_size = alphabet_sizes[j]; if (!j && img->color_cache_bits > 0) alphabet_size += 1 << img->color_cache_bits; if (get_bits1(&s->gb)) { read_huffman_code_simple(s, &hg[j]); } else { ret = read_huffman_code_normal(s, &hg[j], alphabet_size); if (ret < 0) return ret; } } } width = img->frame->width; if (role == IMAGE_ROLE_ARGB && s->reduced_width > 0) width = s->reduced_width; x = 0; y = 0; while (y < img->frame->height) { int v; hg = get_huffman_group(s, img, x, y); v = huff_reader_get_symbol(&hg[HUFF_IDX_GREEN], &s->gb); if (v < NUM_LITERAL_CODES) { /* literal pixel values */ uint8_t *p = GET_PIXEL(img->frame, x, y); p[2] = v; p[1] = huff_reader_get_symbol(&hg[HUFF_IDX_RED], &s->gb); p[3] = huff_reader_get_symbol(&hg[HUFF_IDX_BLUE], &s->gb); p[0] = huff_reader_get_symbol(&hg[HUFF_IDX_ALPHA], &s->gb); if (img->color_cache_bits) color_cache_put(img, AV_RB32(p)); x++; if (x == width) { x = 0; y++; } } else if (v < NUM_LITERAL_CODES + NUM_LENGTH_CODES) { /* LZ77 backwards mapping */ int prefix_code, length, distance, ref_x, ref_y; /* parse length and distance */ prefix_code = v - NUM_LITERAL_CODES; if (prefix_code < 4) { length = prefix_code + 1; } else { int extra_bits = (prefix_code - 2) >> 1; int offset = 2 + (prefix_code & 1) << extra_bits; length = offset + get_bits(&s->gb, extra_bits) + 1; } prefix_code = huff_reader_get_symbol(&hg[HUFF_IDX_DIST], &s->gb); if (prefix_code > 39) { av_log(s->avctx, AV_LOG_ERROR, "distance prefix code too large: %d\n", prefix_code); return AVERROR_INVALIDDATA; } if (prefix_code < 4) { distance = prefix_code + 1; } else { int extra_bits = prefix_code - 2 >> 1; int offset = 2 + (prefix_code & 1) << extra_bits; distance = offset + get_bits(&s->gb, extra_bits) + 1; } /* find reference location */ if (distance <= NUM_SHORT_DISTANCES) { int xi = lz77_distance_offsets[distance - 1][0]; int yi = lz77_distance_offsets[distance - 1][1]; distance = FFMAX(1, xi + yi * width); } else { distance -= NUM_SHORT_DISTANCES; } ref_x = x; ref_y = y; if (distance <= x) { ref_x -= distance; distance = 0; } else { ref_x = 0; distance -= x; } while (distance >= width) { ref_y--; distance -= width; } if (distance > 0) { ref_x = width - distance; ref_y--; } ref_x = FFMAX(0, ref_x); ref_y = FFMAX(0, ref_y); /* copy pixels * source and dest regions can overlap and wrap lines, so just * copy per-pixel */ for (i = 0; i < length; i++) { uint8_t *p_ref = GET_PIXEL(img->frame, ref_x, ref_y); uint8_t *p = GET_PIXEL(img->frame, x, y); AV_COPY32(p, p_ref); if (img->color_cache_bits) color_cache_put(img, AV_RB32(p)); x++; ref_x++; if (x == width) { x = 0; y++; } if (ref_x == width) { ref_x = 0; ref_y++; } if (y == img->frame->height || ref_y == img->frame->height) break; } } else { /* read from color cache */ uint8_t *p = GET_PIXEL(img->frame, x, y); int cache_idx = v - (NUM_LITERAL_CODES + NUM_LENGTH_CODES); if (!img->color_cache_bits) { av_log(s->avctx, AV_LOG_ERROR, "color cache not found\n"); return AVERROR_INVALIDDATA; } if (cache_idx >= 1 << img->color_cache_bits) { av_log(s->avctx, AV_LOG_ERROR, "color cache index out-of-bounds\n"); return AVERROR_INVALIDDATA; } AV_WB32(p, img->color_cache[cache_idx]); x++; if (x == width) { x = 0; y++; } } } return 0; } /* PRED_MODE_BLACK */ static void inv_predict_0(uint8_t *p, const uint8_t *p_l, const uint8_t *p_tl, const uint8_t *p_t, const uint8_t *p_tr) { AV_WB32(p, 0xFF000000); } /* PRED_MODE_L */ static void inv_predict_1(uint8_t *p, const uint8_t *p_l, const uint8_t *p_tl, const uint8_t *p_t, const uint8_t *p_tr) { AV_COPY32(p, p_l); } /* PRED_MODE_T */ static void inv_predict_2(uint8_t *p, const uint8_t *p_l, const uint8_t *p_tl, const uint8_t *p_t, const uint8_t *p_tr) { AV_COPY32(p, p_t); } /* PRED_MODE_TR */ static void inv_predict_3(uint8_t *p, const uint8_t *p_l, const uint8_t *p_tl, const uint8_t *p_t, const uint8_t *p_tr) { AV_COPY32(p, p_tr); } /* PRED_MODE_TL */ static void inv_predict_4(uint8_t *p, const uint8_t *p_l, const uint8_t *p_tl, const uint8_t *p_t, const uint8_t *p_tr) { AV_COPY32(p, p_tl); } /* PRED_MODE_AVG_T_AVG_L_TR */ static void inv_predict_5(uint8_t *p, const uint8_t *p_l, const uint8_t *p_tl, const uint8_t *p_t, const uint8_t *p_tr) { p[0] = p_t[0] + (p_l[0] + p_tr[0] >> 1) >> 1; p[1] = p_t[1] + (p_l[1] + p_tr[1] >> 1) >> 1; p[2] = p_t[2] + (p_l[2] + p_tr[2] >> 1) >> 1; p[3] = p_t[3] + (p_l[3] + p_tr[3] >> 1) >> 1; } /* PRED_MODE_AVG_L_TL */ static void inv_predict_6(uint8_t *p, const uint8_t *p_l, const uint8_t *p_tl, const uint8_t *p_t, const uint8_t *p_tr) { p[0] = p_l[0] + p_tl[0] >> 1; p[1] = p_l[1] + p_tl[1] >> 1; p[2] = p_l[2] + p_tl[2] >> 1; p[3] = p_l[3] + p_tl[3] >> 1; } /* PRED_MODE_AVG_L_T */ static void inv_predict_7(uint8_t *p, const uint8_t *p_l, const uint8_t *p_tl, const uint8_t *p_t, const uint8_t *p_tr) { p[0] = p_l[0] + p_t[0] >> 1; p[1] = p_l[1] + p_t[1] >> 1; p[2] = p_l[2] + p_t[2] >> 1; p[3] = p_l[3] + p_t[3] >> 1; } /* PRED_MODE_AVG_TL_T */ static void inv_predict_8(uint8_t *p, const uint8_t *p_l, const uint8_t *p_tl, const uint8_t *p_t, const uint8_t *p_tr) { p[0] = p_tl[0] + p_t[0] >> 1; p[1] = p_tl[1] + p_t[1] >> 1; p[2] = p_tl[2] + p_t[2] >> 1; p[3] = p_tl[3] + p_t[3] >> 1; } /* PRED_MODE_AVG_T_TR */ static void inv_predict_9(uint8_t *p, const uint8_t *p_l, const uint8_t *p_tl, const uint8_t *p_t, const uint8_t *p_tr) { p[0] = p_t[0] + p_tr[0] >> 1; p[1] = p_t[1] + p_tr[1] >> 1; p[2] = p_t[2] + p_tr[2] >> 1; p[3] = p_t[3] + p_tr[3] >> 1; } /* PRED_MODE_AVG_AVG_L_TL_AVG_T_TR */ static void inv_predict_10(uint8_t *p, const uint8_t *p_l, const uint8_t *p_tl, const uint8_t *p_t, const uint8_t *p_tr) { p[0] = (p_l[0] + p_tl[0] >> 1) + (p_t[0] + p_tr[0] >> 1) >> 1; p[1] = (p_l[1] + p_tl[1] >> 1) + (p_t[1] + p_tr[1] >> 1) >> 1; p[2] = (p_l[2] + p_tl[2] >> 1) + (p_t[2] + p_tr[2] >> 1) >> 1; p[3] = (p_l[3] + p_tl[3] >> 1) + (p_t[3] + p_tr[3] >> 1) >> 1; } /* PRED_MODE_SELECT */ static void inv_predict_11(uint8_t *p, const uint8_t *p_l, const uint8_t *p_tl, const uint8_t *p_t, const uint8_t *p_tr) { int diff = (FFABS(p_l[0] - p_tl[0]) - FFABS(p_t[0] - p_tl[0])) + (FFABS(p_l[1] - p_tl[1]) - FFABS(p_t[1] - p_tl[1])) + (FFABS(p_l[2] - p_tl[2]) - FFABS(p_t[2] - p_tl[2])) + (FFABS(p_l[3] - p_tl[3]) - FFABS(p_t[3] - p_tl[3])); if (diff <= 0) AV_COPY32(p, p_t); else AV_COPY32(p, p_l); } /* PRED_MODE_ADD_SUBTRACT_FULL */ static void inv_predict_12(uint8_t *p, const uint8_t *p_l, const uint8_t *p_tl, const uint8_t *p_t, const uint8_t *p_tr) { p[0] = av_clip_uint8(p_l[0] + p_t[0] - p_tl[0]); p[1] = av_clip_uint8(p_l[1] + p_t[1] - p_tl[1]); p[2] = av_clip_uint8(p_l[2] + p_t[2] - p_tl[2]); p[3] = av_clip_uint8(p_l[3] + p_t[3] - p_tl[3]); } static av_always_inline uint8_t clamp_add_subtract_half(int a, int b, int c) { int d = a + b >> 1; return av_clip_uint8(d + (d - c) / 2); } /* PRED_MODE_ADD_SUBTRACT_HALF */ static void inv_predict_13(uint8_t *p, const uint8_t *p_l, const uint8_t *p_tl, const uint8_t *p_t, const uint8_t *p_tr) { p[0] = clamp_add_subtract_half(p_l[0], p_t[0], p_tl[0]); p[1] = clamp_add_subtract_half(p_l[1], p_t[1], p_tl[1]); p[2] = clamp_add_subtract_half(p_l[2], p_t[2], p_tl[2]); p[3] = clamp_add_subtract_half(p_l[3], p_t[3], p_tl[3]); } typedef void (*inv_predict_func)(uint8_t *p, const uint8_t *p_l, const uint8_t *p_tl, const uint8_t *p_t, const uint8_t *p_tr); static const inv_predict_func inverse_predict[14] = { inv_predict_0, inv_predict_1, inv_predict_2, inv_predict_3, inv_predict_4, inv_predict_5, inv_predict_6, inv_predict_7, inv_predict_8, inv_predict_9, inv_predict_10, inv_predict_11, inv_predict_12, inv_predict_13, }; static void inverse_prediction(AVFrame *frame, enum PredictionMode m, int x, int y) { uint8_t *dec, *p_l, *p_tl, *p_t, *p_tr; uint8_t p[4]; dec = GET_PIXEL(frame, x, y); p_l = GET_PIXEL(frame, x - 1, y); p_tl = GET_PIXEL(frame, x - 1, y - 1); p_t = GET_PIXEL(frame, x, y - 1); if (x == frame->width - 1) p_tr = GET_PIXEL(frame, 0, y); else p_tr = GET_PIXEL(frame, x + 1, y - 1); inverse_predict[m](p, p_l, p_tl, p_t, p_tr); dec[0] += p[0]; dec[1] += p[1]; dec[2] += p[2]; dec[3] += p[3]; } static int apply_predictor_transform(WebPContext *s) { ImageContext *img = &s->image[IMAGE_ROLE_ARGB]; ImageContext *pimg = &s->image[IMAGE_ROLE_PREDICTOR]; int x, y; for (y = 0; y < img->frame->height; y++) { for (x = 0; x < img->frame->width; x++) { int tx = x >> pimg->size_reduction; int ty = y >> pimg->size_reduction; enum PredictionMode m = GET_PIXEL_COMP(pimg->frame, tx, ty, 2); if (x == 0) { if (y == 0) m = PRED_MODE_BLACK; else m = PRED_MODE_T; } else if (y == 0) m = PRED_MODE_L; if (m > 13) { av_log(s->avctx, AV_LOG_ERROR, "invalid predictor mode: %d\n", m); return AVERROR_INVALIDDATA; } inverse_prediction(img->frame, m, x, y); } } return 0; } static av_always_inline uint8_t color_transform_delta(uint8_t color_pred, uint8_t color) { return (int)ff_u8_to_s8(color_pred) * ff_u8_to_s8(color) >> 5; } static int apply_color_transform(WebPContext *s) { ImageContext *img, *cimg; int x, y, cx, cy; uint8_t *p, *cp; img = &s->image[IMAGE_ROLE_ARGB]; cimg = &s->image[IMAGE_ROLE_COLOR_TRANSFORM]; for (y = 0; y < img->frame->height; y++) { for (x = 0; x < img->frame->width; x++) { cx = x >> cimg->size_reduction; cy = y >> cimg->size_reduction; cp = GET_PIXEL(cimg->frame, cx, cy); p = GET_PIXEL(img->frame, x, y); p[1] += color_transform_delta(cp[3], p[2]); p[3] += color_transform_delta(cp[2], p[2]) + color_transform_delta(cp[1], p[1]); } } return 0; } static int apply_subtract_green_transform(WebPContext *s) { int x, y; ImageContext *img = &s->image[IMAGE_ROLE_ARGB]; for (y = 0; y < img->frame->height; y++) { for (x = 0; x < img->frame->width; x++) { uint8_t *p = GET_PIXEL(img->frame, x, y); p[1] += p[2]; p[3] += p[2]; } } return 0; } static int apply_color_indexing_transform(WebPContext *s) { ImageContext *img; ImageContext *pal; int i, x, y; uint8_t *p; img = &s->image[IMAGE_ROLE_ARGB]; pal = &s->image[IMAGE_ROLE_COLOR_INDEXING]; if (pal->size_reduction > 0) { GetBitContext gb_g; uint8_t *line; int pixel_bits = 8 >> pal->size_reduction; line = av_malloc(img->frame->linesize[0]); if (!line) return AVERROR(ENOMEM); for (y = 0; y < img->frame->height; y++) { p = GET_PIXEL(img->frame, 0, y); memcpy(line, p, img->frame->linesize[0]); init_get_bits(&gb_g, line, img->frame->linesize[0] * 8); skip_bits(&gb_g, 16); i = 0; for (x = 0; x < img->frame->width; x++) { p = GET_PIXEL(img->frame, x, y); p[2] = get_bits(&gb_g, pixel_bits); i++; if (i == 1 << pal->size_reduction) { skip_bits(&gb_g, 24); i = 0; } } } av_free(line); } // switch to local palette if it's worth initializing it if (img->frame->height * img->frame->width > 300) { uint8_t palette[256 * 4]; const int size = pal->frame->width * 4; av_assert0(size <= 1024U); memcpy(palette, GET_PIXEL(pal->frame, 0, 0), size); // copy palette // set extra entries to transparent black memset(palette + size, 0, 256 * 4 - size); for (y = 0; y < img->frame->height; y++) { for (x = 0; x < img->frame->width; x++) { p = GET_PIXEL(img->frame, x, y); i = p[2]; AV_COPY32(p, &palette[i * 4]); } } } else { for (y = 0; y < img->frame->height; y++) { for (x = 0; x < img->frame->width; x++) { p = GET_PIXEL(img->frame, x, y); i = p[2]; if (i >= pal->frame->width) { AV_WB32(p, 0x00000000); } else { const uint8_t *pi = GET_PIXEL(pal->frame, i, 0); AV_COPY32(p, pi); } } } } return 0; } static void update_canvas_size(AVCodecContext *avctx, int w, int h) { WebPContext *s = avctx->priv_data; if (s->width && s->width != w) { av_log(avctx, AV_LOG_WARNING, "Width mismatch. %d != %d\n", s->width, w); } s->width = w; if (s->height && s->height != h) { av_log(avctx, AV_LOG_WARNING, "Height mismatch. %d != %d\n", s->height, h); } s->height = h; } static int vp8_lossless_decode_frame(AVCodecContext *avctx, AVFrame *p, int *got_frame, uint8_t *data_start, unsigned int data_size, int is_alpha_chunk) { WebPContext *s = avctx->priv_data; int w, h, ret, i, used; if (!is_alpha_chunk) { s->lossless = 1; avctx->pix_fmt = AV_PIX_FMT_ARGB; } ret = init_get_bits8(&s->gb, data_start, data_size); if (ret < 0) return ret; if (!is_alpha_chunk) { if (get_bits(&s->gb, 8) != 0x2F) { av_log(avctx, AV_LOG_ERROR, "Invalid WebP Lossless signature\n"); return AVERROR_INVALIDDATA; } w = get_bits(&s->gb, 14) + 1; h = get_bits(&s->gb, 14) + 1; update_canvas_size(avctx, w, h); ret = ff_set_dimensions(avctx, s->width, s->height); if (ret < 0) return ret; s->has_alpha = get_bits1(&s->gb); if (get_bits(&s->gb, 3) != 0x0) { av_log(avctx, AV_LOG_ERROR, "Invalid WebP Lossless version\n"); return AVERROR_INVALIDDATA; } } else { if (!s->width || !s->height) return AVERROR_BUG; w = s->width; h = s->height; } /* parse transformations */ s->nb_transforms = 0; s->reduced_width = 0; used = 0; while (get_bits1(&s->gb)) { enum TransformType transform = get_bits(&s->gb, 2); if (used & (1 << transform)) { av_log(avctx, AV_LOG_ERROR, "Transform %d used more than once\n", transform); ret = AVERROR_INVALIDDATA; goto free_and_return; } used |= (1 << transform); s->transforms[s->nb_transforms++] = transform; switch (transform) { case PREDICTOR_TRANSFORM: ret = parse_transform_predictor(s); break; case COLOR_TRANSFORM: ret = parse_transform_color(s); break; case COLOR_INDEXING_TRANSFORM: ret = parse_transform_color_indexing(s); break; } if (ret < 0) goto free_and_return; } /* decode primary image */ s->image[IMAGE_ROLE_ARGB].frame = p; if (is_alpha_chunk) s->image[IMAGE_ROLE_ARGB].is_alpha_primary = 1; ret = decode_entropy_coded_image(s, IMAGE_ROLE_ARGB, w, h); if (ret < 0) goto free_and_return; /* apply transformations */ for (i = s->nb_transforms - 1; i >= 0; i--) { switch (s->transforms[i]) { case PREDICTOR_TRANSFORM: ret = apply_predictor_transform(s); break; case COLOR_TRANSFORM: ret = apply_color_transform(s); break; case SUBTRACT_GREEN: ret = apply_subtract_green_transform(s); break; case COLOR_INDEXING_TRANSFORM: ret = apply_color_indexing_transform(s); break; } if (ret < 0) goto free_and_return; } *got_frame = 1; p->pict_type = AV_PICTURE_TYPE_I; p->key_frame = 1; ret = data_size; free_and_return: for (i = 0; i < IMAGE_ROLE_NB; i++) image_ctx_free(&s->image[i]); return ret; } static void alpha_inverse_prediction(AVFrame *frame, enum AlphaFilter m) { int x, y, ls; uint8_t *dec; ls = frame->linesize[3]; /* filter first row using horizontal filter */ dec = frame->data[3] + 1; for (x = 1; x < frame->width; x++, dec++) *dec += *(dec - 1); /* filter first column using vertical filter */ dec = frame->data[3] + ls; for (y = 1; y < frame->height; y++, dec += ls) *dec += *(dec - ls); /* filter the rest using the specified filter */ switch (m) { case ALPHA_FILTER_HORIZONTAL: for (y = 1; y < frame->height; y++) { dec = frame->data[3] + y * ls + 1; for (x = 1; x < frame->width; x++, dec++) *dec += *(dec - 1); } break; case ALPHA_FILTER_VERTICAL: for (y = 1; y < frame->height; y++) { dec = frame->data[3] + y * ls + 1; for (x = 1; x < frame->width; x++, dec++) *dec += *(dec - ls); } break; case ALPHA_FILTER_GRADIENT: for (y = 1; y < frame->height; y++) { dec = frame->data[3] + y * ls + 1; for (x = 1; x < frame->width; x++, dec++) dec[0] += av_clip_uint8(*(dec - 1) + *(dec - ls) - *(dec - ls - 1)); } break; } } static int vp8_lossy_decode_alpha(AVCodecContext *avctx, AVFrame *p, uint8_t *data_start, unsigned int data_size) { WebPContext *s = avctx->priv_data; int x, y, ret; if (s->alpha_compression == ALPHA_COMPRESSION_NONE) { GetByteContext gb; bytestream2_init(&gb, data_start, data_size); for (y = 0; y < s->height; y++) bytestream2_get_buffer(&gb, p->data[3] + p->linesize[3] * y, s->width); } else if (s->alpha_compression == ALPHA_COMPRESSION_VP8L) { uint8_t *ap, *pp; int alpha_got_frame = 0; s->alpha_frame = av_frame_alloc(); if (!s->alpha_frame) return AVERROR(ENOMEM); ret = vp8_lossless_decode_frame(avctx, s->alpha_frame, &alpha_got_frame, data_start, data_size, 1); if (ret < 0) { av_frame_free(&s->alpha_frame); return ret; } if (!alpha_got_frame) { av_frame_free(&s->alpha_frame); return AVERROR_INVALIDDATA; } /* copy green component of alpha image to alpha plane of primary image */ for (y = 0; y < s->height; y++) { ap = GET_PIXEL(s->alpha_frame, 0, y) + 2; pp = p->data[3] + p->linesize[3] * y; for (x = 0; x < s->width; x++) { *pp = *ap; pp++; ap += 4; } } av_frame_free(&s->alpha_frame); } /* apply alpha filtering */ if (s->alpha_filter) alpha_inverse_prediction(p, s->alpha_filter); return 0; } static int vp8_lossy_decode_frame(AVCodecContext *avctx, AVFrame *p, int *got_frame, uint8_t *data_start, unsigned int data_size) { WebPContext *s = avctx->priv_data; AVPacket pkt; int ret; if (!s->initialized) { ff_vp8_decode_init(avctx); s->initialized = 1; } avctx->pix_fmt = s->has_alpha ? AV_PIX_FMT_YUVA420P : AV_PIX_FMT_YUV420P; s->lossless = 0; if (data_size > INT_MAX) { av_log(avctx, AV_LOG_ERROR, "unsupported chunk size\n"); return AVERROR_PATCHWELCOME; } av_init_packet(&pkt); pkt.data = data_start; pkt.size = data_size; ret = ff_vp8_decode_frame(avctx, p, got_frame, &pkt); if (ret < 0) return ret; update_canvas_size(avctx, avctx->width, avctx->height); if (s->has_alpha) { ret = vp8_lossy_decode_alpha(avctx, p, s->alpha_data, s->alpha_data_size); if (ret < 0) return ret; } return ret; } static int webp_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { AVFrame * const p = data; WebPContext *s = avctx->priv_data; GetByteContext gb; int ret; uint32_t chunk_type, chunk_size; int vp8x_flags = 0; s->avctx = avctx; s->width = 0; s->height = 0; *got_frame = 0; s->has_alpha = 0; s->has_exif = 0; bytestream2_init(&gb, avpkt->data, avpkt->size); if (bytestream2_get_bytes_left(&gb) < 12) return AVERROR_INVALIDDATA; if (bytestream2_get_le32(&gb) != MKTAG('R', 'I', 'F', 'F')) { av_log(avctx, AV_LOG_ERROR, "missing RIFF tag\n"); return AVERROR_INVALIDDATA; } chunk_size = bytestream2_get_le32(&gb); if (bytestream2_get_bytes_left(&gb) < chunk_size) return AVERROR_INVALIDDATA; if (bytestream2_get_le32(&gb) != MKTAG('W', 'E', 'B', 'P')) { av_log(avctx, AV_LOG_ERROR, "missing WEBP tag\n"); return AVERROR_INVALIDDATA; } while (bytestream2_get_bytes_left(&gb) > 8) { char chunk_str[5] = { 0 }; chunk_type = bytestream2_get_le32(&gb); chunk_size = bytestream2_get_le32(&gb); if (chunk_size == UINT32_MAX) return AVERROR_INVALIDDATA; chunk_size += chunk_size & 1; if (bytestream2_get_bytes_left(&gb) < chunk_size) return AVERROR_INVALIDDATA; switch (chunk_type) { case MKTAG('V', 'P', '8', ' '): if (!*got_frame) { ret = vp8_lossy_decode_frame(avctx, p, got_frame, avpkt->data + bytestream2_tell(&gb), chunk_size); if (ret < 0) return ret; } bytestream2_skip(&gb, chunk_size); break; case MKTAG('V', 'P', '8', 'L'): if (!*got_frame) { ret = vp8_lossless_decode_frame(avctx, p, got_frame, avpkt->data + bytestream2_tell(&gb), chunk_size, 0); if (ret < 0) return ret; avctx->properties |= FF_CODEC_PROPERTY_LOSSLESS; } bytestream2_skip(&gb, chunk_size); break; case MKTAG('V', 'P', '8', 'X'): if (s->width || s->height || *got_frame) { av_log(avctx, AV_LOG_ERROR, "Canvas dimensions are already set\n"); return AVERROR_INVALIDDATA; } vp8x_flags = bytestream2_get_byte(&gb); bytestream2_skip(&gb, 3); s->width = bytestream2_get_le24(&gb) + 1; s->height = bytestream2_get_le24(&gb) + 1; ret = av_image_check_size(s->width, s->height, 0, avctx); if (ret < 0) return ret; break; case MKTAG('A', 'L', 'P', 'H'): { int alpha_header, filter_m, compression; if (!(vp8x_flags & VP8X_FLAG_ALPHA)) { av_log(avctx, AV_LOG_WARNING, "ALPHA chunk present, but alpha bit not set in the " "VP8X header\n"); } if (chunk_size == 0) { av_log(avctx, AV_LOG_ERROR, "invalid ALPHA chunk size\n"); return AVERROR_INVALIDDATA; } alpha_header = bytestream2_get_byte(&gb); s->alpha_data = avpkt->data + bytestream2_tell(&gb); s->alpha_data_size = chunk_size - 1; bytestream2_skip(&gb, s->alpha_data_size); filter_m = (alpha_header >> 2) & 0x03; compression = alpha_header & 0x03; if (compression > ALPHA_COMPRESSION_VP8L) { av_log(avctx, AV_LOG_VERBOSE, "skipping unsupported ALPHA chunk\n"); } else { s->has_alpha = 1; s->alpha_compression = compression; s->alpha_filter = filter_m; } break; } case MKTAG('E', 'X', 'I', 'F'): { int le, ifd_offset, exif_offset = bytestream2_tell(&gb); AVDictionary *exif_metadata = NULL; GetByteContext exif_gb; if (s->has_exif) { av_log(avctx, AV_LOG_VERBOSE, "Ignoring extra EXIF chunk\n"); goto exif_end; } if (!(vp8x_flags & VP8X_FLAG_EXIF_METADATA)) av_log(avctx, AV_LOG_WARNING, "EXIF chunk present, but Exif bit not set in the " "VP8X header\n"); s->has_exif = 1; bytestream2_init(&exif_gb, avpkt->data + exif_offset, avpkt->size - exif_offset); if (ff_tdecode_header(&exif_gb, &le, &ifd_offset) < 0) { av_log(avctx, AV_LOG_ERROR, "invalid TIFF header " "in Exif data\n"); goto exif_end; } bytestream2_seek(&exif_gb, ifd_offset, SEEK_SET); if (avpriv_exif_decode_ifd(avctx, &exif_gb, le, 0, &exif_metadata) < 0) { av_log(avctx, AV_LOG_ERROR, "error decoding Exif data\n"); goto exif_end; } av_dict_copy(&((AVFrame *) data)->metadata, exif_metadata, 0); exif_end: av_dict_free(&exif_metadata); bytestream2_skip(&gb, chunk_size); break; } case MKTAG('I', 'C', 'C', 'P'): case MKTAG('A', 'N', 'I', 'M'): case MKTAG('A', 'N', 'M', 'F'): case MKTAG('X', 'M', 'P', ' '): AV_WL32(chunk_str, chunk_type); av_log(avctx, AV_LOG_WARNING, "skipping unsupported chunk: %s\n", chunk_str); bytestream2_skip(&gb, chunk_size); break; default: AV_WL32(chunk_str, chunk_type); av_log(avctx, AV_LOG_VERBOSE, "skipping unknown chunk: %s\n", chunk_str); bytestream2_skip(&gb, chunk_size); break; } } if (!*got_frame) { av_log(avctx, AV_LOG_ERROR, "image data not found\n"); return AVERROR_INVALIDDATA; } return avpkt->size; } static av_cold int webp_decode_close(AVCodecContext *avctx) { WebPContext *s = avctx->priv_data; if (s->initialized) return ff_vp8_decode_free(avctx); return 0; } AVCodec ff_webp_decoder = { .name = "webp", .long_name = NULL_IF_CONFIG_SMALL("WebP image"), .type = AVMEDIA_TYPE_VIDEO, .id = AV_CODEC_ID_WEBP, .priv_data_size = sizeof(WebPContext), .decode = webp_decode_frame, .close = webp_decode_close, .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS, };
./CrossVul/dataset_final_sorted/CWE-119/c/good_3418_1
crossvul-cpp_data_good_3857_0
/* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * Generic socket support routines. Memory allocators, socket lock/release * handler for protocols to use and generic option handler. * * * Authors: Ross Biro * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG> * Florian La Roche, <flla@stud.uni-sb.de> * Alan Cox, <A.Cox@swansea.ac.uk> * * Fixes: * Alan Cox : Numerous verify_area() problems * Alan Cox : Connecting on a connecting socket * now returns an error for tcp. * Alan Cox : sock->protocol is set correctly. * and is not sometimes left as 0. * Alan Cox : connect handles icmp errors on a * connect properly. Unfortunately there * is a restart syscall nasty there. I * can't match BSD without hacking the C * library. Ideas urgently sought! * Alan Cox : Disallow bind() to addresses that are * not ours - especially broadcast ones!! * Alan Cox : Socket 1024 _IS_ ok for users. (fencepost) * Alan Cox : sock_wfree/sock_rfree don't destroy sockets, * instead they leave that for the DESTROY timer. * Alan Cox : Clean up error flag in accept * Alan Cox : TCP ack handling is buggy, the DESTROY timer * was buggy. Put a remove_sock() in the handler * for memory when we hit 0. Also altered the timer * code. The ACK stuff can wait and needs major * TCP layer surgery. * Alan Cox : Fixed TCP ack bug, removed remove sock * and fixed timer/inet_bh race. * Alan Cox : Added zapped flag for TCP * Alan Cox : Move kfree_skb into skbuff.c and tidied up surplus code * Alan Cox : for new sk_buff allocations wmalloc/rmalloc now call alloc_skb * Alan Cox : kfree_s calls now are kfree_skbmem so we can track skb resources * Alan Cox : Supports socket option broadcast now as does udp. Packet and raw need fixing. * Alan Cox : Added RCVBUF,SNDBUF size setting. It suddenly occurred to me how easy it was so... * Rick Sladkey : Relaxed UDP rules for matching packets. * C.E.Hawkins : IFF_PROMISC/SIOCGHWADDR support * Pauline Middelink : identd support * Alan Cox : Fixed connect() taking signals I think. * Alan Cox : SO_LINGER supported * Alan Cox : Error reporting fixes * Anonymous : inet_create tidied up (sk->reuse setting) * Alan Cox : inet sockets don't set sk->type! * Alan Cox : Split socket option code * Alan Cox : Callbacks * Alan Cox : Nagle flag for Charles & Johannes stuff * Alex : Removed restriction on inet fioctl * Alan Cox : Splitting INET from NET core * Alan Cox : Fixed bogus SO_TYPE handling in getsockopt() * Adam Caldwell : Missing return in SO_DONTROUTE/SO_DEBUG code * Alan Cox : Split IP from generic code * Alan Cox : New kfree_skbmem() * Alan Cox : Make SO_DEBUG superuser only. * Alan Cox : Allow anyone to clear SO_DEBUG * (compatibility fix) * Alan Cox : Added optimistic memory grabbing for AF_UNIX throughput. * Alan Cox : Allocator for a socket is settable. * Alan Cox : SO_ERROR includes soft errors. * Alan Cox : Allow NULL arguments on some SO_ opts * Alan Cox : Generic socket allocation to make hooks * easier (suggested by Craig Metz). * Michael Pall : SO_ERROR returns positive errno again * Steve Whitehouse: Added default destructor to free * protocol private data. * Steve Whitehouse: Added various other default routines * common to several socket families. * Chris Evans : Call suser() check last on F_SETOWN * Jay Schulist : Added SO_ATTACH_FILTER and SO_DETACH_FILTER. * Andi Kleen : Add sock_kmalloc()/sock_kfree_s() * Andi Kleen : Fix write_space callback * Chris Evans : Security fixes - signedness again * Arnaldo C. Melo : cleanups, use skb_queue_purge * * To Fix: * * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #include <linux/capability.h> #include <linux/errno.h> #include <linux/types.h> #include <linux/socket.h> #include <linux/in.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/proc_fs.h> #include <linux/seq_file.h> #include <linux/sched.h> #include <linux/timer.h> #include <linux/string.h> #include <linux/sockios.h> #include <linux/net.h> #include <linux/mm.h> #include <linux/slab.h> #include <linux/interrupt.h> #include <linux/poll.h> #include <linux/tcp.h> #include <linux/init.h> #include <linux/highmem.h> #include <linux/user_namespace.h> #include <linux/static_key.h> #include <linux/memcontrol.h> #include <asm/uaccess.h> #include <linux/netdevice.h> #include <net/protocol.h> #include <linux/skbuff.h> #include <net/net_namespace.h> #include <net/request_sock.h> #include <net/sock.h> #include <linux/net_tstamp.h> #include <net/xfrm.h> #include <linux/ipsec.h> #include <net/cls_cgroup.h> #include <net/netprio_cgroup.h> #include <linux/filter.h> #include <trace/events/sock.h> #ifdef CONFIG_INET #include <net/tcp.h> #endif static DEFINE_MUTEX(proto_list_mutex); static LIST_HEAD(proto_list); #ifdef CONFIG_CGROUP_MEM_RES_CTLR_KMEM int mem_cgroup_sockets_init(struct cgroup *cgrp, struct cgroup_subsys *ss) { struct proto *proto; int ret = 0; mutex_lock(&proto_list_mutex); list_for_each_entry(proto, &proto_list, node) { if (proto->init_cgroup) { ret = proto->init_cgroup(cgrp, ss); if (ret) goto out; } } mutex_unlock(&proto_list_mutex); return ret; out: list_for_each_entry_continue_reverse(proto, &proto_list, node) if (proto->destroy_cgroup) proto->destroy_cgroup(cgrp); mutex_unlock(&proto_list_mutex); return ret; } void mem_cgroup_sockets_destroy(struct cgroup *cgrp) { struct proto *proto; mutex_lock(&proto_list_mutex); list_for_each_entry_reverse(proto, &proto_list, node) if (proto->destroy_cgroup) proto->destroy_cgroup(cgrp); mutex_unlock(&proto_list_mutex); } #endif /* * Each address family might have different locking rules, so we have * one slock key per address family: */ static struct lock_class_key af_family_keys[AF_MAX]; static struct lock_class_key af_family_slock_keys[AF_MAX]; struct static_key memcg_socket_limit_enabled; EXPORT_SYMBOL(memcg_socket_limit_enabled); /* * Make lock validator output more readable. (we pre-construct these * strings build-time, so that runtime initialization of socket * locks is fast): */ static const char *const af_family_key_strings[AF_MAX+1] = { "sk_lock-AF_UNSPEC", "sk_lock-AF_UNIX" , "sk_lock-AF_INET" , "sk_lock-AF_AX25" , "sk_lock-AF_IPX" , "sk_lock-AF_APPLETALK", "sk_lock-AF_NETROM", "sk_lock-AF_BRIDGE" , "sk_lock-AF_ATMPVC" , "sk_lock-AF_X25" , "sk_lock-AF_INET6" , "sk_lock-AF_ROSE" , "sk_lock-AF_DECnet", "sk_lock-AF_NETBEUI" , "sk_lock-AF_SECURITY" , "sk_lock-AF_KEY" , "sk_lock-AF_NETLINK" , "sk_lock-AF_PACKET" , "sk_lock-AF_ASH" , "sk_lock-AF_ECONET" , "sk_lock-AF_ATMSVC" , "sk_lock-AF_RDS" , "sk_lock-AF_SNA" , "sk_lock-AF_IRDA" , "sk_lock-AF_PPPOX" , "sk_lock-AF_WANPIPE" , "sk_lock-AF_LLC" , "sk_lock-27" , "sk_lock-28" , "sk_lock-AF_CAN" , "sk_lock-AF_TIPC" , "sk_lock-AF_BLUETOOTH", "sk_lock-IUCV" , "sk_lock-AF_RXRPC" , "sk_lock-AF_ISDN" , "sk_lock-AF_PHONET" , "sk_lock-AF_IEEE802154", "sk_lock-AF_CAIF" , "sk_lock-AF_ALG" , "sk_lock-AF_NFC" , "sk_lock-AF_MAX" }; static const char *const af_family_slock_key_strings[AF_MAX+1] = { "slock-AF_UNSPEC", "slock-AF_UNIX" , "slock-AF_INET" , "slock-AF_AX25" , "slock-AF_IPX" , "slock-AF_APPLETALK", "slock-AF_NETROM", "slock-AF_BRIDGE" , "slock-AF_ATMPVC" , "slock-AF_X25" , "slock-AF_INET6" , "slock-AF_ROSE" , "slock-AF_DECnet", "slock-AF_NETBEUI" , "slock-AF_SECURITY" , "slock-AF_KEY" , "slock-AF_NETLINK" , "slock-AF_PACKET" , "slock-AF_ASH" , "slock-AF_ECONET" , "slock-AF_ATMSVC" , "slock-AF_RDS" , "slock-AF_SNA" , "slock-AF_IRDA" , "slock-AF_PPPOX" , "slock-AF_WANPIPE" , "slock-AF_LLC" , "slock-27" , "slock-28" , "slock-AF_CAN" , "slock-AF_TIPC" , "slock-AF_BLUETOOTH", "slock-AF_IUCV" , "slock-AF_RXRPC" , "slock-AF_ISDN" , "slock-AF_PHONET" , "slock-AF_IEEE802154", "slock-AF_CAIF" , "slock-AF_ALG" , "slock-AF_NFC" , "slock-AF_MAX" }; static const char *const af_family_clock_key_strings[AF_MAX+1] = { "clock-AF_UNSPEC", "clock-AF_UNIX" , "clock-AF_INET" , "clock-AF_AX25" , "clock-AF_IPX" , "clock-AF_APPLETALK", "clock-AF_NETROM", "clock-AF_BRIDGE" , "clock-AF_ATMPVC" , "clock-AF_X25" , "clock-AF_INET6" , "clock-AF_ROSE" , "clock-AF_DECnet", "clock-AF_NETBEUI" , "clock-AF_SECURITY" , "clock-AF_KEY" , "clock-AF_NETLINK" , "clock-AF_PACKET" , "clock-AF_ASH" , "clock-AF_ECONET" , "clock-AF_ATMSVC" , "clock-AF_RDS" , "clock-AF_SNA" , "clock-AF_IRDA" , "clock-AF_PPPOX" , "clock-AF_WANPIPE" , "clock-AF_LLC" , "clock-27" , "clock-28" , "clock-AF_CAN" , "clock-AF_TIPC" , "clock-AF_BLUETOOTH", "clock-AF_IUCV" , "clock-AF_RXRPC" , "clock-AF_ISDN" , "clock-AF_PHONET" , "clock-AF_IEEE802154", "clock-AF_CAIF" , "clock-AF_ALG" , "clock-AF_NFC" , "clock-AF_MAX" }; /* * sk_callback_lock locking rules are per-address-family, * so split the lock classes by using a per-AF key: */ static struct lock_class_key af_callback_keys[AF_MAX]; /* Take into consideration the size of the struct sk_buff overhead in the * determination of these values, since that is non-constant across * platforms. This makes socket queueing behavior and performance * not depend upon such differences. */ #define _SK_MEM_PACKETS 256 #define _SK_MEM_OVERHEAD SKB_TRUESIZE(256) #define SK_WMEM_MAX (_SK_MEM_OVERHEAD * _SK_MEM_PACKETS) #define SK_RMEM_MAX (_SK_MEM_OVERHEAD * _SK_MEM_PACKETS) /* Run time adjustable parameters. */ __u32 sysctl_wmem_max __read_mostly = SK_WMEM_MAX; __u32 sysctl_rmem_max __read_mostly = SK_RMEM_MAX; __u32 sysctl_wmem_default __read_mostly = SK_WMEM_MAX; __u32 sysctl_rmem_default __read_mostly = SK_RMEM_MAX; /* Maximal space eaten by iovec or ancillary data plus some space */ int sysctl_optmem_max __read_mostly = sizeof(unsigned long)*(2*UIO_MAXIOV+512); EXPORT_SYMBOL(sysctl_optmem_max); #if defined(CONFIG_CGROUPS) #if !defined(CONFIG_NET_CLS_CGROUP) int net_cls_subsys_id = -1; EXPORT_SYMBOL_GPL(net_cls_subsys_id); #endif #if !defined(CONFIG_NETPRIO_CGROUP) int net_prio_subsys_id = -1; EXPORT_SYMBOL_GPL(net_prio_subsys_id); #endif #endif static int sock_set_timeout(long *timeo_p, char __user *optval, int optlen) { struct timeval tv; if (optlen < sizeof(tv)) return -EINVAL; if (copy_from_user(&tv, optval, sizeof(tv))) return -EFAULT; if (tv.tv_usec < 0 || tv.tv_usec >= USEC_PER_SEC) return -EDOM; if (tv.tv_sec < 0) { static int warned __read_mostly; *timeo_p = 0; if (warned < 10 && net_ratelimit()) { warned++; printk(KERN_INFO "sock_set_timeout: `%s' (pid %d) " "tries to set negative timeout\n", current->comm, task_pid_nr(current)); } return 0; } *timeo_p = MAX_SCHEDULE_TIMEOUT; if (tv.tv_sec == 0 && tv.tv_usec == 0) return 0; if (tv.tv_sec < (MAX_SCHEDULE_TIMEOUT/HZ - 1)) *timeo_p = tv.tv_sec*HZ + (tv.tv_usec+(1000000/HZ-1))/(1000000/HZ); return 0; } static void sock_warn_obsolete_bsdism(const char *name) { static int warned; static char warncomm[TASK_COMM_LEN]; if (strcmp(warncomm, current->comm) && warned < 5) { strcpy(warncomm, current->comm); printk(KERN_WARNING "process `%s' is using obsolete " "%s SO_BSDCOMPAT\n", warncomm, name); warned++; } } #define SK_FLAGS_TIMESTAMP ((1UL << SOCK_TIMESTAMP) | (1UL << SOCK_TIMESTAMPING_RX_SOFTWARE)) static void sock_disable_timestamp(struct sock *sk, unsigned long flags) { if (sk->sk_flags & flags) { sk->sk_flags &= ~flags; if (!(sk->sk_flags & SK_FLAGS_TIMESTAMP)) net_disable_timestamp(); } } int sock_queue_rcv_skb(struct sock *sk, struct sk_buff *skb) { int err; int skb_len; unsigned long flags; struct sk_buff_head *list = &sk->sk_receive_queue; if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf) { atomic_inc(&sk->sk_drops); trace_sock_rcvqueue_full(sk, skb); return -ENOMEM; } err = sk_filter(sk, skb); if (err) return err; if (!sk_rmem_schedule(sk, skb->truesize)) { atomic_inc(&sk->sk_drops); return -ENOBUFS; } skb->dev = NULL; skb_set_owner_r(skb, sk); /* Cache the SKB length before we tack it onto the receive * queue. Once it is added it no longer belongs to us and * may be freed by other threads of control pulling packets * from the queue. */ skb_len = skb->len; /* we escape from rcu protected region, make sure we dont leak * a norefcounted dst */ skb_dst_force(skb); spin_lock_irqsave(&list->lock, flags); skb->dropcount = atomic_read(&sk->sk_drops); __skb_queue_tail(list, skb); spin_unlock_irqrestore(&list->lock, flags); if (!sock_flag(sk, SOCK_DEAD)) sk->sk_data_ready(sk, skb_len); return 0; } EXPORT_SYMBOL(sock_queue_rcv_skb); int sk_receive_skb(struct sock *sk, struct sk_buff *skb, const int nested) { int rc = NET_RX_SUCCESS; if (sk_filter(sk, skb)) goto discard_and_relse; skb->dev = NULL; if (sk_rcvqueues_full(sk, skb, sk->sk_rcvbuf)) { atomic_inc(&sk->sk_drops); goto discard_and_relse; } if (nested) bh_lock_sock_nested(sk); else bh_lock_sock(sk); if (!sock_owned_by_user(sk)) { /* * trylock + unlock semantics: */ mutex_acquire(&sk->sk_lock.dep_map, 0, 1, _RET_IP_); rc = sk_backlog_rcv(sk, skb); mutex_release(&sk->sk_lock.dep_map, 1, _RET_IP_); } else if (sk_add_backlog(sk, skb, sk->sk_rcvbuf)) { bh_unlock_sock(sk); atomic_inc(&sk->sk_drops); goto discard_and_relse; } bh_unlock_sock(sk); out: sock_put(sk); return rc; discard_and_relse: kfree_skb(skb); goto out; } EXPORT_SYMBOL(sk_receive_skb); void sk_reset_txq(struct sock *sk) { sk_tx_queue_clear(sk); } EXPORT_SYMBOL(sk_reset_txq); struct dst_entry *__sk_dst_check(struct sock *sk, u32 cookie) { struct dst_entry *dst = __sk_dst_get(sk); if (dst && dst->obsolete && dst->ops->check(dst, cookie) == NULL) { sk_tx_queue_clear(sk); RCU_INIT_POINTER(sk->sk_dst_cache, NULL); dst_release(dst); return NULL; } return dst; } EXPORT_SYMBOL(__sk_dst_check); struct dst_entry *sk_dst_check(struct sock *sk, u32 cookie) { struct dst_entry *dst = sk_dst_get(sk); if (dst && dst->obsolete && dst->ops->check(dst, cookie) == NULL) { sk_dst_reset(sk); dst_release(dst); return NULL; } return dst; } EXPORT_SYMBOL(sk_dst_check); static int sock_bindtodevice(struct sock *sk, char __user *optval, int optlen) { int ret = -ENOPROTOOPT; #ifdef CONFIG_NETDEVICES struct net *net = sock_net(sk); char devname[IFNAMSIZ]; int index; /* Sorry... */ ret = -EPERM; if (!capable(CAP_NET_RAW)) goto out; ret = -EINVAL; if (optlen < 0) goto out; /* Bind this socket to a particular device like "eth0", * as specified in the passed interface name. If the * name is "" or the option length is zero the socket * is not bound. */ if (optlen > IFNAMSIZ - 1) optlen = IFNAMSIZ - 1; memset(devname, 0, sizeof(devname)); ret = -EFAULT; if (copy_from_user(devname, optval, optlen)) goto out; index = 0; if (devname[0] != '\0') { struct net_device *dev; rcu_read_lock(); dev = dev_get_by_name_rcu(net, devname); if (dev) index = dev->ifindex; rcu_read_unlock(); ret = -ENODEV; if (!dev) goto out; } lock_sock(sk); sk->sk_bound_dev_if = index; sk_dst_reset(sk); release_sock(sk); ret = 0; out: #endif return ret; } static inline void sock_valbool_flag(struct sock *sk, int bit, int valbool) { if (valbool) sock_set_flag(sk, bit); else sock_reset_flag(sk, bit); } /* * This is meant for all protocols to use and covers goings on * at the socket level. Everything here is generic. */ int sock_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; int val; int valbool; struct linger ling; int ret = 0; /* * Options without arguments */ if (optname == SO_BINDTODEVICE) return sock_bindtodevice(sk, optval, optlen); if (optlen < sizeof(int)) return -EINVAL; if (get_user(val, (int __user *)optval)) return -EFAULT; valbool = val ? 1 : 0; lock_sock(sk); switch (optname) { case SO_DEBUG: if (val && !capable(CAP_NET_ADMIN)) ret = -EACCES; else sock_valbool_flag(sk, SOCK_DBG, valbool); break; case SO_REUSEADDR: sk->sk_reuse = (valbool ? SK_CAN_REUSE : SK_NO_REUSE); break; case SO_TYPE: case SO_PROTOCOL: case SO_DOMAIN: case SO_ERROR: ret = -ENOPROTOOPT; break; case SO_DONTROUTE: sock_valbool_flag(sk, SOCK_LOCALROUTE, valbool); break; case SO_BROADCAST: sock_valbool_flag(sk, SOCK_BROADCAST, valbool); break; case SO_SNDBUF: /* Don't error on this BSD doesn't and if you think * about it this is right. Otherwise apps have to * play 'guess the biggest size' games. RCVBUF/SNDBUF * are treated in BSD as hints */ val = min_t(u32, val, sysctl_wmem_max); set_sndbuf: sk->sk_userlocks |= SOCK_SNDBUF_LOCK; sk->sk_sndbuf = max_t(u32, val * 2, SOCK_MIN_SNDBUF); /* Wake up sending tasks if we upped the value. */ sk->sk_write_space(sk); break; case SO_SNDBUFFORCE: if (!capable(CAP_NET_ADMIN)) { ret = -EPERM; break; } goto set_sndbuf; case SO_RCVBUF: /* Don't error on this BSD doesn't and if you think * about it this is right. Otherwise apps have to * play 'guess the biggest size' games. RCVBUF/SNDBUF * are treated in BSD as hints */ val = min_t(u32, val, sysctl_rmem_max); set_rcvbuf: sk->sk_userlocks |= SOCK_RCVBUF_LOCK; /* * We double it on the way in to account for * "struct sk_buff" etc. overhead. Applications * assume that the SO_RCVBUF setting they make will * allow that much actual data to be received on that * socket. * * Applications are unaware that "struct sk_buff" and * other overheads allocate from the receive buffer * during socket buffer allocation. * * And after considering the possible alternatives, * returning the value we actually used in getsockopt * is the most desirable behavior. */ sk->sk_rcvbuf = max_t(u32, val * 2, SOCK_MIN_RCVBUF); break; case SO_RCVBUFFORCE: if (!capable(CAP_NET_ADMIN)) { ret = -EPERM; break; } goto set_rcvbuf; case SO_KEEPALIVE: #ifdef CONFIG_INET if (sk->sk_protocol == IPPROTO_TCP) tcp_set_keepalive(sk, valbool); #endif sock_valbool_flag(sk, SOCK_KEEPOPEN, valbool); break; case SO_OOBINLINE: sock_valbool_flag(sk, SOCK_URGINLINE, valbool); break; case SO_NO_CHECK: sk->sk_no_check = valbool; break; case SO_PRIORITY: if ((val >= 0 && val <= 6) || capable(CAP_NET_ADMIN)) sk->sk_priority = val; else ret = -EPERM; break; case SO_LINGER: if (optlen < sizeof(ling)) { ret = -EINVAL; /* 1003.1g */ break; } if (copy_from_user(&ling, optval, sizeof(ling))) { ret = -EFAULT; break; } if (!ling.l_onoff) sock_reset_flag(sk, SOCK_LINGER); else { #if (BITS_PER_LONG == 32) if ((unsigned int)ling.l_linger >= MAX_SCHEDULE_TIMEOUT/HZ) sk->sk_lingertime = MAX_SCHEDULE_TIMEOUT; else #endif sk->sk_lingertime = (unsigned int)ling.l_linger * HZ; sock_set_flag(sk, SOCK_LINGER); } break; case SO_BSDCOMPAT: sock_warn_obsolete_bsdism("setsockopt"); break; case SO_PASSCRED: if (valbool) set_bit(SOCK_PASSCRED, &sock->flags); else clear_bit(SOCK_PASSCRED, &sock->flags); break; case SO_TIMESTAMP: case SO_TIMESTAMPNS: if (valbool) { if (optname == SO_TIMESTAMP) sock_reset_flag(sk, SOCK_RCVTSTAMPNS); else sock_set_flag(sk, SOCK_RCVTSTAMPNS); sock_set_flag(sk, SOCK_RCVTSTAMP); sock_enable_timestamp(sk, SOCK_TIMESTAMP); } else { sock_reset_flag(sk, SOCK_RCVTSTAMP); sock_reset_flag(sk, SOCK_RCVTSTAMPNS); } break; case SO_TIMESTAMPING: if (val & ~SOF_TIMESTAMPING_MASK) { ret = -EINVAL; break; } sock_valbool_flag(sk, SOCK_TIMESTAMPING_TX_HARDWARE, val & SOF_TIMESTAMPING_TX_HARDWARE); sock_valbool_flag(sk, SOCK_TIMESTAMPING_TX_SOFTWARE, val & SOF_TIMESTAMPING_TX_SOFTWARE); sock_valbool_flag(sk, SOCK_TIMESTAMPING_RX_HARDWARE, val & SOF_TIMESTAMPING_RX_HARDWARE); if (val & SOF_TIMESTAMPING_RX_SOFTWARE) sock_enable_timestamp(sk, SOCK_TIMESTAMPING_RX_SOFTWARE); else sock_disable_timestamp(sk, (1UL << SOCK_TIMESTAMPING_RX_SOFTWARE)); sock_valbool_flag(sk, SOCK_TIMESTAMPING_SOFTWARE, val & SOF_TIMESTAMPING_SOFTWARE); sock_valbool_flag(sk, SOCK_TIMESTAMPING_SYS_HARDWARE, val & SOF_TIMESTAMPING_SYS_HARDWARE); sock_valbool_flag(sk, SOCK_TIMESTAMPING_RAW_HARDWARE, val & SOF_TIMESTAMPING_RAW_HARDWARE); break; case SO_RCVLOWAT: if (val < 0) val = INT_MAX; sk->sk_rcvlowat = val ? : 1; break; case SO_RCVTIMEO: ret = sock_set_timeout(&sk->sk_rcvtimeo, optval, optlen); break; case SO_SNDTIMEO: ret = sock_set_timeout(&sk->sk_sndtimeo, optval, optlen); break; case SO_ATTACH_FILTER: ret = -EINVAL; if (optlen == sizeof(struct sock_fprog)) { struct sock_fprog fprog; ret = -EFAULT; if (copy_from_user(&fprog, optval, sizeof(fprog))) break; ret = sk_attach_filter(&fprog, sk); } break; case SO_DETACH_FILTER: ret = sk_detach_filter(sk); break; case SO_PASSSEC: if (valbool) set_bit(SOCK_PASSSEC, &sock->flags); else clear_bit(SOCK_PASSSEC, &sock->flags); break; case SO_MARK: if (!capable(CAP_NET_ADMIN)) ret = -EPERM; else sk->sk_mark = val; break; /* We implement the SO_SNDLOWAT etc to not be settable (1003.1g 5.3) */ case SO_RXQ_OVFL: sock_valbool_flag(sk, SOCK_RXQ_OVFL, valbool); break; case SO_WIFI_STATUS: sock_valbool_flag(sk, SOCK_WIFI_STATUS, valbool); break; case SO_PEEK_OFF: if (sock->ops->set_peek_off) sock->ops->set_peek_off(sk, val); else ret = -EOPNOTSUPP; break; case SO_NOFCS: sock_valbool_flag(sk, SOCK_NOFCS, valbool); break; default: ret = -ENOPROTOOPT; break; } release_sock(sk); return ret; } EXPORT_SYMBOL(sock_setsockopt); void cred_to_ucred(struct pid *pid, const struct cred *cred, struct ucred *ucred) { ucred->pid = pid_vnr(pid); ucred->uid = ucred->gid = -1; if (cred) { struct user_namespace *current_ns = current_user_ns(); ucred->uid = user_ns_map_uid(current_ns, cred, cred->euid); ucred->gid = user_ns_map_gid(current_ns, cred, cred->egid); } } EXPORT_SYMBOL_GPL(cred_to_ucred); int sock_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; union { int val; struct linger ling; struct timeval tm; } v; int lv = sizeof(int); int len; if (get_user(len, optlen)) return -EFAULT; if (len < 0) return -EINVAL; memset(&v, 0, sizeof(v)); switch (optname) { case SO_DEBUG: v.val = sock_flag(sk, SOCK_DBG); break; case SO_DONTROUTE: v.val = sock_flag(sk, SOCK_LOCALROUTE); break; case SO_BROADCAST: v.val = !!sock_flag(sk, SOCK_BROADCAST); break; case SO_SNDBUF: v.val = sk->sk_sndbuf; break; case SO_RCVBUF: v.val = sk->sk_rcvbuf; break; case SO_REUSEADDR: v.val = sk->sk_reuse; break; case SO_KEEPALIVE: v.val = !!sock_flag(sk, SOCK_KEEPOPEN); break; case SO_TYPE: v.val = sk->sk_type; break; case SO_PROTOCOL: v.val = sk->sk_protocol; break; case SO_DOMAIN: v.val = sk->sk_family; break; case SO_ERROR: v.val = -sock_error(sk); if (v.val == 0) v.val = xchg(&sk->sk_err_soft, 0); break; case SO_OOBINLINE: v.val = !!sock_flag(sk, SOCK_URGINLINE); break; case SO_NO_CHECK: v.val = sk->sk_no_check; break; case SO_PRIORITY: v.val = sk->sk_priority; break; case SO_LINGER: lv = sizeof(v.ling); v.ling.l_onoff = !!sock_flag(sk, SOCK_LINGER); v.ling.l_linger = sk->sk_lingertime / HZ; break; case SO_BSDCOMPAT: sock_warn_obsolete_bsdism("getsockopt"); break; case SO_TIMESTAMP: v.val = sock_flag(sk, SOCK_RCVTSTAMP) && !sock_flag(sk, SOCK_RCVTSTAMPNS); break; case SO_TIMESTAMPNS: v.val = sock_flag(sk, SOCK_RCVTSTAMPNS); break; case SO_TIMESTAMPING: v.val = 0; if (sock_flag(sk, SOCK_TIMESTAMPING_TX_HARDWARE)) v.val |= SOF_TIMESTAMPING_TX_HARDWARE; if (sock_flag(sk, SOCK_TIMESTAMPING_TX_SOFTWARE)) v.val |= SOF_TIMESTAMPING_TX_SOFTWARE; if (sock_flag(sk, SOCK_TIMESTAMPING_RX_HARDWARE)) v.val |= SOF_TIMESTAMPING_RX_HARDWARE; if (sock_flag(sk, SOCK_TIMESTAMPING_RX_SOFTWARE)) v.val |= SOF_TIMESTAMPING_RX_SOFTWARE; if (sock_flag(sk, SOCK_TIMESTAMPING_SOFTWARE)) v.val |= SOF_TIMESTAMPING_SOFTWARE; if (sock_flag(sk, SOCK_TIMESTAMPING_SYS_HARDWARE)) v.val |= SOF_TIMESTAMPING_SYS_HARDWARE; if (sock_flag(sk, SOCK_TIMESTAMPING_RAW_HARDWARE)) v.val |= SOF_TIMESTAMPING_RAW_HARDWARE; break; case SO_RCVTIMEO: lv = sizeof(struct timeval); if (sk->sk_rcvtimeo == MAX_SCHEDULE_TIMEOUT) { v.tm.tv_sec = 0; v.tm.tv_usec = 0; } else { v.tm.tv_sec = sk->sk_rcvtimeo / HZ; v.tm.tv_usec = ((sk->sk_rcvtimeo % HZ) * 1000000) / HZ; } break; case SO_SNDTIMEO: lv = sizeof(struct timeval); if (sk->sk_sndtimeo == MAX_SCHEDULE_TIMEOUT) { v.tm.tv_sec = 0; v.tm.tv_usec = 0; } else { v.tm.tv_sec = sk->sk_sndtimeo / HZ; v.tm.tv_usec = ((sk->sk_sndtimeo % HZ) * 1000000) / HZ; } break; case SO_RCVLOWAT: v.val = sk->sk_rcvlowat; break; case SO_SNDLOWAT: v.val = 1; break; case SO_PASSCRED: v.val = !!test_bit(SOCK_PASSCRED, &sock->flags); break; case SO_PEERCRED: { struct ucred peercred; if (len > sizeof(peercred)) len = sizeof(peercred); cred_to_ucred(sk->sk_peer_pid, sk->sk_peer_cred, &peercred); if (copy_to_user(optval, &peercred, len)) return -EFAULT; goto lenout; } case SO_PEERNAME: { char address[128]; if (sock->ops->getname(sock, (struct sockaddr *)address, &lv, 2)) return -ENOTCONN; if (lv < len) return -EINVAL; if (copy_to_user(optval, address, len)) return -EFAULT; goto lenout; } /* Dubious BSD thing... Probably nobody even uses it, but * the UNIX standard wants it for whatever reason... -DaveM */ case SO_ACCEPTCONN: v.val = sk->sk_state == TCP_LISTEN; break; case SO_PASSSEC: v.val = !!test_bit(SOCK_PASSSEC, &sock->flags); break; case SO_PEERSEC: return security_socket_getpeersec_stream(sock, optval, optlen, len); case SO_MARK: v.val = sk->sk_mark; break; case SO_RXQ_OVFL: v.val = !!sock_flag(sk, SOCK_RXQ_OVFL); break; case SO_WIFI_STATUS: v.val = !!sock_flag(sk, SOCK_WIFI_STATUS); break; case SO_PEEK_OFF: if (!sock->ops->set_peek_off) return -EOPNOTSUPP; v.val = sk->sk_peek_off; break; case SO_NOFCS: v.val = !!sock_flag(sk, SOCK_NOFCS); break; default: return -ENOPROTOOPT; } if (len > lv) len = lv; if (copy_to_user(optval, &v, len)) return -EFAULT; lenout: if (put_user(len, optlen)) return -EFAULT; return 0; } /* * Initialize an sk_lock. * * (We also register the sk_lock with the lock validator.) */ static inline void sock_lock_init(struct sock *sk) { sock_lock_init_class_and_name(sk, af_family_slock_key_strings[sk->sk_family], af_family_slock_keys + sk->sk_family, af_family_key_strings[sk->sk_family], af_family_keys + sk->sk_family); } /* * Copy all fields from osk to nsk but nsk->sk_refcnt must not change yet, * even temporarly, because of RCU lookups. sk_node should also be left as is. * We must not copy fields between sk_dontcopy_begin and sk_dontcopy_end */ static void sock_copy(struct sock *nsk, const struct sock *osk) { #ifdef CONFIG_SECURITY_NETWORK void *sptr = nsk->sk_security; #endif memcpy(nsk, osk, offsetof(struct sock, sk_dontcopy_begin)); memcpy(&nsk->sk_dontcopy_end, &osk->sk_dontcopy_end, osk->sk_prot->obj_size - offsetof(struct sock, sk_dontcopy_end)); #ifdef CONFIG_SECURITY_NETWORK nsk->sk_security = sptr; security_sk_clone(osk, nsk); #endif } /* * caches using SLAB_DESTROY_BY_RCU should let .next pointer from nulls nodes * un-modified. Special care is taken when initializing object to zero. */ static inline void sk_prot_clear_nulls(struct sock *sk, int size) { if (offsetof(struct sock, sk_node.next) != 0) memset(sk, 0, offsetof(struct sock, sk_node.next)); memset(&sk->sk_node.pprev, 0, size - offsetof(struct sock, sk_node.pprev)); } void sk_prot_clear_portaddr_nulls(struct sock *sk, int size) { unsigned long nulls1, nulls2; nulls1 = offsetof(struct sock, __sk_common.skc_node.next); nulls2 = offsetof(struct sock, __sk_common.skc_portaddr_node.next); if (nulls1 > nulls2) swap(nulls1, nulls2); if (nulls1 != 0) memset((char *)sk, 0, nulls1); memset((char *)sk + nulls1 + sizeof(void *), 0, nulls2 - nulls1 - sizeof(void *)); memset((char *)sk + nulls2 + sizeof(void *), 0, size - nulls2 - sizeof(void *)); } EXPORT_SYMBOL(sk_prot_clear_portaddr_nulls); static struct sock *sk_prot_alloc(struct proto *prot, gfp_t priority, int family) { struct sock *sk; struct kmem_cache *slab; slab = prot->slab; if (slab != NULL) { sk = kmem_cache_alloc(slab, priority & ~__GFP_ZERO); if (!sk) return sk; if (priority & __GFP_ZERO) { if (prot->clear_sk) prot->clear_sk(sk, prot->obj_size); else sk_prot_clear_nulls(sk, prot->obj_size); } } else sk = kmalloc(prot->obj_size, priority); if (sk != NULL) { kmemcheck_annotate_bitfield(sk, flags); if (security_sk_alloc(sk, family, priority)) goto out_free; if (!try_module_get(prot->owner)) goto out_free_sec; sk_tx_queue_clear(sk); } return sk; out_free_sec: security_sk_free(sk); out_free: if (slab != NULL) kmem_cache_free(slab, sk); else kfree(sk); return NULL; } static void sk_prot_free(struct proto *prot, struct sock *sk) { struct kmem_cache *slab; struct module *owner; owner = prot->owner; slab = prot->slab; security_sk_free(sk); if (slab != NULL) kmem_cache_free(slab, sk); else kfree(sk); module_put(owner); } #ifdef CONFIG_CGROUPS void sock_update_classid(struct sock *sk) { u32 classid; rcu_read_lock(); /* doing current task, which cannot vanish. */ classid = task_cls_classid(current); rcu_read_unlock(); if (classid && classid != sk->sk_classid) sk->sk_classid = classid; } EXPORT_SYMBOL(sock_update_classid); void sock_update_netprioidx(struct sock *sk) { if (in_interrupt()) return; sk->sk_cgrp_prioidx = task_netprioidx(current); } EXPORT_SYMBOL_GPL(sock_update_netprioidx); #endif /** * sk_alloc - All socket objects are allocated here * @net: the applicable net namespace * @family: protocol family * @priority: for allocation (%GFP_KERNEL, %GFP_ATOMIC, etc) * @prot: struct proto associated with this new sock instance */ struct sock *sk_alloc(struct net *net, int family, gfp_t priority, struct proto *prot) { struct sock *sk; sk = sk_prot_alloc(prot, priority | __GFP_ZERO, family); if (sk) { sk->sk_family = family; /* * See comment in struct sock definition to understand * why we need sk_prot_creator -acme */ sk->sk_prot = sk->sk_prot_creator = prot; sock_lock_init(sk); sock_net_set(sk, get_net(net)); atomic_set(&sk->sk_wmem_alloc, 1); sock_update_classid(sk); sock_update_netprioidx(sk); } return sk; } EXPORT_SYMBOL(sk_alloc); static void __sk_free(struct sock *sk) { struct sk_filter *filter; if (sk->sk_destruct) sk->sk_destruct(sk); filter = rcu_dereference_check(sk->sk_filter, atomic_read(&sk->sk_wmem_alloc) == 0); if (filter) { sk_filter_uncharge(sk, filter); RCU_INIT_POINTER(sk->sk_filter, NULL); } sock_disable_timestamp(sk, SK_FLAGS_TIMESTAMP); if (atomic_read(&sk->sk_omem_alloc)) printk(KERN_DEBUG "%s: optmem leakage (%d bytes) detected.\n", __func__, atomic_read(&sk->sk_omem_alloc)); if (sk->sk_peer_cred) put_cred(sk->sk_peer_cred); put_pid(sk->sk_peer_pid); put_net(sock_net(sk)); sk_prot_free(sk->sk_prot_creator, sk); } void sk_free(struct sock *sk) { /* * We subtract one from sk_wmem_alloc and can know if * some packets are still in some tx queue. * If not null, sock_wfree() will call __sk_free(sk) later */ if (atomic_dec_and_test(&sk->sk_wmem_alloc)) __sk_free(sk); } EXPORT_SYMBOL(sk_free); /* * Last sock_put should drop reference to sk->sk_net. It has already * been dropped in sk_change_net. Taking reference to stopping namespace * is not an option. * Take reference to a socket to remove it from hash _alive_ and after that * destroy it in the context of init_net. */ void sk_release_kernel(struct sock *sk) { if (sk == NULL || sk->sk_socket == NULL) return; sock_hold(sk); sock_release(sk->sk_socket); release_net(sock_net(sk)); sock_net_set(sk, get_net(&init_net)); sock_put(sk); } EXPORT_SYMBOL(sk_release_kernel); static void sk_update_clone(const struct sock *sk, struct sock *newsk) { if (mem_cgroup_sockets_enabled && sk->sk_cgrp) sock_update_memcg(newsk); } /** * sk_clone_lock - clone a socket, and lock its clone * @sk: the socket to clone * @priority: for allocation (%GFP_KERNEL, %GFP_ATOMIC, etc) * * Caller must unlock socket even in error path (bh_unlock_sock(newsk)) */ struct sock *sk_clone_lock(const struct sock *sk, const gfp_t priority) { struct sock *newsk; newsk = sk_prot_alloc(sk->sk_prot, priority, sk->sk_family); if (newsk != NULL) { struct sk_filter *filter; sock_copy(newsk, sk); /* SANITY */ get_net(sock_net(newsk)); sk_node_init(&newsk->sk_node); sock_lock_init(newsk); bh_lock_sock(newsk); newsk->sk_backlog.head = newsk->sk_backlog.tail = NULL; newsk->sk_backlog.len = 0; atomic_set(&newsk->sk_rmem_alloc, 0); /* * sk_wmem_alloc set to one (see sk_free() and sock_wfree()) */ atomic_set(&newsk->sk_wmem_alloc, 1); atomic_set(&newsk->sk_omem_alloc, 0); skb_queue_head_init(&newsk->sk_receive_queue); skb_queue_head_init(&newsk->sk_write_queue); #ifdef CONFIG_NET_DMA skb_queue_head_init(&newsk->sk_async_wait_queue); #endif spin_lock_init(&newsk->sk_dst_lock); rwlock_init(&newsk->sk_callback_lock); lockdep_set_class_and_name(&newsk->sk_callback_lock, af_callback_keys + newsk->sk_family, af_family_clock_key_strings[newsk->sk_family]); newsk->sk_dst_cache = NULL; newsk->sk_wmem_queued = 0; newsk->sk_forward_alloc = 0; newsk->sk_send_head = NULL; newsk->sk_userlocks = sk->sk_userlocks & ~SOCK_BINDPORT_LOCK; sock_reset_flag(newsk, SOCK_DONE); skb_queue_head_init(&newsk->sk_error_queue); filter = rcu_dereference_protected(newsk->sk_filter, 1); if (filter != NULL) sk_filter_charge(newsk, filter); if (unlikely(xfrm_sk_clone_policy(newsk))) { /* It is still raw copy of parent, so invalidate * destructor and make plain sk_free() */ newsk->sk_destruct = NULL; bh_unlock_sock(newsk); sk_free(newsk); newsk = NULL; goto out; } newsk->sk_err = 0; newsk->sk_priority = 0; /* * Before updating sk_refcnt, we must commit prior changes to memory * (Documentation/RCU/rculist_nulls.txt for details) */ smp_wmb(); atomic_set(&newsk->sk_refcnt, 2); /* * Increment the counter in the same struct proto as the master * sock (sk_refcnt_debug_inc uses newsk->sk_prot->socks, that * is the same as sk->sk_prot->socks, as this field was copied * with memcpy). * * This _changes_ the previous behaviour, where * tcp_create_openreq_child always was incrementing the * equivalent to tcp_prot->socks (inet_sock_nr), so this have * to be taken into account in all callers. -acme */ sk_refcnt_debug_inc(newsk); sk_set_socket(newsk, NULL); newsk->sk_wq = NULL; sk_update_clone(sk, newsk); if (newsk->sk_prot->sockets_allocated) sk_sockets_allocated_inc(newsk); if (newsk->sk_flags & SK_FLAGS_TIMESTAMP) net_enable_timestamp(); } out: return newsk; } EXPORT_SYMBOL_GPL(sk_clone_lock); void sk_setup_caps(struct sock *sk, struct dst_entry *dst) { __sk_dst_set(sk, dst); sk->sk_route_caps = dst->dev->features; if (sk->sk_route_caps & NETIF_F_GSO) sk->sk_route_caps |= NETIF_F_GSO_SOFTWARE; sk->sk_route_caps &= ~sk->sk_route_nocaps; if (sk_can_gso(sk)) { if (dst->header_len) { sk->sk_route_caps &= ~NETIF_F_GSO_MASK; } else { sk->sk_route_caps |= NETIF_F_SG | NETIF_F_HW_CSUM; sk->sk_gso_max_size = dst->dev->gso_max_size; } } } EXPORT_SYMBOL_GPL(sk_setup_caps); void __init sk_init(void) { if (totalram_pages <= 4096) { sysctl_wmem_max = 32767; sysctl_rmem_max = 32767; sysctl_wmem_default = 32767; sysctl_rmem_default = 32767; } else if (totalram_pages >= 131072) { sysctl_wmem_max = 131071; sysctl_rmem_max = 131071; } } /* * Simple resource managers for sockets. */ /* * Write buffer destructor automatically called from kfree_skb. */ void sock_wfree(struct sk_buff *skb) { struct sock *sk = skb->sk; unsigned int len = skb->truesize; if (!sock_flag(sk, SOCK_USE_WRITE_QUEUE)) { /* * Keep a reference on sk_wmem_alloc, this will be released * after sk_write_space() call */ atomic_sub(len - 1, &sk->sk_wmem_alloc); sk->sk_write_space(sk); len = 1; } /* * if sk_wmem_alloc reaches 0, we must finish what sk_free() * could not do because of in-flight packets */ if (atomic_sub_and_test(len, &sk->sk_wmem_alloc)) __sk_free(sk); } EXPORT_SYMBOL(sock_wfree); /* * Read buffer destructor automatically called from kfree_skb. */ void sock_rfree(struct sk_buff *skb) { struct sock *sk = skb->sk; unsigned int len = skb->truesize; atomic_sub(len, &sk->sk_rmem_alloc); sk_mem_uncharge(sk, len); } EXPORT_SYMBOL(sock_rfree); int sock_i_uid(struct sock *sk) { int uid; read_lock_bh(&sk->sk_callback_lock); uid = sk->sk_socket ? SOCK_INODE(sk->sk_socket)->i_uid : 0; read_unlock_bh(&sk->sk_callback_lock); return uid; } EXPORT_SYMBOL(sock_i_uid); unsigned long sock_i_ino(struct sock *sk) { unsigned long ino; read_lock_bh(&sk->sk_callback_lock); ino = sk->sk_socket ? SOCK_INODE(sk->sk_socket)->i_ino : 0; read_unlock_bh(&sk->sk_callback_lock); return ino; } EXPORT_SYMBOL(sock_i_ino); /* * Allocate a skb from the socket's send buffer. */ struct sk_buff *sock_wmalloc(struct sock *sk, unsigned long size, int force, gfp_t priority) { if (force || atomic_read(&sk->sk_wmem_alloc) < sk->sk_sndbuf) { struct sk_buff *skb = alloc_skb(size, priority); if (skb) { skb_set_owner_w(skb, sk); return skb; } } return NULL; } EXPORT_SYMBOL(sock_wmalloc); /* * Allocate a skb from the socket's receive buffer. */ struct sk_buff *sock_rmalloc(struct sock *sk, unsigned long size, int force, gfp_t priority) { if (force || atomic_read(&sk->sk_rmem_alloc) < sk->sk_rcvbuf) { struct sk_buff *skb = alloc_skb(size, priority); if (skb) { skb_set_owner_r(skb, sk); return skb; } } return NULL; } /* * Allocate a memory block from the socket's option memory buffer. */ void *sock_kmalloc(struct sock *sk, int size, gfp_t priority) { if ((unsigned int)size <= sysctl_optmem_max && atomic_read(&sk->sk_omem_alloc) + size < sysctl_optmem_max) { void *mem; /* First do the add, to avoid the race if kmalloc * might sleep. */ atomic_add(size, &sk->sk_omem_alloc); mem = kmalloc(size, priority); if (mem) return mem; atomic_sub(size, &sk->sk_omem_alloc); } return NULL; } EXPORT_SYMBOL(sock_kmalloc); /* * Free an option memory block. */ void sock_kfree_s(struct sock *sk, void *mem, int size) { kfree(mem); atomic_sub(size, &sk->sk_omem_alloc); } EXPORT_SYMBOL(sock_kfree_s); /* It is almost wait_for_tcp_memory minus release_sock/lock_sock. I think, these locks should be removed for datagram sockets. */ static long sock_wait_for_wmem(struct sock *sk, long timeo) { DEFINE_WAIT(wait); clear_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags); for (;;) { if (!timeo) break; if (signal_pending(current)) break; set_bit(SOCK_NOSPACE, &sk->sk_socket->flags); prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); if (atomic_read(&sk->sk_wmem_alloc) < sk->sk_sndbuf) break; if (sk->sk_shutdown & SEND_SHUTDOWN) break; if (sk->sk_err) break; timeo = schedule_timeout(timeo); } finish_wait(sk_sleep(sk), &wait); return timeo; } /* * Generic send/receive buffer handlers */ struct sk_buff *sock_alloc_send_pskb(struct sock *sk, unsigned long header_len, unsigned long data_len, int noblock, int *errcode) { struct sk_buff *skb; gfp_t gfp_mask; long timeo; int err; gfp_mask = sk->sk_allocation; if (gfp_mask & __GFP_WAIT) gfp_mask |= __GFP_REPEAT; timeo = sock_sndtimeo(sk, noblock); while (1) { err = sock_error(sk); if (err != 0) goto failure; err = -EPIPE; if (sk->sk_shutdown & SEND_SHUTDOWN) goto failure; if (atomic_read(&sk->sk_wmem_alloc) < sk->sk_sndbuf) { skb = alloc_skb(header_len, gfp_mask); if (skb) { int npages; int i; /* No pages, we're done... */ if (!data_len) break; npages = (data_len + (PAGE_SIZE - 1)) >> PAGE_SHIFT; skb->truesize += data_len; skb_shinfo(skb)->nr_frags = npages; for (i = 0; i < npages; i++) { struct page *page; page = alloc_pages(sk->sk_allocation, 0); if (!page) { err = -ENOBUFS; skb_shinfo(skb)->nr_frags = i; kfree_skb(skb); goto failure; } __skb_fill_page_desc(skb, i, page, 0, (data_len >= PAGE_SIZE ? PAGE_SIZE : data_len)); data_len -= PAGE_SIZE; } /* Full success... */ break; } err = -ENOBUFS; goto failure; } set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags); set_bit(SOCK_NOSPACE, &sk->sk_socket->flags); err = -EAGAIN; if (!timeo) goto failure; if (signal_pending(current)) goto interrupted; timeo = sock_wait_for_wmem(sk, timeo); } skb_set_owner_w(skb, sk); return skb; interrupted: err = sock_intr_errno(timeo); failure: *errcode = err; return NULL; } EXPORT_SYMBOL(sock_alloc_send_pskb); struct sk_buff *sock_alloc_send_skb(struct sock *sk, unsigned long size, int noblock, int *errcode) { return sock_alloc_send_pskb(sk, size, 0, noblock, errcode); } EXPORT_SYMBOL(sock_alloc_send_skb); static void __lock_sock(struct sock *sk) __releases(&sk->sk_lock.slock) __acquires(&sk->sk_lock.slock) { DEFINE_WAIT(wait); for (;;) { prepare_to_wait_exclusive(&sk->sk_lock.wq, &wait, TASK_UNINTERRUPTIBLE); spin_unlock_bh(&sk->sk_lock.slock); schedule(); spin_lock_bh(&sk->sk_lock.slock); if (!sock_owned_by_user(sk)) break; } finish_wait(&sk->sk_lock.wq, &wait); } static void __release_sock(struct sock *sk) __releases(&sk->sk_lock.slock) __acquires(&sk->sk_lock.slock) { struct sk_buff *skb = sk->sk_backlog.head; do { sk->sk_backlog.head = sk->sk_backlog.tail = NULL; bh_unlock_sock(sk); do { struct sk_buff *next = skb->next; WARN_ON_ONCE(skb_dst_is_noref(skb)); skb->next = NULL; sk_backlog_rcv(sk, skb); /* * We are in process context here with softirqs * disabled, use cond_resched_softirq() to preempt. * This is safe to do because we've taken the backlog * queue private: */ cond_resched_softirq(); skb = next; } while (skb != NULL); bh_lock_sock(sk); } while ((skb = sk->sk_backlog.head) != NULL); /* * Doing the zeroing here guarantee we can not loop forever * while a wild producer attempts to flood us. */ sk->sk_backlog.len = 0; } /** * sk_wait_data - wait for data to arrive at sk_receive_queue * @sk: sock to wait on * @timeo: for how long * * Now socket state including sk->sk_err is changed only under lock, * hence we may omit checks after joining wait queue. * We check receive queue before schedule() only as optimization; * it is very likely that release_sock() added new data. */ int sk_wait_data(struct sock *sk, long *timeo) { int rc; DEFINE_WAIT(wait); prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); set_bit(SOCK_ASYNC_WAITDATA, &sk->sk_socket->flags); rc = sk_wait_event(sk, timeo, !skb_queue_empty(&sk->sk_receive_queue)); clear_bit(SOCK_ASYNC_WAITDATA, &sk->sk_socket->flags); finish_wait(sk_sleep(sk), &wait); return rc; } EXPORT_SYMBOL(sk_wait_data); /** * __sk_mem_schedule - increase sk_forward_alloc and memory_allocated * @sk: socket * @size: memory size to allocate * @kind: allocation type * * If kind is SK_MEM_SEND, it means wmem allocation. Otherwise it means * rmem allocation. This function assumes that protocols which have * memory_pressure use sk_wmem_queued as write buffer accounting. */ int __sk_mem_schedule(struct sock *sk, int size, int kind) { struct proto *prot = sk->sk_prot; int amt = sk_mem_pages(size); long allocated; int parent_status = UNDER_LIMIT; sk->sk_forward_alloc += amt * SK_MEM_QUANTUM; allocated = sk_memory_allocated_add(sk, amt, &parent_status); /* Under limit. */ if (parent_status == UNDER_LIMIT && allocated <= sk_prot_mem_limits(sk, 0)) { sk_leave_memory_pressure(sk); return 1; } /* Under pressure. (we or our parents) */ if ((parent_status > SOFT_LIMIT) || allocated > sk_prot_mem_limits(sk, 1)) sk_enter_memory_pressure(sk); /* Over hard limit (we or our parents) */ if ((parent_status == OVER_LIMIT) || (allocated > sk_prot_mem_limits(sk, 2))) goto suppress_allocation; /* guarantee minimum buffer size under pressure */ if (kind == SK_MEM_RECV) { if (atomic_read(&sk->sk_rmem_alloc) < prot->sysctl_rmem[0]) return 1; } else { /* SK_MEM_SEND */ if (sk->sk_type == SOCK_STREAM) { if (sk->sk_wmem_queued < prot->sysctl_wmem[0]) return 1; } else if (atomic_read(&sk->sk_wmem_alloc) < prot->sysctl_wmem[0]) return 1; } if (sk_has_memory_pressure(sk)) { int alloc; if (!sk_under_memory_pressure(sk)) return 1; alloc = sk_sockets_allocated_read_positive(sk); if (sk_prot_mem_limits(sk, 2) > alloc * sk_mem_pages(sk->sk_wmem_queued + atomic_read(&sk->sk_rmem_alloc) + sk->sk_forward_alloc)) return 1; } suppress_allocation: if (kind == SK_MEM_SEND && sk->sk_type == SOCK_STREAM) { sk_stream_moderate_sndbuf(sk); /* Fail only if socket is _under_ its sndbuf. * In this case we cannot block, so that we have to fail. */ if (sk->sk_wmem_queued + size >= sk->sk_sndbuf) return 1; } trace_sock_exceed_buf_limit(sk, prot, allocated); /* Alas. Undo changes. */ sk->sk_forward_alloc -= amt * SK_MEM_QUANTUM; sk_memory_allocated_sub(sk, amt); return 0; } EXPORT_SYMBOL(__sk_mem_schedule); /** * __sk_reclaim - reclaim memory_allocated * @sk: socket */ void __sk_mem_reclaim(struct sock *sk) { sk_memory_allocated_sub(sk, sk->sk_forward_alloc >> SK_MEM_QUANTUM_SHIFT); sk->sk_forward_alloc &= SK_MEM_QUANTUM - 1; if (sk_under_memory_pressure(sk) && (sk_memory_allocated(sk) < sk_prot_mem_limits(sk, 0))) sk_leave_memory_pressure(sk); } EXPORT_SYMBOL(__sk_mem_reclaim); /* * Set of default routines for initialising struct proto_ops when * the protocol does not support a particular function. In certain * cases where it makes no sense for a protocol to have a "do nothing" * function, some default processing is provided. */ int sock_no_bind(struct socket *sock, struct sockaddr *saddr, int len) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_bind); int sock_no_connect(struct socket *sock, struct sockaddr *saddr, int len, int flags) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_connect); int sock_no_socketpair(struct socket *sock1, struct socket *sock2) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_socketpair); int sock_no_accept(struct socket *sock, struct socket *newsock, int flags) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_accept); int sock_no_getname(struct socket *sock, struct sockaddr *saddr, int *len, int peer) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_getname); unsigned int sock_no_poll(struct file *file, struct socket *sock, poll_table *pt) { return 0; } EXPORT_SYMBOL(sock_no_poll); int sock_no_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_ioctl); int sock_no_listen(struct socket *sock, int backlog) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_listen); int sock_no_shutdown(struct socket *sock, int how) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_shutdown); int sock_no_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_setsockopt); int sock_no_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_getsockopt); int sock_no_sendmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *m, size_t len) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_sendmsg); int sock_no_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *m, size_t len, int flags) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_recvmsg); int sock_no_mmap(struct file *file, struct socket *sock, struct vm_area_struct *vma) { /* Mirror missing mmap method error code */ return -ENODEV; } EXPORT_SYMBOL(sock_no_mmap); ssize_t sock_no_sendpage(struct socket *sock, struct page *page, int offset, size_t size, int flags) { ssize_t res; struct msghdr msg = {.msg_flags = flags}; struct kvec iov; char *kaddr = kmap(page); iov.iov_base = kaddr + offset; iov.iov_len = size; res = kernel_sendmsg(sock, &msg, &iov, 1, size); kunmap(page); return res; } EXPORT_SYMBOL(sock_no_sendpage); /* * Default Socket Callbacks */ static void sock_def_wakeup(struct sock *sk) { struct socket_wq *wq; rcu_read_lock(); wq = rcu_dereference(sk->sk_wq); if (wq_has_sleeper(wq)) wake_up_interruptible_all(&wq->wait); rcu_read_unlock(); } static void sock_def_error_report(struct sock *sk) { struct socket_wq *wq; rcu_read_lock(); wq = rcu_dereference(sk->sk_wq); if (wq_has_sleeper(wq)) wake_up_interruptible_poll(&wq->wait, POLLERR); sk_wake_async(sk, SOCK_WAKE_IO, POLL_ERR); rcu_read_unlock(); } static void sock_def_readable(struct sock *sk, int len) { struct socket_wq *wq; rcu_read_lock(); wq = rcu_dereference(sk->sk_wq); if (wq_has_sleeper(wq)) wake_up_interruptible_sync_poll(&wq->wait, POLLIN | POLLPRI | POLLRDNORM | POLLRDBAND); sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_IN); rcu_read_unlock(); } static void sock_def_write_space(struct sock *sk) { struct socket_wq *wq; rcu_read_lock(); /* Do not wake up a writer until he can make "significant" * progress. --DaveM */ if ((atomic_read(&sk->sk_wmem_alloc) << 1) <= sk->sk_sndbuf) { wq = rcu_dereference(sk->sk_wq); if (wq_has_sleeper(wq)) wake_up_interruptible_sync_poll(&wq->wait, POLLOUT | POLLWRNORM | POLLWRBAND); /* Should agree with poll, otherwise some programs break */ if (sock_writeable(sk)) sk_wake_async(sk, SOCK_WAKE_SPACE, POLL_OUT); } rcu_read_unlock(); } static void sock_def_destruct(struct sock *sk) { kfree(sk->sk_protinfo); } void sk_send_sigurg(struct sock *sk) { if (sk->sk_socket && sk->sk_socket->file) if (send_sigurg(&sk->sk_socket->file->f_owner)) sk_wake_async(sk, SOCK_WAKE_URG, POLL_PRI); } EXPORT_SYMBOL(sk_send_sigurg); void sk_reset_timer(struct sock *sk, struct timer_list* timer, unsigned long expires) { if (!mod_timer(timer, expires)) sock_hold(sk); } EXPORT_SYMBOL(sk_reset_timer); void sk_stop_timer(struct sock *sk, struct timer_list* timer) { if (timer_pending(timer) && del_timer(timer)) __sock_put(sk); } EXPORT_SYMBOL(sk_stop_timer); void sock_init_data(struct socket *sock, struct sock *sk) { skb_queue_head_init(&sk->sk_receive_queue); skb_queue_head_init(&sk->sk_write_queue); skb_queue_head_init(&sk->sk_error_queue); #ifdef CONFIG_NET_DMA skb_queue_head_init(&sk->sk_async_wait_queue); #endif sk->sk_send_head = NULL; init_timer(&sk->sk_timer); sk->sk_allocation = GFP_KERNEL; sk->sk_rcvbuf = sysctl_rmem_default; sk->sk_sndbuf = sysctl_wmem_default; sk->sk_state = TCP_CLOSE; sk_set_socket(sk, sock); sock_set_flag(sk, SOCK_ZAPPED); if (sock) { sk->sk_type = sock->type; sk->sk_wq = sock->wq; sock->sk = sk; } else sk->sk_wq = NULL; spin_lock_init(&sk->sk_dst_lock); rwlock_init(&sk->sk_callback_lock); lockdep_set_class_and_name(&sk->sk_callback_lock, af_callback_keys + sk->sk_family, af_family_clock_key_strings[sk->sk_family]); sk->sk_state_change = sock_def_wakeup; sk->sk_data_ready = sock_def_readable; sk->sk_write_space = sock_def_write_space; sk->sk_error_report = sock_def_error_report; sk->sk_destruct = sock_def_destruct; sk->sk_sndmsg_page = NULL; sk->sk_sndmsg_off = 0; sk->sk_peek_off = -1; sk->sk_peer_pid = NULL; sk->sk_peer_cred = NULL; sk->sk_write_pending = 0; sk->sk_rcvlowat = 1; sk->sk_rcvtimeo = MAX_SCHEDULE_TIMEOUT; sk->sk_sndtimeo = MAX_SCHEDULE_TIMEOUT; sk->sk_stamp = ktime_set(-1L, 0); /* * Before updating sk_refcnt, we must commit prior changes to memory * (Documentation/RCU/rculist_nulls.txt for details) */ smp_wmb(); atomic_set(&sk->sk_refcnt, 1); atomic_set(&sk->sk_drops, 0); } EXPORT_SYMBOL(sock_init_data); void lock_sock_nested(struct sock *sk, int subclass) { might_sleep(); spin_lock_bh(&sk->sk_lock.slock); if (sk->sk_lock.owned) __lock_sock(sk); sk->sk_lock.owned = 1; spin_unlock(&sk->sk_lock.slock); /* * The sk_lock has mutex_lock() semantics here: */ mutex_acquire(&sk->sk_lock.dep_map, subclass, 0, _RET_IP_); local_bh_enable(); } EXPORT_SYMBOL(lock_sock_nested); void release_sock(struct sock *sk) { /* * The sk_lock has mutex_unlock() semantics: */ mutex_release(&sk->sk_lock.dep_map, 1, _RET_IP_); spin_lock_bh(&sk->sk_lock.slock); if (sk->sk_backlog.tail) __release_sock(sk); sk->sk_lock.owned = 0; if (waitqueue_active(&sk->sk_lock.wq)) wake_up(&sk->sk_lock.wq); spin_unlock_bh(&sk->sk_lock.slock); } EXPORT_SYMBOL(release_sock); /** * lock_sock_fast - fast version of lock_sock * @sk: socket * * This version should be used for very small section, where process wont block * return false if fast path is taken * sk_lock.slock locked, owned = 0, BH disabled * return true if slow path is taken * sk_lock.slock unlocked, owned = 1, BH enabled */ bool lock_sock_fast(struct sock *sk) { might_sleep(); spin_lock_bh(&sk->sk_lock.slock); if (!sk->sk_lock.owned) /* * Note : We must disable BH */ return false; __lock_sock(sk); sk->sk_lock.owned = 1; spin_unlock(&sk->sk_lock.slock); /* * The sk_lock has mutex_lock() semantics here: */ mutex_acquire(&sk->sk_lock.dep_map, 0, 0, _RET_IP_); local_bh_enable(); return true; } EXPORT_SYMBOL(lock_sock_fast); int sock_get_timestamp(struct sock *sk, struct timeval __user *userstamp) { struct timeval tv; if (!sock_flag(sk, SOCK_TIMESTAMP)) sock_enable_timestamp(sk, SOCK_TIMESTAMP); tv = ktime_to_timeval(sk->sk_stamp); if (tv.tv_sec == -1) return -ENOENT; if (tv.tv_sec == 0) { sk->sk_stamp = ktime_get_real(); tv = ktime_to_timeval(sk->sk_stamp); } return copy_to_user(userstamp, &tv, sizeof(tv)) ? -EFAULT : 0; } EXPORT_SYMBOL(sock_get_timestamp); int sock_get_timestampns(struct sock *sk, struct timespec __user *userstamp) { struct timespec ts; if (!sock_flag(sk, SOCK_TIMESTAMP)) sock_enable_timestamp(sk, SOCK_TIMESTAMP); ts = ktime_to_timespec(sk->sk_stamp); if (ts.tv_sec == -1) return -ENOENT; if (ts.tv_sec == 0) { sk->sk_stamp = ktime_get_real(); ts = ktime_to_timespec(sk->sk_stamp); } return copy_to_user(userstamp, &ts, sizeof(ts)) ? -EFAULT : 0; } EXPORT_SYMBOL(sock_get_timestampns); void sock_enable_timestamp(struct sock *sk, int flag) { if (!sock_flag(sk, flag)) { unsigned long previous_flags = sk->sk_flags; sock_set_flag(sk, flag); /* * we just set one of the two flags which require net * time stamping, but time stamping might have been on * already because of the other one */ if (!(previous_flags & SK_FLAGS_TIMESTAMP)) net_enable_timestamp(); } } /* * Get a socket option on an socket. * * FIX: POSIX 1003.1g is very ambiguous here. It states that * asynchronous errors should be reported by getsockopt. We assume * this means if you specify SO_ERROR (otherwise whats the point of it). */ int sock_common_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; return sk->sk_prot->getsockopt(sk, level, optname, optval, optlen); } EXPORT_SYMBOL(sock_common_getsockopt); #ifdef CONFIG_COMPAT int compat_sock_common_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; if (sk->sk_prot->compat_getsockopt != NULL) return sk->sk_prot->compat_getsockopt(sk, level, optname, optval, optlen); return sk->sk_prot->getsockopt(sk, level, optname, optval, optlen); } EXPORT_SYMBOL(compat_sock_common_getsockopt); #endif int sock_common_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; int addr_len = 0; int err; err = sk->sk_prot->recvmsg(iocb, sk, msg, size, flags & MSG_DONTWAIT, flags & ~MSG_DONTWAIT, &addr_len); if (err >= 0) msg->msg_namelen = addr_len; return err; } EXPORT_SYMBOL(sock_common_recvmsg); /* * Set socket options on an inet socket. */ int sock_common_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; return sk->sk_prot->setsockopt(sk, level, optname, optval, optlen); } EXPORT_SYMBOL(sock_common_setsockopt); #ifdef CONFIG_COMPAT int compat_sock_common_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; if (sk->sk_prot->compat_setsockopt != NULL) return sk->sk_prot->compat_setsockopt(sk, level, optname, optval, optlen); return sk->sk_prot->setsockopt(sk, level, optname, optval, optlen); } EXPORT_SYMBOL(compat_sock_common_setsockopt); #endif void sk_common_release(struct sock *sk) { if (sk->sk_prot->destroy) sk->sk_prot->destroy(sk); /* * Observation: when sock_common_release is called, processes have * no access to socket. But net still has. * Step one, detach it from networking: * * A. Remove from hash tables. */ sk->sk_prot->unhash(sk); /* * In this point socket cannot receive new packets, but it is possible * that some packets are in flight because some CPU runs receiver and * did hash table lookup before we unhashed socket. They will achieve * receive queue and will be purged by socket destructor. * * Also we still have packets pending on receive queue and probably, * our own packets waiting in device queues. sock_destroy will drain * receive queue, but transmitted packets will delay socket destruction * until the last reference will be released. */ sock_orphan(sk); xfrm_sk_free_policy(sk); sk_refcnt_debug_release(sk); sock_put(sk); } EXPORT_SYMBOL(sk_common_release); #ifdef CONFIG_PROC_FS #define PROTO_INUSE_NR 64 /* should be enough for the first time */ struct prot_inuse { int val[PROTO_INUSE_NR]; }; static DECLARE_BITMAP(proto_inuse_idx, PROTO_INUSE_NR); #ifdef CONFIG_NET_NS void sock_prot_inuse_add(struct net *net, struct proto *prot, int val) { __this_cpu_add(net->core.inuse->val[prot->inuse_idx], val); } EXPORT_SYMBOL_GPL(sock_prot_inuse_add); int sock_prot_inuse_get(struct net *net, struct proto *prot) { int cpu, idx = prot->inuse_idx; int res = 0; for_each_possible_cpu(cpu) res += per_cpu_ptr(net->core.inuse, cpu)->val[idx]; return res >= 0 ? res : 0; } EXPORT_SYMBOL_GPL(sock_prot_inuse_get); static int __net_init sock_inuse_init_net(struct net *net) { net->core.inuse = alloc_percpu(struct prot_inuse); return net->core.inuse ? 0 : -ENOMEM; } static void __net_exit sock_inuse_exit_net(struct net *net) { free_percpu(net->core.inuse); } static struct pernet_operations net_inuse_ops = { .init = sock_inuse_init_net, .exit = sock_inuse_exit_net, }; static __init int net_inuse_init(void) { if (register_pernet_subsys(&net_inuse_ops)) panic("Cannot initialize net inuse counters"); return 0; } core_initcall(net_inuse_init); #else static DEFINE_PER_CPU(struct prot_inuse, prot_inuse); void sock_prot_inuse_add(struct net *net, struct proto *prot, int val) { __this_cpu_add(prot_inuse.val[prot->inuse_idx], val); } EXPORT_SYMBOL_GPL(sock_prot_inuse_add); int sock_prot_inuse_get(struct net *net, struct proto *prot) { int cpu, idx = prot->inuse_idx; int res = 0; for_each_possible_cpu(cpu) res += per_cpu(prot_inuse, cpu).val[idx]; return res >= 0 ? res : 0; } EXPORT_SYMBOL_GPL(sock_prot_inuse_get); #endif static void assign_proto_idx(struct proto *prot) { prot->inuse_idx = find_first_zero_bit(proto_inuse_idx, PROTO_INUSE_NR); if (unlikely(prot->inuse_idx == PROTO_INUSE_NR - 1)) { printk(KERN_ERR "PROTO_INUSE_NR exhausted\n"); return; } set_bit(prot->inuse_idx, proto_inuse_idx); } static void release_proto_idx(struct proto *prot) { if (prot->inuse_idx != PROTO_INUSE_NR - 1) clear_bit(prot->inuse_idx, proto_inuse_idx); } #else static inline void assign_proto_idx(struct proto *prot) { } static inline void release_proto_idx(struct proto *prot) { } #endif int proto_register(struct proto *prot, int alloc_slab) { if (alloc_slab) { prot->slab = kmem_cache_create(prot->name, prot->obj_size, 0, SLAB_HWCACHE_ALIGN | prot->slab_flags, NULL); if (prot->slab == NULL) { printk(KERN_CRIT "%s: Can't create sock SLAB cache!\n", prot->name); goto out; } if (prot->rsk_prot != NULL) { prot->rsk_prot->slab_name = kasprintf(GFP_KERNEL, "request_sock_%s", prot->name); if (prot->rsk_prot->slab_name == NULL) goto out_free_sock_slab; prot->rsk_prot->slab = kmem_cache_create(prot->rsk_prot->slab_name, prot->rsk_prot->obj_size, 0, SLAB_HWCACHE_ALIGN, NULL); if (prot->rsk_prot->slab == NULL) { printk(KERN_CRIT "%s: Can't create request sock SLAB cache!\n", prot->name); goto out_free_request_sock_slab_name; } } if (prot->twsk_prot != NULL) { prot->twsk_prot->twsk_slab_name = kasprintf(GFP_KERNEL, "tw_sock_%s", prot->name); if (prot->twsk_prot->twsk_slab_name == NULL) goto out_free_request_sock_slab; prot->twsk_prot->twsk_slab = kmem_cache_create(prot->twsk_prot->twsk_slab_name, prot->twsk_prot->twsk_obj_size, 0, SLAB_HWCACHE_ALIGN | prot->slab_flags, NULL); if (prot->twsk_prot->twsk_slab == NULL) goto out_free_timewait_sock_slab_name; } } mutex_lock(&proto_list_mutex); list_add(&prot->node, &proto_list); assign_proto_idx(prot); mutex_unlock(&proto_list_mutex); return 0; out_free_timewait_sock_slab_name: kfree(prot->twsk_prot->twsk_slab_name); out_free_request_sock_slab: if (prot->rsk_prot && prot->rsk_prot->slab) { kmem_cache_destroy(prot->rsk_prot->slab); prot->rsk_prot->slab = NULL; } out_free_request_sock_slab_name: if (prot->rsk_prot) kfree(prot->rsk_prot->slab_name); out_free_sock_slab: kmem_cache_destroy(prot->slab); prot->slab = NULL; out: return -ENOBUFS; } EXPORT_SYMBOL(proto_register); void proto_unregister(struct proto *prot) { mutex_lock(&proto_list_mutex); release_proto_idx(prot); list_del(&prot->node); mutex_unlock(&proto_list_mutex); if (prot->slab != NULL) { kmem_cache_destroy(prot->slab); prot->slab = NULL; } if (prot->rsk_prot != NULL && prot->rsk_prot->slab != NULL) { kmem_cache_destroy(prot->rsk_prot->slab); kfree(prot->rsk_prot->slab_name); prot->rsk_prot->slab = NULL; } if (prot->twsk_prot != NULL && prot->twsk_prot->twsk_slab != NULL) { kmem_cache_destroy(prot->twsk_prot->twsk_slab); kfree(prot->twsk_prot->twsk_slab_name); prot->twsk_prot->twsk_slab = NULL; } } EXPORT_SYMBOL(proto_unregister); #ifdef CONFIG_PROC_FS static void *proto_seq_start(struct seq_file *seq, loff_t *pos) __acquires(proto_list_mutex) { mutex_lock(&proto_list_mutex); return seq_list_start_head(&proto_list, *pos); } static void *proto_seq_next(struct seq_file *seq, void *v, loff_t *pos) { return seq_list_next(v, &proto_list, pos); } static void proto_seq_stop(struct seq_file *seq, void *v) __releases(proto_list_mutex) { mutex_unlock(&proto_list_mutex); } static char proto_method_implemented(const void *method) { return method == NULL ? 'n' : 'y'; } static long sock_prot_memory_allocated(struct proto *proto) { return proto->memory_allocated != NULL ? proto_memory_allocated(proto): -1L; } static char *sock_prot_memory_pressure(struct proto *proto) { return proto->memory_pressure != NULL ? proto_memory_pressure(proto) ? "yes" : "no" : "NI"; } static void proto_seq_printf(struct seq_file *seq, struct proto *proto) { seq_printf(seq, "%-9s %4u %6d %6ld %-3s %6u %-3s %-10s " "%2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c\n", proto->name, proto->obj_size, sock_prot_inuse_get(seq_file_net(seq), proto), sock_prot_memory_allocated(proto), sock_prot_memory_pressure(proto), proto->max_header, proto->slab == NULL ? "no" : "yes", module_name(proto->owner), proto_method_implemented(proto->close), proto_method_implemented(proto->connect), proto_method_implemented(proto->disconnect), proto_method_implemented(proto->accept), proto_method_implemented(proto->ioctl), proto_method_implemented(proto->init), proto_method_implemented(proto->destroy), proto_method_implemented(proto->shutdown), proto_method_implemented(proto->setsockopt), proto_method_implemented(proto->getsockopt), proto_method_implemented(proto->sendmsg), proto_method_implemented(proto->recvmsg), proto_method_implemented(proto->sendpage), proto_method_implemented(proto->bind), proto_method_implemented(proto->backlog_rcv), proto_method_implemented(proto->hash), proto_method_implemented(proto->unhash), proto_method_implemented(proto->get_port), proto_method_implemented(proto->enter_memory_pressure)); } static int proto_seq_show(struct seq_file *seq, void *v) { if (v == &proto_list) seq_printf(seq, "%-9s %-4s %-8s %-6s %-5s %-7s %-4s %-10s %s", "protocol", "size", "sockets", "memory", "press", "maxhdr", "slab", "module", "cl co di ac io in de sh ss gs se re sp bi br ha uh gp em\n"); else proto_seq_printf(seq, list_entry(v, struct proto, node)); return 0; } static const struct seq_operations proto_seq_ops = { .start = proto_seq_start, .next = proto_seq_next, .stop = proto_seq_stop, .show = proto_seq_show, }; static int proto_seq_open(struct inode *inode, struct file *file) { return seq_open_net(inode, file, &proto_seq_ops, sizeof(struct seq_net_private)); } static const struct file_operations proto_seq_fops = { .owner = THIS_MODULE, .open = proto_seq_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release_net, }; static __net_init int proto_init_net(struct net *net) { if (!proc_net_fops_create(net, "protocols", S_IRUGO, &proto_seq_fops)) return -ENOMEM; return 0; } static __net_exit void proto_exit_net(struct net *net) { proc_net_remove(net, "protocols"); } static __net_initdata struct pernet_operations proto_net_ops = { .init = proto_init_net, .exit = proto_exit_net, }; static int __init proto_init(void) { return register_pernet_subsys(&proto_net_ops); } subsys_initcall(proto_init); #endif /* PROC_FS */
./CrossVul/dataset_final_sorted/CWE-119/c/good_3857_0
crossvul-cpp_data_bad_2863_0
/* radare - LGPL - Copyright 2008-2017 - nibble, pancake, alvaro_fe */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <r_types.h> #include <r_util.h> #include "elf.h" #ifdef IFDBG #undef IFDBG #endif #define DO_THE_DBG 0 #define IFDBG if (DO_THE_DBG) #define IFINT if (0) #define ELF_PAGE_MASK 0xFFFFFFFFFFFFF000LL #define ELF_PAGE_SIZE 12 #define R_ELF_NO_RELRO 0 #define R_ELF_PART_RELRO 1 #define R_ELF_FULL_RELRO 2 #define bprintf if(bin->verbose)eprintf #define READ8(x, i) r_read_ble8(x + i); i += 1; #define READ16(x, i) r_read_ble16(x + i, bin->endian); i += 2; #define READ32(x, i) r_read_ble32(x + i, bin->endian); i += 4; #define READ64(x, i) r_read_ble64(x + i, bin->endian); i += 8; #define GROWTH_FACTOR (1.5) static inline int __strnlen(const char *str, int len) { int l = 0; while (IS_PRINTABLE (*str) && --len) { if (((ut8)*str) == 0xff) { break; } str++; l++; } return l + 1; } static int handle_e_ident(ELFOBJ *bin) { return !strncmp ((char *)bin->ehdr.e_ident, ELFMAG, SELFMAG) || !strncmp ((char *)bin->ehdr.e_ident, CGCMAG, SCGCMAG); } static int init_ehdr(ELFOBJ *bin) { ut8 e_ident[EI_NIDENT]; ut8 ehdr[sizeof (Elf_(Ehdr))] = {0}; int i, len; if (r_buf_read_at (bin->b, 0, e_ident, EI_NIDENT) == -1) { bprintf ("Warning: read (magic)\n"); return false; } sdb_set (bin->kv, "elf_type.cparse", "enum elf_type { ET_NONE=0, ET_REL=1," " ET_EXEC=2, ET_DYN=3, ET_CORE=4, ET_LOOS=0xfe00, ET_HIOS=0xfeff," " ET_LOPROC=0xff00, ET_HIPROC=0xffff };", 0); sdb_set (bin->kv, "elf_machine.cparse", "enum elf_machine{EM_NONE=0, EM_M32=1," " EM_SPARC=2, EM_386=3, EM_68K=4, EM_88K=5, EM_486=6, " " EM_860=7, EM_MIPS=8, EM_S370=9, EM_MIPS_RS3_LE=10, EM_RS6000=11," " EM_UNKNOWN12=12, EM_UNKNOWN13=13, EM_UNKNOWN14=14, " " EM_PA_RISC=15, EM_PARISC=EM_PA_RISC, EM_nCUBE=16, EM_VPP500=17," " EM_SPARC32PLUS=18, EM_960=19, EM_PPC=20, EM_PPC64=21, " " EM_S390=22, EM_UNKNOWN22=EM_S390, EM_UNKNOWN23=23, EM_UNKNOWN24=24," " EM_UNKNOWN25=25, EM_UNKNOWN26=26, EM_UNKNOWN27=27, EM_UNKNOWN28=28," " EM_UNKNOWN29=29, EM_UNKNOWN30=30, EM_UNKNOWN31=31, EM_UNKNOWN32=32," " EM_UNKNOWN33=33, EM_UNKNOWN34=34, EM_UNKNOWN35=35, EM_V800=36," " EM_FR20=37, EM_RH32=38, EM_RCE=39, EM_ARM=40, EM_ALPHA=41, EM_SH=42," " EM_SPARCV9=43, EM_TRICORE=44, EM_ARC=45, EM_H8_300=46, EM_H8_300H=47," " EM_H8S=48, EM_H8_500=49, EM_IA_64=50, EM_MIPS_X=51, EM_COLDFIRE=52," " EM_68HC12=53, EM_MMA=54, EM_PCP=55, EM_NCPU=56, EM_NDR1=57," " EM_STARCORE=58, EM_ME16=59, EM_ST100=60, EM_TINYJ=61, EM_AMD64=62," " EM_X86_64=EM_AMD64, EM_PDSP=63, EM_UNKNOWN64=64, EM_UNKNOWN65=65," " EM_FX66=66, EM_ST9PLUS=67, EM_ST7=68, EM_68HC16=69, EM_68HC11=70," " EM_68HC08=71, EM_68HC05=72, EM_SVX=73, EM_ST19=74, EM_VAX=75, " " EM_CRIS=76, EM_JAVELIN=77, EM_FIREPATH=78, EM_ZSP=79, EM_MMIX=80," " EM_HUANY=81, EM_PRISM=82, EM_AVR=83, EM_FR30=84, EM_D10V=85, EM_D30V=86," " EM_V850=87, EM_M32R=88, EM_MN10300=89, EM_MN10200=90, EM_PJ=91," " EM_OPENRISC=92, EM_ARC_A5=93, EM_XTENSA=94, EM_NUM=95};", 0); sdb_num_set (bin->kv, "elf_header.offset", 0, 0); sdb_num_set (bin->kv, "elf_header.size", sizeof (Elf_(Ehdr)), 0); #if R_BIN_ELF64 sdb_set (bin->kv, "elf_header.format", "[16]z[2]E[2]Exqqqxwwwwww" " ident (elf_type)type (elf_machine)machine version entry phoff shoff flags ehsize" " phentsize phnum shentsize shnum shstrndx", 0); #else sdb_set (bin->kv, "elf_header.format", "[16]z[2]E[2]Exxxxxwwwwww" " ident (elf_type)type (elf_machine)machine version entry phoff shoff flags ehsize" " phentsize phnum shentsize shnum shstrndx", 0); #endif bin->endian = (e_ident[EI_DATA] == ELFDATA2MSB)? 1: 0; memset (&bin->ehdr, 0, sizeof (Elf_(Ehdr))); len = r_buf_read_at (bin->b, 0, ehdr, sizeof (Elf_(Ehdr))); if (len < 1) { bprintf ("Warning: read (ehdr)\n"); return false; } memcpy (&bin->ehdr.e_ident, ehdr, 16); i = 16; bin->ehdr.e_type = READ16 (ehdr, i) bin->ehdr.e_machine = READ16 (ehdr, i) bin->ehdr.e_version = READ32 (ehdr, i) #if R_BIN_ELF64 bin->ehdr.e_entry = READ64 (ehdr, i) bin->ehdr.e_phoff = READ64 (ehdr, i) bin->ehdr.e_shoff = READ64 (ehdr, i) #else bin->ehdr.e_entry = READ32 (ehdr, i) bin->ehdr.e_phoff = READ32 (ehdr, i) bin->ehdr.e_shoff = READ32 (ehdr, i) #endif bin->ehdr.e_flags = READ32 (ehdr, i) bin->ehdr.e_ehsize = READ16 (ehdr, i) bin->ehdr.e_phentsize = READ16 (ehdr, i) bin->ehdr.e_phnum = READ16 (ehdr, i) bin->ehdr.e_shentsize = READ16 (ehdr, i) bin->ehdr.e_shnum = READ16 (ehdr, i) bin->ehdr.e_shstrndx = READ16 (ehdr, i) return handle_e_ident (bin); // Usage example: // > td `k bin/cur/info/elf_type.cparse`; td `k bin/cur/info/elf_machine.cparse` // > pf `k bin/cur/info/elf_header.format` @ `k bin/cur/info/elf_header.offset` } static int init_phdr(ELFOBJ *bin) { ut32 phdr_size; ut8 phdr[sizeof (Elf_(Phdr))] = {0}; int i, j, len; if (!bin->ehdr.e_phnum) { return false; } if (bin->phdr) { return true; } if (!UT32_MUL (&phdr_size, (ut32)bin->ehdr.e_phnum, sizeof (Elf_(Phdr)))) { return false; } if (!phdr_size) { return false; } if (phdr_size > bin->size) { return false; } if (phdr_size > (ut32)bin->size) { return false; } if (bin->ehdr.e_phoff > bin->size) { return false; } if (bin->ehdr.e_phoff + phdr_size > bin->size) { return false; } if (!(bin->phdr = calloc (phdr_size, 1))) { perror ("malloc (phdr)"); return false; } for (i = 0; i < bin->ehdr.e_phnum; i++) { j = 0; len = r_buf_read_at (bin->b, bin->ehdr.e_phoff + i * sizeof (Elf_(Phdr)), phdr, sizeof (Elf_(Phdr))); if (len < 1) { bprintf ("Warning: read (phdr)\n"); R_FREE (bin->phdr); return false; } bin->phdr[i].p_type = READ32 (phdr, j) #if R_BIN_ELF64 bin->phdr[i].p_flags = READ32 (phdr, j) bin->phdr[i].p_offset = READ64 (phdr, j) bin->phdr[i].p_vaddr = READ64 (phdr, j) bin->phdr[i].p_paddr = READ64 (phdr, j) bin->phdr[i].p_filesz = READ64 (phdr, j) bin->phdr[i].p_memsz = READ64 (phdr, j) bin->phdr[i].p_align = READ64 (phdr, j) #else bin->phdr[i].p_offset = READ32 (phdr, j) bin->phdr[i].p_vaddr = READ32 (phdr, j) bin->phdr[i].p_paddr = READ32 (phdr, j) bin->phdr[i].p_filesz = READ32 (phdr, j) bin->phdr[i].p_memsz = READ32 (phdr, j) bin->phdr[i].p_flags = READ32 (phdr, j) bin->phdr[i].p_align = READ32 (phdr, j) #endif } sdb_num_set (bin->kv, "elf_phdr.offset", bin->ehdr.e_phoff, 0); sdb_num_set (bin->kv, "elf_phdr.size", sizeof (Elf_(Phdr)), 0); sdb_set (bin->kv, "elf_p_type.cparse", "enum elf_p_type {PT_NULL=0,PT_LOAD=1,PT_DYNAMIC=2," "PT_INTERP=3,PT_NOTE=4,PT_SHLIB=5,PT_PHDR=6,PT_LOOS=0x60000000," "PT_HIOS=0x6fffffff,PT_LOPROC=0x70000000,PT_HIPROC=0x7fffffff};", 0); sdb_set (bin->kv, "elf_p_flags.cparse", "enum elf_p_flags {PF_None=0,PF_Exec=1," "PF_Write=2,PF_Write_Exec=3,PF_Read=4,PF_Read_Exec=5,PF_Read_Write=6," "PF_Read_Write_Exec=7};", 0); #if R_BIN_ELF64 sdb_set (bin->kv, "elf_phdr.format", "[4]E[4]Eqqqqqq (elf_p_type)type (elf_p_flags)flags" " offset vaddr paddr filesz memsz align", 0); #else sdb_set (bin->kv, "elf_phdr.format", "[4]Exxxxx[4]Ex (elf_p_type)type offset vaddr paddr" " filesz memsz (elf_p_flags)flags align", 0); #endif return true; // Usage example: // > td `k bin/cur/info/elf_p_type.cparse`; td `k bin/cur/info/elf_p_flags.cparse` // > pf `k bin/cur/info/elf_phdr.format` @ `k bin/cur/info/elf_phdr.offset` } static int init_shdr(ELFOBJ *bin) { ut32 shdr_size; ut8 shdr[sizeof (Elf_(Shdr))] = {0}; int i, j, len; if (!bin || bin->shdr) { return true; } if (!UT32_MUL (&shdr_size, bin->ehdr.e_shnum, sizeof (Elf_(Shdr)))) { return false; } if (shdr_size < 1) { return false; } if (shdr_size > bin->size) { return false; } if (bin->ehdr.e_shoff > bin->size) { return false; } if (bin->ehdr.e_shoff + shdr_size > bin->size) { return false; } if (!(bin->shdr = calloc (1, shdr_size + 1))) { perror ("malloc (shdr)"); return false; } sdb_num_set (bin->kv, "elf_shdr.offset", bin->ehdr.e_shoff, 0); sdb_num_set (bin->kv, "elf_shdr.size", sizeof (Elf_(Shdr)), 0); sdb_set (bin->kv, "elf_s_type.cparse", "enum elf_s_type {SHT_NULL=0,SHT_PROGBITS=1," "SHT_SYMTAB=2,SHT_STRTAB=3,SHT_RELA=4,SHT_HASH=5,SHT_DYNAMIC=6,SHT_NOTE=7," "SHT_NOBITS=8,SHT_REL=9,SHT_SHLIB=10,SHT_DYNSYM=11,SHT_LOOS=0x60000000," "SHT_HIOS=0x6fffffff,SHT_LOPROC=0x70000000,SHT_HIPROC=0x7fffffff};", 0); for (i = 0; i < bin->ehdr.e_shnum; i++) { j = 0; len = r_buf_read_at (bin->b, bin->ehdr.e_shoff + i * sizeof (Elf_(Shdr)), shdr, sizeof (Elf_(Shdr))); if (len < 1) { bprintf ("Warning: read (shdr) at 0x%"PFMT64x"\n", (ut64) bin->ehdr.e_shoff); R_FREE (bin->shdr); return false; } bin->shdr[i].sh_name = READ32 (shdr, j) bin->shdr[i].sh_type = READ32 (shdr, j) #if R_BIN_ELF64 bin->shdr[i].sh_flags = READ64 (shdr, j) bin->shdr[i].sh_addr = READ64 (shdr, j) bin->shdr[i].sh_offset = READ64 (shdr, j) bin->shdr[i].sh_size = READ64 (shdr, j) bin->shdr[i].sh_link = READ32 (shdr, j) bin->shdr[i].sh_info = READ32 (shdr, j) bin->shdr[i].sh_addralign = READ64 (shdr, j) bin->shdr[i].sh_entsize = READ64 (shdr, j) #else bin->shdr[i].sh_flags = READ32 (shdr, j) bin->shdr[i].sh_addr = READ32 (shdr, j) bin->shdr[i].sh_offset = READ32 (shdr, j) bin->shdr[i].sh_size = READ32 (shdr, j) bin->shdr[i].sh_link = READ32 (shdr, j) bin->shdr[i].sh_info = READ32 (shdr, j) bin->shdr[i].sh_addralign = READ32 (shdr, j) bin->shdr[i].sh_entsize = READ32 (shdr, j) #endif } #if R_BIN_ELF64 sdb_set (bin->kv, "elf_s_flags_64.cparse", "enum elf_s_flags_64 {SF64_None=0,SF64_Exec=1," "SF64_Alloc=2,SF64_Alloc_Exec=3,SF64_Write=4,SF64_Write_Exec=5," "SF64_Write_Alloc=6,SF64_Write_Alloc_Exec=7};", 0); sdb_set (bin->kv, "elf_shdr.format", "x[4]E[8]Eqqqxxqq name (elf_s_type)type" " (elf_s_flags_64)flags addr offset size link info addralign entsize", 0); #else sdb_set (bin->kv, "elf_s_flags_32.cparse", "enum elf_s_flags_32 {SF32_None=0,SF32_Exec=1," "SF32_Alloc=2,SF32_Alloc_Exec=3,SF32_Write=4,SF32_Write_Exec=5," "SF32_Write_Alloc=6,SF32_Write_Alloc_Exec=7};", 0); sdb_set (bin->kv, "elf_shdr.format", "x[4]E[4]Exxxxxxx name (elf_s_type)type" " (elf_s_flags_32)flags addr offset size link info addralign entsize", 0); #endif return true; // Usage example: // > td `k bin/cur/info/elf_s_type.cparse`; td `k bin/cur/info/elf_s_flags_64.cparse` // > pf `k bin/cur/info/elf_shdr.format` @ `k bin/cur/info/elf_shdr.offset` } static int init_strtab(ELFOBJ *bin) { if (bin->strtab || !bin->shdr) { return false; } if (bin->ehdr.e_shstrndx != SHN_UNDEF && (bin->ehdr.e_shstrndx >= bin->ehdr.e_shnum || (bin->ehdr.e_shstrndx >= SHN_LORESERVE && bin->ehdr.e_shstrndx < SHN_HIRESERVE))) return false; /* sh_size must be lower than UT32_MAX and not equal to zero, to avoid bugs on malloc() */ if (bin->shdr[bin->ehdr.e_shstrndx].sh_size > UT32_MAX) { return false; } if (!bin->shdr[bin->ehdr.e_shstrndx].sh_size) { return false; } bin->shstrtab_section = bin->strtab_section = &bin->shdr[bin->ehdr.e_shstrndx]; bin->shstrtab_size = bin->strtab_section->sh_size; if (bin->shstrtab_size > bin->size) { return false; } if (!(bin->shstrtab = calloc (1, bin->shstrtab_size + 1))) { perror ("malloc"); bin->shstrtab = NULL; return false; } if (bin->shstrtab_section->sh_offset > bin->size) { R_FREE (bin->shstrtab); return false; } if (bin->shstrtab_section->sh_offset + bin->shstrtab_section->sh_size > bin->size) { R_FREE (bin->shstrtab); return false; } if (r_buf_read_at (bin->b, bin->shstrtab_section->sh_offset, (ut8*)bin->shstrtab, bin->shstrtab_section->sh_size + 1) < 1) { bprintf ("Warning: read (shstrtab) at 0x%"PFMT64x"\n", (ut64) bin->shstrtab_section->sh_offset); R_FREE (bin->shstrtab); return false; } bin->shstrtab[bin->shstrtab_section->sh_size] = '\0'; sdb_num_set (bin->kv, "elf_shstrtab.offset", bin->shstrtab_section->sh_offset, 0); sdb_num_set (bin->kv, "elf_shstrtab.size", bin->shstrtab_section->sh_size, 0); return true; } static int init_dynamic_section(struct Elf_(r_bin_elf_obj_t) *bin) { Elf_(Dyn) *dyn = NULL; Elf_(Dyn) d = {0}; Elf_(Addr) strtabaddr = 0; ut64 offset = 0; char *strtab = NULL; size_t relentry = 0, strsize = 0; int entries; int i, j, len, r; ut8 sdyn[sizeof (Elf_(Dyn))] = {0}; ut32 dyn_size = 0; if (!bin || !bin->phdr || !bin->ehdr.e_phnum) { return false; } for (i = 0; i < bin->ehdr.e_phnum ; i++) { if (bin->phdr[i].p_type == PT_DYNAMIC) { dyn_size = bin->phdr[i].p_filesz; break; } } if (i == bin->ehdr.e_phnum) { return false; } if (bin->phdr[i].p_filesz > bin->size) { return false; } if (bin->phdr[i].p_offset > bin->size) { return false; } if (bin->phdr[i].p_offset + sizeof(Elf_(Dyn)) > bin->size) { return false; } for (entries = 0; entries < (dyn_size / sizeof (Elf_(Dyn))); entries++) { j = 0; len = r_buf_read_at (bin->b, bin->phdr[i].p_offset + entries * sizeof (Elf_(Dyn)), sdyn, sizeof (Elf_(Dyn))); if (len < 1) { goto beach; } #if R_BIN_ELF64 d.d_tag = READ64 (sdyn, j) #else d.d_tag = READ32 (sdyn, j) #endif if (d.d_tag == DT_NULL) { break; } } if (entries < 1) { return false; } dyn = (Elf_(Dyn)*)calloc (entries, sizeof (Elf_(Dyn))); if (!dyn) { return false; } if (!UT32_MUL (&dyn_size, entries, sizeof (Elf_(Dyn)))) { goto beach; } if (!dyn_size) { goto beach; } offset = Elf_(r_bin_elf_v2p) (bin, bin->phdr[i].p_vaddr); if (offset > bin->size || offset + dyn_size > bin->size) { goto beach; } for (i = 0; i < entries; i++) { j = 0; r_buf_read_at (bin->b, offset + i * sizeof (Elf_(Dyn)), sdyn, sizeof (Elf_(Dyn))); if (len < 1) { bprintf("Warning: read (dyn)\n"); } #if R_BIN_ELF64 dyn[i].d_tag = READ64 (sdyn, j) dyn[i].d_un.d_ptr = READ64 (sdyn, j) #else dyn[i].d_tag = READ32 (sdyn, j) dyn[i].d_un.d_ptr = READ32 (sdyn, j) #endif switch (dyn[i].d_tag) { case DT_STRTAB: strtabaddr = Elf_(r_bin_elf_v2p) (bin, dyn[i].d_un.d_ptr); break; case DT_STRSZ: strsize = dyn[i].d_un.d_val; break; case DT_PLTREL: bin->is_rela = dyn[i].d_un.d_val; break; case DT_RELAENT: relentry = dyn[i].d_un.d_val; break; default: if ((dyn[i].d_tag >= DT_VERSYM) && (dyn[i].d_tag <= DT_VERNEEDNUM)) { bin->version_info[DT_VERSIONTAGIDX (dyn[i].d_tag)] = dyn[i].d_un.d_val; } break; } } if (!bin->is_rela) { bin->is_rela = sizeof (Elf_(Rela)) == relentry? DT_RELA : DT_REL; } if (!strtabaddr || strtabaddr > bin->size || strsize > ST32_MAX || !strsize || strsize > bin->size) { if (!strtabaddr) { bprintf ("Warning: section.shstrtab not found or invalid\n"); } goto beach; } strtab = (char *)calloc (1, strsize + 1); if (!strtab) { goto beach; } if (strtabaddr + strsize > bin->size) { free (strtab); goto beach; } r = r_buf_read_at (bin->b, strtabaddr, (ut8 *)strtab, strsize); if (r < 1) { free (strtab); goto beach; } bin->dyn_buf = dyn; bin->dyn_entries = entries; bin->strtab = strtab; bin->strtab_size = strsize; r = Elf_(r_bin_elf_has_relro)(bin); switch (r) { case R_ELF_FULL_RELRO: sdb_set (bin->kv, "elf.relro", "full", 0); break; case R_ELF_PART_RELRO: sdb_set (bin->kv, "elf.relro", "partial", 0); break; default: sdb_set (bin->kv, "elf.relro", "no", 0); break; } sdb_num_set (bin->kv, "elf_strtab.offset", strtabaddr, 0); sdb_num_set (bin->kv, "elf_strtab.size", strsize, 0); return true; beach: free (dyn); return false; } static RBinElfSection* get_section_by_name(ELFOBJ *bin, const char *section_name) { int i; if (!bin->g_sections) { return NULL; } for (i = 0; !bin->g_sections[i].last; i++) { if (!strncmp (bin->g_sections[i].name, section_name, ELF_STRING_LENGTH-1)) { return &bin->g_sections[i]; } } return NULL; } static char *get_ver_flags(ut32 flags) { static char buff[32]; buff[0] = 0; if (!flags) { return "none"; } if (flags & VER_FLG_BASE) { strcpy (buff, "BASE "); } if (flags & VER_FLG_WEAK) { if (flags & VER_FLG_BASE) { strcat (buff, "| "); } strcat (buff, "WEAK "); } if (flags & ~(VER_FLG_BASE | VER_FLG_WEAK)) { strcat (buff, "| <unknown>"); } return buff; } static Sdb *store_versioninfo_gnu_versym(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) { int i; const ut64 num_entries = sz / sizeof (Elf_(Versym)); const char *section_name = ""; const char *link_section_name = ""; Elf_(Shdr) *link_shdr = NULL; Sdb *sdb = sdb_new0(); if (!sdb) { return NULL; } if (!bin->version_info[DT_VERSIONTAGIDX (DT_VERSYM)]) { sdb_free (sdb); return NULL; } if (shdr->sh_link > bin->ehdr.e_shnum) { sdb_free (sdb); return NULL; } link_shdr = &bin->shdr[shdr->sh_link]; ut8 *edata = (ut8*) calloc (R_MAX (1, num_entries), sizeof (ut16)); if (!edata) { sdb_free (sdb); return NULL; } ut16 *data = (ut16*) calloc (R_MAX (1, num_entries), sizeof (ut16)); if (!data) { free (edata); sdb_free (sdb); return NULL; } ut64 off = Elf_(r_bin_elf_v2p) (bin, bin->version_info[DT_VERSIONTAGIDX (DT_VERSYM)]); if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) { section_name = &bin->shstrtab[shdr->sh_name]; } if (bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) { link_section_name = &bin->shstrtab[link_shdr->sh_name]; } r_buf_read_at (bin->b, off, edata, sizeof (ut16) * num_entries); sdb_set (sdb, "section_name", section_name, 0); sdb_num_set (sdb, "num_entries", num_entries, 0); sdb_num_set (sdb, "addr", shdr->sh_addr, 0); sdb_num_set (sdb, "offset", shdr->sh_offset, 0); sdb_num_set (sdb, "link", shdr->sh_link, 0); sdb_set (sdb, "link_section_name", link_section_name, 0); for (i = num_entries; i--;) { data[i] = r_read_ble16 (&edata[i * sizeof (ut16)], bin->endian); } R_FREE (edata); for (i = 0; i < num_entries; i += 4) { int j; int check_def; char key[32] = {0}; Sdb *sdb_entry = sdb_new0 (); snprintf (key, sizeof (key), "entry%d", i / 4); sdb_ns_set (sdb, key, sdb_entry); sdb_num_set (sdb_entry, "idx", i, 0); for (j = 0; (j < 4) && (i + j) < num_entries; ++j) { int k; char *tmp_val = NULL; snprintf (key, sizeof (key), "value%d", j); switch (data[i + j]) { case 0: sdb_set (sdb_entry, key, "0 (*local*)", 0); break; case 1: sdb_set (sdb_entry, key, "1 (*global*)", 0); break; default: tmp_val = sdb_fmt (0, "%x ", data[i+j] & 0x7FFF); check_def = true; if (bin->version_info[DT_VERSIONTAGIDX (DT_VERNEED)]) { Elf_(Verneed) vn; ut8 svn[sizeof (Elf_(Verneed))] = {0}; ut64 offset = Elf_(r_bin_elf_v2p) (bin, bin->version_info[DT_VERSIONTAGIDX (DT_VERNEED)]); do { Elf_(Vernaux) vna; ut8 svna[sizeof (Elf_(Vernaux))] = {0}; ut64 a_off; if (offset > bin->size || offset + sizeof (vn) > bin->size) { goto beach; } if (r_buf_read_at (bin->b, offset, svn, sizeof (svn)) < 0) { bprintf ("Warning: Cannot read Verneed for Versym\n"); goto beach; } k = 0; vn.vn_version = READ16 (svn, k) vn.vn_cnt = READ16 (svn, k) vn.vn_file = READ32 (svn, k) vn.vn_aux = READ32 (svn, k) vn.vn_next = READ32 (svn, k) a_off = offset + vn.vn_aux; do { if (a_off > bin->size || a_off + sizeof (vna) > bin->size) { goto beach; } if (r_buf_read_at (bin->b, a_off, svna, sizeof (svna)) < 0) { bprintf ("Warning: Cannot read Vernaux for Versym\n"); goto beach; } k = 0; vna.vna_hash = READ32 (svna, k) vna.vna_flags = READ16 (svna, k) vna.vna_other = READ16 (svna, k) vna.vna_name = READ32 (svna, k) vna.vna_next = READ32 (svna, k) a_off += vna.vna_next; } while (vna.vna_other != data[i + j] && vna.vna_next != 0); if (vna.vna_other == data[i + j]) { if (vna.vna_name > bin->strtab_size) { goto beach; } sdb_set (sdb_entry, key, sdb_fmt (0, "%s(%s)", tmp_val, bin->strtab + vna.vna_name), 0); check_def = false; break; } offset += vn.vn_next; } while (vn.vn_next); } ut64 vinfoaddr = bin->version_info[DT_VERSIONTAGIDX (DT_VERDEF)]; if (check_def && data[i + j] != 0x8001 && vinfoaddr) { Elf_(Verdef) vd; ut8 svd[sizeof (Elf_(Verdef))] = {0}; ut64 offset = Elf_(r_bin_elf_v2p) (bin, vinfoaddr); if (offset > bin->size || offset + sizeof (vd) > bin->size) { goto beach; } do { if (r_buf_read_at (bin->b, offset, svd, sizeof (svd)) < 0) { bprintf ("Warning: Cannot read Verdef for Versym\n"); goto beach; } k = 0; vd.vd_version = READ16 (svd, k) vd.vd_flags = READ16 (svd, k) vd.vd_ndx = READ16 (svd, k) vd.vd_cnt = READ16 (svd, k) vd.vd_hash = READ32 (svd, k) vd.vd_aux = READ32 (svd, k) vd.vd_next = READ32 (svd, k) offset += vd.vd_next; } while (vd.vd_ndx != (data[i + j] & 0x7FFF) && vd.vd_next != 0); if (vd.vd_ndx == (data[i + j] & 0x7FFF)) { Elf_(Verdaux) vda; ut8 svda[sizeof (Elf_(Verdaux))] = {0}; ut64 off_vda = offset - vd.vd_next + vd.vd_aux; if (off_vda > bin->size || off_vda + sizeof (vda) > bin->size) { goto beach; } if (r_buf_read_at (bin->b, off_vda, svda, sizeof (svda)) < 0) { bprintf ("Warning: Cannot read Verdaux for Versym\n"); goto beach; } k = 0; vda.vda_name = READ32 (svda, k) vda.vda_next = READ32 (svda, k) if (vda.vda_name > bin->strtab_size) { goto beach; } const char *name = bin->strtab + vda.vda_name; sdb_set (sdb_entry, key, sdb_fmt (0,"%s(%s%-*s)", tmp_val, name, (int)(12 - strlen (name)),")") , 0); } } } } } beach: free (data); return sdb; } static Sdb *store_versioninfo_gnu_verdef(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) { const char *section_name = ""; const char *link_section_name = ""; char *end = NULL; Elf_(Shdr) *link_shdr = NULL; ut8 dfs[sizeof (Elf_(Verdef))] = {0}; Sdb *sdb; int cnt, i; if (shdr->sh_link > bin->ehdr.e_shnum) { return false; } link_shdr = &bin->shdr[shdr->sh_link]; if (shdr->sh_size < 1) { return false; } Elf_(Verdef) *defs = calloc (shdr->sh_size, sizeof (char)); if (!defs) { return false; } if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) { section_name = &bin->shstrtab[shdr->sh_name]; } if (link_shdr && bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) { link_section_name = &bin->shstrtab[link_shdr->sh_name]; } if (!defs) { bprintf ("Warning: Cannot allocate memory (Check Elf_(Verdef))\n"); return NULL; } sdb = sdb_new0 (); end = (char *)defs + shdr->sh_size; sdb_set (sdb, "section_name", section_name, 0); sdb_num_set (sdb, "entries", shdr->sh_info, 0); sdb_num_set (sdb, "addr", shdr->sh_addr, 0); sdb_num_set (sdb, "offset", shdr->sh_offset, 0); sdb_num_set (sdb, "link", shdr->sh_link, 0); sdb_set (sdb, "link_section_name", link_section_name, 0); for (cnt = 0, i = 0; cnt < shdr->sh_info && ((char *)defs + i < end); ++cnt) { Sdb *sdb_verdef = sdb_new0 (); char *vstart = ((char*)defs) + i; char key[32] = {0}; Elf_(Verdef) *verdef = (Elf_(Verdef)*)vstart; Elf_(Verdaux) aux = {0}; int j = 0; int isum = 0; r_buf_read_at (bin->b, shdr->sh_offset + i, dfs, sizeof (Elf_(Verdef))); verdef->vd_version = READ16 (dfs, j) verdef->vd_flags = READ16 (dfs, j) verdef->vd_ndx = READ16 (dfs, j) verdef->vd_cnt = READ16 (dfs, j) verdef->vd_hash = READ32 (dfs, j) verdef->vd_aux = READ32 (dfs, j) verdef->vd_next = READ32 (dfs, j) vstart += verdef->vd_aux; if (vstart > end || vstart + sizeof (Elf_(Verdaux)) > end) { sdb_free (sdb_verdef); goto out_error; } j = 0; aux.vda_name = READ32 (vstart, j) aux.vda_next = READ32 (vstart, j) isum = i + verdef->vd_aux; if (aux.vda_name > bin->dynstr_size) { sdb_free (sdb_verdef); goto out_error; } sdb_num_set (sdb_verdef, "idx", i, 0); sdb_num_set (sdb_verdef, "vd_version", verdef->vd_version, 0); sdb_num_set (sdb_verdef, "vd_ndx", verdef->vd_ndx, 0); sdb_num_set (sdb_verdef, "vd_cnt", verdef->vd_cnt, 0); sdb_set (sdb_verdef, "vda_name", &bin->dynstr[aux.vda_name], 0); sdb_set (sdb_verdef, "flags", get_ver_flags (verdef->vd_flags), 0); for (j = 1; j < verdef->vd_cnt; ++j) { int k; Sdb *sdb_parent = sdb_new0 (); isum += aux.vda_next; vstart += aux.vda_next; if (vstart > end || vstart + sizeof(Elf_(Verdaux)) > end) { sdb_free (sdb_verdef); sdb_free (sdb_parent); goto out_error; } k = 0; aux.vda_name = READ32 (vstart, k) aux.vda_next = READ32 (vstart, k) if (aux.vda_name > bin->dynstr_size) { sdb_free (sdb_verdef); sdb_free (sdb_parent); goto out_error; } sdb_num_set (sdb_parent, "idx", isum, 0); sdb_num_set (sdb_parent, "parent", j, 0); sdb_set (sdb_parent, "vda_name", &bin->dynstr[aux.vda_name], 0); snprintf (key, sizeof (key), "parent%d", j - 1); sdb_ns_set (sdb_verdef, key, sdb_parent); } snprintf (key, sizeof (key), "verdef%d", cnt); sdb_ns_set (sdb, key, sdb_verdef); if (!verdef->vd_next) { sdb_free (sdb_verdef); goto out_error; } i += verdef->vd_next; } free (defs); return sdb; out_error: free (defs); sdb_free (sdb); return NULL; } static Sdb *store_versioninfo_gnu_verneed(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) { ut8 *end, *need = NULL; const char *section_name = ""; Elf_(Shdr) *link_shdr = NULL; const char *link_section_name = ""; Sdb *sdb_vernaux = NULL; Sdb *sdb_version = NULL; Sdb *sdb = NULL; int i, cnt; if (!bin || !bin->dynstr) { return NULL; } if (shdr->sh_link > bin->ehdr.e_shnum) { return NULL; } if (shdr->sh_size < 1) { return NULL; } sdb = sdb_new0 (); if (!sdb) { return NULL; } link_shdr = &bin->shdr[shdr->sh_link]; if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) { section_name = &bin->shstrtab[shdr->sh_name]; } if (bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) { link_section_name = &bin->shstrtab[link_shdr->sh_name]; } if (!(need = (ut8*) calloc (R_MAX (1, shdr->sh_size), sizeof (ut8)))) { bprintf ("Warning: Cannot allocate memory for Elf_(Verneed)\n"); goto beach; } end = need + shdr->sh_size; sdb_set (sdb, "section_name", section_name, 0); sdb_num_set (sdb, "num_entries", shdr->sh_info, 0); sdb_num_set (sdb, "addr", shdr->sh_addr, 0); sdb_num_set (sdb, "offset", shdr->sh_offset, 0); sdb_num_set (sdb, "link", shdr->sh_link, 0); sdb_set (sdb, "link_section_name", link_section_name, 0); if (shdr->sh_offset > bin->size || shdr->sh_offset + shdr->sh_size > bin->size) { goto beach; } if (shdr->sh_offset + shdr->sh_size < shdr->sh_size) { goto beach; } i = r_buf_read_at (bin->b, shdr->sh_offset, need, shdr->sh_size); if (i < 0) goto beach; //XXX we should use DT_VERNEEDNUM instead of sh_info //TODO https://sourceware.org/ml/binutils/2014-11/msg00353.html for (i = 0, cnt = 0; cnt < shdr->sh_info; ++cnt) { int j, isum; ut8 *vstart = need + i; Elf_(Verneed) vvn = {0}; if (vstart + sizeof (Elf_(Verneed)) > end) { goto beach; } Elf_(Verneed) *entry = &vvn; char key[32] = {0}; sdb_version = sdb_new0 (); if (!sdb_version) { goto beach; } j = 0; vvn.vn_version = READ16 (vstart, j) vvn.vn_cnt = READ16 (vstart, j) vvn.vn_file = READ32 (vstart, j) vvn.vn_aux = READ32 (vstart, j) vvn.vn_next = READ32 (vstart, j) sdb_num_set (sdb_version, "vn_version", entry->vn_version, 0); sdb_num_set (sdb_version, "idx", i, 0); if (entry->vn_file > bin->dynstr_size) { goto beach; } { char *s = r_str_ndup (&bin->dynstr[entry->vn_file], 16); sdb_set (sdb_version, "file_name", s, 0); free (s); } sdb_num_set (sdb_version, "cnt", entry->vn_cnt, 0); vstart += entry->vn_aux; for (j = 0, isum = i + entry->vn_aux; j < entry->vn_cnt && vstart + sizeof (Elf_(Vernaux)) <= end; ++j) { int k; Elf_(Vernaux) * aux = NULL; Elf_(Vernaux) vaux = {0}; sdb_vernaux = sdb_new0 (); if (!sdb_vernaux) { goto beach; } aux = (Elf_(Vernaux)*)&vaux; k = 0; vaux.vna_hash = READ32 (vstart, k) vaux.vna_flags = READ16 (vstart, k) vaux.vna_other = READ16 (vstart, k) vaux.vna_name = READ32 (vstart, k) vaux.vna_next = READ32 (vstart, k) if (aux->vna_name > bin->dynstr_size) { goto beach; } sdb_num_set (sdb_vernaux, "idx", isum, 0); if (aux->vna_name > 0 && aux->vna_name + 8 < bin->dynstr_size) { char name [16]; strncpy (name, &bin->dynstr[aux->vna_name], sizeof (name)-1); name[sizeof(name)-1] = 0; sdb_set (sdb_vernaux, "name", name, 0); } sdb_set (sdb_vernaux, "flags", get_ver_flags (aux->vna_flags), 0); sdb_num_set (sdb_vernaux, "version", aux->vna_other, 0); isum += aux->vna_next; vstart += aux->vna_next; snprintf (key, sizeof (key), "vernaux%d", j); sdb_ns_set (sdb_version, key, sdb_vernaux); } if ((int)entry->vn_next < 0) { bprintf ("Invalid vn_next\n"); break; } i += entry->vn_next; snprintf (key, sizeof (key), "version%d", cnt ); sdb_ns_set (sdb, key, sdb_version); //if entry->vn_next is 0 it iterate infinitely if (!entry->vn_next) { break; } } free (need); return sdb; beach: free (need); sdb_free (sdb_vernaux); sdb_free (sdb_version); sdb_free (sdb); return NULL; } static Sdb *store_versioninfo(ELFOBJ *bin) { Sdb *sdb_versioninfo = NULL; int num_verdef = 0; int num_verneed = 0; int num_versym = 0; int i; if (!bin || !bin->shdr) { return NULL; } if (!(sdb_versioninfo = sdb_new0 ())) { return NULL; } for (i = 0; i < bin->ehdr.e_shnum; i++) { Sdb *sdb = NULL; char key[32] = {0}; int size = bin->shdr[i].sh_size; if (size - (i*sizeof(Elf_(Shdr)) > bin->size)) { size = bin->size - (i*sizeof(Elf_(Shdr))); } int left = size - (i * sizeof (Elf_(Shdr))); left = R_MIN (left, bin->shdr[i].sh_size); if (left < 0) { break; } switch (bin->shdr[i].sh_type) { case SHT_GNU_verdef: sdb = store_versioninfo_gnu_verdef (bin, &bin->shdr[i], left); snprintf (key, sizeof (key), "verdef%d", num_verdef++); sdb_ns_set (sdb_versioninfo, key, sdb); break; case SHT_GNU_verneed: sdb = store_versioninfo_gnu_verneed (bin, &bin->shdr[i], left); snprintf (key, sizeof (key), "verneed%d", num_verneed++); sdb_ns_set (sdb_versioninfo, key, sdb); break; case SHT_GNU_versym: sdb = store_versioninfo_gnu_versym (bin, &bin->shdr[i], left); snprintf (key, sizeof (key), "versym%d", num_versym++); sdb_ns_set (sdb_versioninfo, key, sdb); break; } } return sdb_versioninfo; } static bool init_dynstr(ELFOBJ *bin) { int i, r; const char *section_name = NULL; if (!bin || !bin->shdr) { return false; } if (!bin->shstrtab) { return false; } for (i = 0; i < bin->ehdr.e_shnum; ++i) { if (bin->shdr[i].sh_name > bin->shstrtab_size) { return false; } section_name = &bin->shstrtab[bin->shdr[i].sh_name]; if (bin->shdr[i].sh_type == SHT_STRTAB && !strcmp (section_name, ".dynstr")) { if (!(bin->dynstr = (char*) calloc (bin->shdr[i].sh_size + 1, sizeof (char)))) { bprintf("Warning: Cannot allocate memory for dynamic strings\n"); return false; } if (bin->shdr[i].sh_offset > bin->size) { return false; } if (bin->shdr[i].sh_offset + bin->shdr[i].sh_size > bin->size) { return false; } if (bin->shdr[i].sh_offset + bin->shdr[i].sh_size < bin->shdr[i].sh_size) { return false; } r = r_buf_read_at (bin->b, bin->shdr[i].sh_offset, (ut8*)bin->dynstr, bin->shdr[i].sh_size); if (r < 1) { R_FREE (bin->dynstr); bin->dynstr_size = 0; return false; } bin->dynstr_size = bin->shdr[i].sh_size; return true; } } return false; } static int elf_init(ELFOBJ *bin) { bin->phdr = NULL; bin->shdr = NULL; bin->strtab = NULL; bin->shstrtab = NULL; bin->strtab_size = 0; bin->strtab_section = NULL; bin->dyn_buf = NULL; bin->dynstr = NULL; ZERO_FILL (bin->version_info); bin->g_sections = NULL; bin->g_symbols = NULL; bin->g_imports = NULL; /* bin is not an ELF */ if (!init_ehdr (bin)) { return false; } if (!init_phdr (bin)) { bprintf ("Warning: Cannot initialize program headers\n"); } if (!init_shdr (bin)) { bprintf ("Warning: Cannot initialize section headers\n"); } if (!init_strtab (bin)) { bprintf ("Warning: Cannot initialize strings table\n"); } if (!init_dynstr (bin)) { bprintf ("Warning: Cannot initialize dynamic strings\n"); } bin->baddr = Elf_(r_bin_elf_get_baddr) (bin); if (!init_dynamic_section (bin) && !Elf_(r_bin_elf_get_static)(bin)) bprintf ("Warning: Cannot initialize dynamic section\n"); bin->imports_by_ord_size = 0; bin->imports_by_ord = NULL; bin->symbols_by_ord_size = 0; bin->symbols_by_ord = NULL; bin->g_sections = Elf_(r_bin_elf_get_sections) (bin); bin->boffset = Elf_(r_bin_elf_get_boffset) (bin); sdb_ns_set (bin->kv, "versioninfo", store_versioninfo (bin)); return true; } ut64 Elf_(r_bin_elf_get_section_offset)(ELFOBJ *bin, const char *section_name) { RBinElfSection *section = get_section_by_name (bin, section_name); if (!section) return UT64_MAX; return section->offset; } ut64 Elf_(r_bin_elf_get_section_addr)(ELFOBJ *bin, const char *section_name) { RBinElfSection *section = get_section_by_name (bin, section_name); return section? section->rva: UT64_MAX; } ut64 Elf_(r_bin_elf_get_section_addr_end)(ELFOBJ *bin, const char *section_name) { RBinElfSection *section = get_section_by_name (bin, section_name); return section? section->rva + section->size: UT64_MAX; } #define REL (is_rela ? (void*)rela : (void*)rel) #define REL_BUF is_rela ? (ut8*)(&rela[k]) : (ut8*)(&rel[k]) #define REL_OFFSET is_rela ? rela[k].r_offset : rel[k].r_offset #define REL_TYPE is_rela ? rela[k].r_info : rel[k].r_info static ut64 get_import_addr(ELFOBJ *bin, int sym) { Elf_(Rel) *rel = NULL; Elf_(Rela) *rela = NULL; ut8 rl[sizeof (Elf_(Rel))] = {0}; ut8 rla[sizeof (Elf_(Rela))] = {0}; RBinElfSection *rel_sec = NULL; Elf_(Addr) plt_sym_addr = -1; ut64 got_addr, got_offset; ut64 plt_addr; int j, k, tsize, len, nrel; bool is_rela = false; const char *rel_sect[] = { ".rel.plt", ".rela.plt", ".rel.dyn", ".rela.dyn", NULL }; const char *rela_sect[] = { ".rela.plt", ".rel.plt", ".rela.dyn", ".rel.dyn", NULL }; if ((!bin->shdr || !bin->strtab) && !bin->phdr) { return -1; } if ((got_offset = Elf_(r_bin_elf_get_section_offset) (bin, ".got")) == -1 && (got_offset = Elf_(r_bin_elf_get_section_offset) (bin, ".got.plt")) == -1) { return -1; } if ((got_addr = Elf_(r_bin_elf_get_section_addr) (bin, ".got")) == -1 && (got_addr = Elf_(r_bin_elf_get_section_addr) (bin, ".got.plt")) == -1) { return -1; } if (bin->is_rela == DT_REL) { j = 0; while (!rel_sec && rel_sect[j]) { rel_sec = get_section_by_name (bin, rel_sect[j++]); } tsize = sizeof (Elf_(Rel)); } else if (bin->is_rela == DT_RELA) { j = 0; while (!rel_sec && rela_sect[j]) { rel_sec = get_section_by_name (bin, rela_sect[j++]); } is_rela = true; tsize = sizeof (Elf_(Rela)); } if (!rel_sec) { return -1; } if (rel_sec->size < 1) { return -1; } nrel = (ut32)((int)rel_sec->size / (int)tsize); if (nrel < 1) { return -1; } if (is_rela) { rela = calloc (nrel, tsize); if (!rela) { return -1; } } else { rel = calloc (nrel, tsize); if (!rel) { return -1; } } for (j = k = 0; j < rel_sec->size && k < nrel; j += tsize, k++) { int l = 0; if (rel_sec->offset + j > bin->size) { goto out; } if (rel_sec->offset + j + tsize > bin->size) { goto out; } len = r_buf_read_at ( bin->b, rel_sec->offset + j, is_rela ? rla : rl, is_rela ? sizeof (Elf_ (Rela)) : sizeof (Elf_ (Rel))); if (len < 1) { goto out; } #if R_BIN_ELF64 if (is_rela) { rela[k].r_offset = READ64 (rla, l) rela[k].r_info = READ64 (rla, l) rela[k].r_addend = READ64 (rla, l) } else { rel[k].r_offset = READ64 (rl, l) rel[k].r_info = READ64 (rl, l) } #else if (is_rela) { rela[k].r_offset = READ32 (rla, l) rela[k].r_info = READ32 (rla, l) rela[k].r_addend = READ32 (rla, l) } else { rel[k].r_offset = READ32 (rl, l) rel[k].r_info = READ32 (rl, l) } #endif int reloc_type = ELF_R_TYPE (REL_TYPE); int reloc_sym = ELF_R_SYM (REL_TYPE); if (reloc_sym == sym) { int of = REL_OFFSET; of = of - got_addr + got_offset; switch (bin->ehdr.e_machine) { case EM_PPC: case EM_PPC64: { RBinElfSection *s = get_section_by_name (bin, ".plt"); if (s) { ut8 buf[4]; ut64 base; len = r_buf_read_at (bin->b, s->offset, buf, sizeof (buf)); if (len < 4) { goto out; } base = r_read_be32 (buf); base -= (nrel * 16); base += (k * 16); plt_addr = base; free (REL); return plt_addr; } } break; case EM_SPARC: case EM_SPARCV9: case EM_SPARC32PLUS: plt_addr = Elf_(r_bin_elf_get_section_addr) (bin, ".plt"); if (plt_addr == -1) { free (rela); return -1; } if (reloc_type == R_386_PC16) { plt_addr += k * 12 + 20; // thumb symbol if (plt_addr & 1) { plt_addr--; } free (REL); return plt_addr; } else { bprintf ("Unknown sparc reloc type %d\n", reloc_type); } /* SPARC */ break; case EM_ARM: case EM_AARCH64: plt_addr = Elf_(r_bin_elf_get_section_addr) (bin, ".plt"); if (plt_addr == -1) { free (rela); return UT32_MAX; } switch (reloc_type) { case R_386_8: { plt_addr += k * 12 + 20; // thumb symbol if (plt_addr & 1) { plt_addr--; } free (REL); return plt_addr; } break; case 1026: // arm64 aarch64 plt_sym_addr = plt_addr + k * 16 + 32; goto done; default: bprintf ("Unsupported relocation type for imports %d\n", reloc_type); break; } break; case EM_386: case EM_X86_64: switch (reloc_type) { case 1: // unknown relocs found in voidlinux for x86-64 // break; case R_386_GLOB_DAT: case R_386_JMP_SLOT: { ut8 buf[8]; if (of + sizeof(Elf_(Addr)) < bin->size) { // ONLY FOR X86 if (of > bin->size || of + sizeof (Elf_(Addr)) > bin->size) { goto out; } len = r_buf_read_at (bin->b, of, buf, sizeof (Elf_(Addr))); if (len < -1) { goto out; } plt_sym_addr = sizeof (Elf_(Addr)) == 4 ? r_read_le32 (buf) : r_read_le64 (buf); if (!plt_sym_addr) { //XXX HACK ALERT!!!! full relro?? try to fix it //will there always be .plt.got, what would happen if is .got.plt? RBinElfSection *s = get_section_by_name (bin, ".plt.got"); if (Elf_(r_bin_elf_has_relro)(bin) < R_ELF_PART_RELRO || !s) { goto done; } plt_addr = s->offset; of = of + got_addr - got_offset; while (plt_addr + 2 + 4 < s->offset + s->size) { /*we try to locate the plt entry that correspond with the relocation since got does not point back to .plt. In this case it has the following form ff253a152000 JMP QWORD [RIP + 0x20153A] 6690 NOP ---- ff25ec9f0408 JMP DWORD [reloc.puts_236] plt_addr + 2 to remove jmp opcode and get the imm reading 4 and if RIP (plt_addr + 6) + imm == rel->offset return plt_addr, that will be our sym addr perhaps this hack doesn't work on 32 bits */ len = r_buf_read_at (bin->b, plt_addr + 2, buf, 4); if (len < -1) { goto out; } plt_sym_addr = sizeof (Elf_(Addr)) == 4 ? r_read_le32 (buf) : r_read_le64 (buf); //relative address if ((plt_addr + 6 + Elf_(r_bin_elf_v2p) (bin, plt_sym_addr)) == of) { plt_sym_addr = plt_addr; goto done; } else if (plt_sym_addr == of) { plt_sym_addr = plt_addr; goto done; } plt_addr += 8; } } else { plt_sym_addr -= 6; } goto done; } break; } default: bprintf ("Unsupported relocation type for imports %d\n", reloc_type); free (REL); return of; break; } break; case 8: // MIPS32 BIG ENDIAN relocs { RBinElfSection *s = get_section_by_name (bin, ".rela.plt"); if (s) { ut8 buf[1024]; const ut8 *base; plt_addr = s->rva + s->size; len = r_buf_read_at (bin->b, s->offset + s->size, buf, sizeof (buf)); if (len != sizeof (buf)) { // oops } base = r_mem_mem_aligned (buf, sizeof (buf), (const ut8*)"\x3c\x0f\x00", 3, 4); if (base) { plt_addr += (int)(size_t)(base - buf); } else { plt_addr += 108 + 8; // HARDCODED HACK } plt_addr += k * 16; free (REL); return plt_addr; } } break; default: bprintf ("Unsupported relocs type %d for arch %d\n", reloc_type, bin->ehdr.e_machine); break; } } } done: free (REL); return plt_sym_addr; out: free (REL); return -1; } int Elf_(r_bin_elf_has_nx)(ELFOBJ *bin) { int i; if (bin && bin->phdr) { for (i = 0; i < bin->ehdr.e_phnum; i++) { if (bin->phdr[i].p_type == PT_GNU_STACK) { return (!(bin->phdr[i].p_flags & 1))? 1: 0; } } } return 0; } int Elf_(r_bin_elf_has_relro)(ELFOBJ *bin) { int i; bool haveBindNow = false; bool haveGnuRelro = false; if (bin && bin->dyn_buf) { for (i = 0; i < bin->dyn_entries; i++) { switch (bin->dyn_buf[i].d_tag) { case DT_BIND_NOW: haveBindNow = true; break; case DT_FLAGS: for (i++; i < bin->dyn_entries ; i++) { ut32 dTag = bin->dyn_buf[i].d_tag; if (!dTag) { break; } switch (dTag) { case DT_FLAGS_1: if (bin->dyn_buf[i].d_un.d_val & DF_1_NOW) { haveBindNow = true; break; } } } break; } } } if (bin && bin->phdr) { for (i = 0; i < bin->ehdr.e_phnum; i++) { if (bin->phdr[i].p_type == PT_GNU_RELRO) { haveGnuRelro = true; break; } } } if (haveGnuRelro) { if (haveBindNow) { return R_ELF_FULL_RELRO; } return R_ELF_PART_RELRO; } return R_ELF_NO_RELRO; } /* To compute the base address, one determines the memory address associated with the lowest p_vaddr value for a PT_LOAD segment. One then obtains the base address by truncating the memory address to the nearest multiple of the maximum page size */ ut64 Elf_(r_bin_elf_get_baddr)(ELFOBJ *bin) { int i; ut64 tmp, base = UT64_MAX; if (!bin) { return 0; } if (bin->phdr) { for (i = 0; i < bin->ehdr.e_phnum; i++) { if (bin->phdr[i].p_type == PT_LOAD) { tmp = (ut64)bin->phdr[i].p_vaddr & ELF_PAGE_MASK; tmp = tmp - (tmp % (1 << ELF_PAGE_SIZE)); if (tmp < base) { base = tmp; } } } } if (base == UT64_MAX && bin->ehdr.e_type == ET_REL) { //we return our own base address for ET_REL type //we act as a loader for ELF return 0x08000000; } return base == UT64_MAX ? 0 : base; } ut64 Elf_(r_bin_elf_get_boffset)(ELFOBJ *bin) { int i; ut64 tmp, base = UT64_MAX; if (bin && bin->phdr) { for (i = 0; i < bin->ehdr.e_phnum; i++) { if (bin->phdr[i].p_type == PT_LOAD) { tmp = (ut64)bin->phdr[i].p_offset & ELF_PAGE_MASK; tmp = tmp - (tmp % (1 << ELF_PAGE_SIZE)); if (tmp < base) { base = tmp; } } } } return base == UT64_MAX ? 0 : base; } ut64 Elf_(r_bin_elf_get_init_offset)(ELFOBJ *bin) { ut64 entry = Elf_(r_bin_elf_get_entry_offset) (bin); ut8 buf[512]; if (!bin) { return 0LL; } if (r_buf_read_at (bin->b, entry + 16, buf, sizeof (buf)) < 1) { bprintf ("Warning: read (init_offset)\n"); return 0; } if (buf[0] == 0x68) { // push // x86 only ut64 addr; memmove (buf, buf+1, 4); addr = (ut64)r_read_le32 (buf); return Elf_(r_bin_elf_v2p) (bin, addr); } return 0; } ut64 Elf_(r_bin_elf_get_fini_offset)(ELFOBJ *bin) { ut64 entry = Elf_(r_bin_elf_get_entry_offset) (bin); ut8 buf[512]; if (!bin) { return 0LL; } if (r_buf_read_at (bin->b, entry+11, buf, sizeof (buf)) == -1) { bprintf ("Warning: read (get_fini)\n"); return 0; } if (*buf == 0x68) { // push // x86/32 only ut64 addr; memmove (buf, buf+1, 4); addr = (ut64)r_read_le32 (buf); return Elf_(r_bin_elf_v2p) (bin, addr); } return 0; } ut64 Elf_(r_bin_elf_get_entry_offset)(ELFOBJ *bin) { ut64 entry; if (!bin) { return 0LL; } entry = bin->ehdr.e_entry; if (!entry) { entry = Elf_(r_bin_elf_get_section_offset)(bin, ".init.text"); if (entry != UT64_MAX) { return entry; } entry = Elf_(r_bin_elf_get_section_offset)(bin, ".text"); if (entry != UT64_MAX) { return entry; } entry = Elf_(r_bin_elf_get_section_offset)(bin, ".init"); if (entry != UT64_MAX) { return entry; } if (entry == UT64_MAX) { return 0; } } return Elf_(r_bin_elf_v2p) (bin, entry); } static ut64 getmainsymbol(ELFOBJ *bin) { struct r_bin_elf_symbol_t *symbol; int i; if (!(symbol = Elf_(r_bin_elf_get_symbols) (bin))) { return UT64_MAX; } for (i = 0; !symbol[i].last; i++) { if (!strcmp (symbol[i].name, "main")) { ut64 paddr = symbol[i].offset; return Elf_(r_bin_elf_p2v) (bin, paddr); } } return UT64_MAX; } ut64 Elf_(r_bin_elf_get_main_offset)(ELFOBJ *bin) { ut64 entry = Elf_(r_bin_elf_get_entry_offset) (bin); ut8 buf[512]; if (!bin) { return 0LL; } if (entry > bin->size || (entry + sizeof (buf)) > bin->size) { return 0; } if (r_buf_read_at (bin->b, entry, buf, sizeof (buf)) < 1) { bprintf ("Warning: read (main)\n"); return 0; } // ARM64 if (buf[0x18+3] == 0x58 && buf[0x2f] == 0x00) { ut32 entry_vaddr = Elf_(r_bin_elf_p2v) (bin, entry); ut32 main_addr = r_read_le32 (&buf[0x30]); if ((main_addr >> 16) == (entry_vaddr >> 16)) { return Elf_(r_bin_elf_v2p) (bin, main_addr); } } // TODO: Use arch to identify arch before memcmp's // ARM ut64 text = Elf_(r_bin_elf_get_section_offset)(bin, ".text"); ut64 text_end = text + bin->size; // ARM-Thumb-Linux if (entry & 1 && !memcmp (buf, "\xf0\x00\x0b\x4f\xf0\x00", 6)) { ut32 * ptr = (ut32*)(buf+40-1); if (*ptr &1) { return Elf_(r_bin_elf_v2p) (bin, *ptr -1); } } if (!memcmp (buf, "\x00\xb0\xa0\xe3\x00\xe0\xa0\xe3", 8)) { // endian stuff here ut32 *addr = (ut32*)(buf+0x34); /* 0x00012000 00b0a0e3 mov fp, 0 0x00012004 00e0a0e3 mov lr, 0 */ if (*addr > text && *addr < (text_end)) { return Elf_(r_bin_elf_v2p) (bin, *addr); } } // MIPS /* get .got, calculate offset of main symbol */ if (!memcmp (buf, "\x21\x00\xe0\x03\x01\x00\x11\x04", 8)) { /* assuming the startup code looks like got = gp-0x7ff0 got[index__libc_start_main] ( got[index_main] ); looking for the instruction generating the first argument to find main lw a0, offset(gp) */ ut64 got_offset; if ((got_offset = Elf_(r_bin_elf_get_section_offset) (bin, ".got")) != -1 || (got_offset = Elf_(r_bin_elf_get_section_offset) (bin, ".got.plt")) != -1) { const ut64 gp = got_offset + 0x7ff0; unsigned i; for (i = 0; i < sizeof(buf) / sizeof(buf[0]); i += 4) { const ut32 instr = r_read_le32 (&buf[i]); if ((instr & 0xffff0000) == 0x8f840000) { // lw a0, offset(gp) const short delta = instr & 0x0000ffff; r_buf_read_at (bin->b, /* got_entry_offset = */ gp + delta, buf, 4); return Elf_(r_bin_elf_v2p) (bin, r_read_le32 (&buf[0])); } } } return 0; } // ARM if (!memcmp (buf, "\x24\xc0\x9f\xe5\x00\xb0\xa0\xe3", 8)) { ut64 addr = r_read_le32 (&buf[48]); return Elf_(r_bin_elf_v2p) (bin, addr); } // X86-CGC if (buf[0] == 0xe8 && !memcmp (buf + 5, "\x50\xe8\x00\x00\x00\x00\xb8\x01\x00\x00\x00\x53", 12)) { size_t SIZEOF_CALL = 5; ut64 rel_addr = (ut64)((int)(buf[1] + (buf[2] << 8) + (buf[3] << 16) + (buf[4] << 24))); ut64 addr = Elf_(r_bin_elf_p2v)(bin, entry + SIZEOF_CALL); addr += rel_addr; return Elf_(r_bin_elf_v2p) (bin, addr); } // X86-PIE if (buf[0x00] == 0x48 && buf[0x1e] == 0x8d && buf[0x11] == 0xe8) { ut32 *pmain = (ut32*)(buf + 0x30); ut64 vmain = Elf_(r_bin_elf_p2v) (bin, (ut64)*pmain); ut64 ventry = Elf_(r_bin_elf_p2v) (bin, entry); if (vmain >> 16 == ventry >> 16) { return (ut64)vmain; } } // X86-PIE if (buf[0x1d] == 0x48 && buf[0x1e] == 0x8b) { if (!memcmp (buf, "\x31\xed\x49\x89", 4)) {// linux ut64 maddr, baddr; ut8 n32s[sizeof (ut32)] = {0}; maddr = entry + 0x24 + r_read_le32 (buf + 0x20); if (r_buf_read_at (bin->b, maddr, n32s, sizeof (ut32)) == -1) { bprintf ("Warning: read (maddr) 2\n"); return 0; } maddr = (ut64)r_read_le32 (&n32s[0]); baddr = (bin->ehdr.e_entry >> 16) << 16; if (bin->phdr) { baddr = Elf_(r_bin_elf_get_baddr) (bin); } maddr += baddr; return maddr; } } // X86-NONPIE #if R_BIN_ELF64 if (!memcmp (buf, "\x49\x89\xd9", 3) && buf[156] == 0xe8) { // openbsd return r_read_le32 (&buf[157]) + entry + 156 + 5; } if (!memcmp (buf+29, "\x48\xc7\xc7", 3)) { // linux ut64 addr = (ut64)r_read_le32 (&buf[29 + 3]); return Elf_(r_bin_elf_v2p) (bin, addr); } #else if (buf[23] == '\x68') { ut64 addr = (ut64)r_read_le32 (&buf[23 + 1]); return Elf_(r_bin_elf_v2p) (bin, addr); } #endif /* linux64 pie main -- probably buggy in some cases */ if (buf[29] == 0x48 && buf[30] == 0x8d) { // lea rdi, qword [rip-0x21c4] ut8 *p = buf + 32; st32 maindelta = (st32)r_read_le32 (p); ut64 vmain = (ut64)(entry + 29 + maindelta) + 7; ut64 ventry = Elf_(r_bin_elf_p2v) (bin, entry); if (vmain>>16 == ventry>>16) { return (ut64)vmain; } } /* find sym.main if possible */ { ut64 m = getmainsymbol (bin); if (m != UT64_MAX) return m; } return UT64_MAX; } int Elf_(r_bin_elf_get_stripped)(ELFOBJ *bin) { int i; if (!bin->shdr) { return false; } for (i = 0; i < bin->ehdr.e_shnum; i++) { if (bin->shdr[i].sh_type == SHT_SYMTAB) { return false; } } return true; } char *Elf_(r_bin_elf_intrp)(ELFOBJ *bin) { int i; if (!bin || !bin->phdr) { return NULL; } for (i = 0; i < bin->ehdr.e_phnum; i++) { if (bin->phdr[i].p_type == PT_INTERP) { char *str = NULL; ut64 addr = bin->phdr[i].p_offset; int sz = bin->phdr[i].p_memsz; sdb_num_set (bin->kv, "elf_header.intrp_addr", addr, 0); sdb_num_set (bin->kv, "elf_header.intrp_size", sz, 0); if (sz < 1) { return NULL; } str = malloc (sz + 1); if (!str) { return NULL; } if (r_buf_read_at (bin->b, addr, (ut8*)str, sz) < 1) { bprintf ("Warning: read (main)\n"); return 0; } str[sz] = 0; sdb_set (bin->kv, "elf_header.intrp", str, 0); return str; } } return NULL; } int Elf_(r_bin_elf_get_static)(ELFOBJ *bin) { int i; if (!bin->phdr) { return false; } for (i = 0; i < bin->ehdr.e_phnum; i++) { if (bin->phdr[i].p_type == PT_INTERP) { return false; } } return true; } char* Elf_(r_bin_elf_get_data_encoding)(ELFOBJ *bin) { switch (bin->ehdr.e_ident[EI_DATA]) { case ELFDATANONE: return strdup ("none"); case ELFDATA2LSB: return strdup ("2's complement, little endian"); case ELFDATA2MSB: return strdup ("2's complement, big endian"); default: return r_str_newf ("<unknown: %x>", bin->ehdr.e_ident[EI_DATA]); } } int Elf_(r_bin_elf_has_va)(ELFOBJ *bin) { return true; } char* Elf_(r_bin_elf_get_arch)(ELFOBJ *bin) { switch (bin->ehdr.e_machine) { case EM_ARC: case EM_ARC_A5: return strdup ("arc"); case EM_AVR: return strdup ("avr"); case EM_CRIS: return strdup ("cris"); case EM_68K: return strdup ("m68k"); case EM_MIPS: case EM_MIPS_RS3_LE: case EM_MIPS_X: return strdup ("mips"); case EM_MCST_ELBRUS: return strdup ("elbrus"); case EM_TRICORE: return strdup ("tricore"); case EM_ARM: case EM_AARCH64: return strdup ("arm"); case EM_HEXAGON: return strdup ("hexagon"); case EM_BLACKFIN: return strdup ("blackfin"); case EM_SPARC: case EM_SPARC32PLUS: case EM_SPARCV9: return strdup ("sparc"); case EM_PPC: case EM_PPC64: return strdup ("ppc"); case EM_PARISC: return strdup ("hppa"); case EM_PROPELLER: return strdup ("propeller"); case EM_MICROBLAZE: return strdup ("microblaze.gnu"); case EM_RISCV: return strdup ("riscv"); case EM_VAX: return strdup ("vax"); case EM_XTENSA: return strdup ("xtensa"); case EM_LANAI: return strdup ("lanai"); case EM_VIDEOCORE3: case EM_VIDEOCORE4: return strdup ("vc4"); case EM_SH: return strdup ("sh"); case EM_V850: return strdup ("v850"); case EM_IA_64: return strdup("ia64"); default: return strdup ("x86"); } } char* Elf_(r_bin_elf_get_machine_name)(ELFOBJ *bin) { switch (bin->ehdr.e_machine) { case EM_NONE: return strdup ("No machine"); case EM_M32: return strdup ("AT&T WE 32100"); case EM_SPARC: return strdup ("SUN SPARC"); case EM_386: return strdup ("Intel 80386"); case EM_68K: return strdup ("Motorola m68k family"); case EM_88K: return strdup ("Motorola m88k family"); case EM_860: return strdup ("Intel 80860"); case EM_MIPS: return strdup ("MIPS R3000"); case EM_S370: return strdup ("IBM System/370"); case EM_MIPS_RS3_LE: return strdup ("MIPS R3000 little-endian"); case EM_PARISC: return strdup ("HPPA"); case EM_VPP500: return strdup ("Fujitsu VPP500"); case EM_SPARC32PLUS: return strdup ("Sun's \"v8plus\""); case EM_960: return strdup ("Intel 80960"); case EM_PPC: return strdup ("PowerPC"); case EM_PPC64: return strdup ("PowerPC 64-bit"); case EM_S390: return strdup ("IBM S390"); case EM_V800: return strdup ("NEC V800 series"); case EM_FR20: return strdup ("Fujitsu FR20"); case EM_RH32: return strdup ("TRW RH-32"); case EM_RCE: return strdup ("Motorola RCE"); case EM_ARM: return strdup ("ARM"); case EM_BLACKFIN: return strdup ("Analog Devices Blackfin"); case EM_FAKE_ALPHA: return strdup ("Digital Alpha"); case EM_SH: return strdup ("Hitachi SH"); case EM_SPARCV9: return strdup ("SPARC v9 64-bit"); case EM_TRICORE: return strdup ("Siemens Tricore"); case EM_ARC: return strdup ("Argonaut RISC Core"); case EM_H8_300: return strdup ("Hitachi H8/300"); case EM_H8_300H: return strdup ("Hitachi H8/300H"); case EM_H8S: return strdup ("Hitachi H8S"); case EM_H8_500: return strdup ("Hitachi H8/500"); case EM_IA_64: return strdup ("Intel Merced"); case EM_MIPS_X: return strdup ("Stanford MIPS-X"); case EM_COLDFIRE: return strdup ("Motorola Coldfire"); case EM_68HC12: return strdup ("Motorola M68HC12"); case EM_MMA: return strdup ("Fujitsu MMA Multimedia Accelerator"); case EM_PCP: return strdup ("Siemens PCP"); case EM_NCPU: return strdup ("Sony nCPU embeeded RISC"); case EM_NDR1: return strdup ("Denso NDR1 microprocessor"); case EM_STARCORE: return strdup ("Motorola Start*Core processor"); case EM_ME16: return strdup ("Toyota ME16 processor"); case EM_ST100: return strdup ("STMicroelectronic ST100 processor"); case EM_TINYJ: return strdup ("Advanced Logic Corp. Tinyj emb.fam"); case EM_X86_64: return strdup ("AMD x86-64 architecture"); case EM_LANAI: return strdup ("32bit LANAI architecture"); case EM_PDSP: return strdup ("Sony DSP Processor"); case EM_FX66: return strdup ("Siemens FX66 microcontroller"); case EM_ST9PLUS: return strdup ("STMicroelectronics ST9+ 8/16 mc"); case EM_ST7: return strdup ("STmicroelectronics ST7 8 bit mc"); case EM_68HC16: return strdup ("Motorola MC68HC16 microcontroller"); case EM_68HC11: return strdup ("Motorola MC68HC11 microcontroller"); case EM_68HC08: return strdup ("Motorola MC68HC08 microcontroller"); case EM_68HC05: return strdup ("Motorola MC68HC05 microcontroller"); case EM_SVX: return strdup ("Silicon Graphics SVx"); case EM_ST19: return strdup ("STMicroelectronics ST19 8 bit mc"); case EM_VAX: return strdup ("Digital VAX"); case EM_CRIS: return strdup ("Axis Communications 32-bit embedded processor"); case EM_JAVELIN: return strdup ("Infineon Technologies 32-bit embedded processor"); case EM_FIREPATH: return strdup ("Element 14 64-bit DSP Processor"); case EM_ZSP: return strdup ("LSI Logic 16-bit DSP Processor"); case EM_MMIX: return strdup ("Donald Knuth's educational 64-bit processor"); case EM_HUANY: return strdup ("Harvard University machine-independent object files"); case EM_PRISM: return strdup ("SiTera Prism"); case EM_AVR: return strdup ("Atmel AVR 8-bit microcontroller"); case EM_FR30: return strdup ("Fujitsu FR30"); case EM_D10V: return strdup ("Mitsubishi D10V"); case EM_D30V: return strdup ("Mitsubishi D30V"); case EM_V850: return strdup ("NEC v850"); case EM_M32R: return strdup ("Mitsubishi M32R"); case EM_MN10300: return strdup ("Matsushita MN10300"); case EM_MN10200: return strdup ("Matsushita MN10200"); case EM_PJ: return strdup ("picoJava"); case EM_OPENRISC: return strdup ("OpenRISC 32-bit embedded processor"); case EM_ARC_A5: return strdup ("ARC Cores Tangent-A5"); case EM_XTENSA: return strdup ("Tensilica Xtensa Architecture"); case EM_AARCH64: return strdup ("ARM aarch64"); case EM_PROPELLER: return strdup ("Parallax Propeller"); case EM_MICROBLAZE: return strdup ("Xilinx MicroBlaze"); case EM_RISCV: return strdup ("RISC V"); case EM_VIDEOCORE3: return strdup ("VideoCore III"); case EM_VIDEOCORE4: return strdup ("VideoCore IV"); default: return r_str_newf ("<unknown>: 0x%x", bin->ehdr.e_machine); } } char* Elf_(r_bin_elf_get_file_type)(ELFOBJ *bin) { ut32 e_type; if (!bin) { return NULL; } e_type = (ut32)bin->ehdr.e_type; // cast to avoid warn in iphone-gcc, must be ut16 switch (e_type) { case ET_NONE: return strdup ("NONE (None)"); case ET_REL: return strdup ("REL (Relocatable file)"); case ET_EXEC: return strdup ("EXEC (Executable file)"); case ET_DYN: return strdup ("DYN (Shared object file)"); case ET_CORE: return strdup ("CORE (Core file)"); } if ((e_type >= ET_LOPROC) && (e_type <= ET_HIPROC)) { return r_str_newf ("Processor Specific: %x", e_type); } if ((e_type >= ET_LOOS) && (e_type <= ET_HIOS)) { return r_str_newf ("OS Specific: %x", e_type); } return r_str_newf ("<unknown>: %x", e_type); } char* Elf_(r_bin_elf_get_elf_class)(ELFOBJ *bin) { switch (bin->ehdr.e_ident[EI_CLASS]) { case ELFCLASSNONE: return strdup ("none"); case ELFCLASS32: return strdup ("ELF32"); case ELFCLASS64: return strdup ("ELF64"); default: return r_str_newf ("<unknown: %x>", bin->ehdr.e_ident[EI_CLASS]); } } int Elf_(r_bin_elf_get_bits)(ELFOBJ *bin) { /* Hack for ARCompact */ if (bin->ehdr.e_machine == EM_ARC_A5) { return 16; } /* Hack for Ps2 */ if (bin->phdr && bin->ehdr.e_machine == EM_MIPS) { const ut32 mipsType = bin->ehdr.e_flags & EF_MIPS_ARCH; if (bin->ehdr.e_type == ET_EXEC) { int i; bool haveInterp = false; for (i = 0; i < bin->ehdr.e_phnum; i++) { if (bin->phdr[i].p_type == PT_INTERP) { haveInterp = true; } } if (!haveInterp && mipsType == EF_MIPS_ARCH_3) { // Playstation2 Hack return 64; } } // TODO: show this specific asm.cpu somewhere in bininfo (mips1, mips2, mips3, mips32r2, ...) switch (mipsType) { case EF_MIPS_ARCH_1: case EF_MIPS_ARCH_2: case EF_MIPS_ARCH_3: case EF_MIPS_ARCH_4: case EF_MIPS_ARCH_5: case EF_MIPS_ARCH_32: return 32; case EF_MIPS_ARCH_64: return 64; case EF_MIPS_ARCH_32R2: return 32; case EF_MIPS_ARCH_64R2: return 64; break; } return 32; } /* Hack for Thumb */ if (bin->ehdr.e_machine == EM_ARM) { if (bin->ehdr.e_type != ET_EXEC) { struct r_bin_elf_symbol_t *symbol; if ((symbol = Elf_(r_bin_elf_get_symbols) (bin))) { int i = 0; for (i = 0; !symbol[i].last; i++) { ut64 paddr = symbol[i].offset; if (paddr & 1) { return 16; } } } } { ut64 entry = Elf_(r_bin_elf_get_entry_offset) (bin); if (entry & 1) { return 16; } } } switch (bin->ehdr.e_ident[EI_CLASS]) { case ELFCLASS32: return 32; case ELFCLASS64: return 64; case ELFCLASSNONE: default: return 32; // defaults } } static inline int noodle(ELFOBJ *bin, const char *s) { const ut8 *p = bin->b->buf; if (bin->b->length > 64) { p += bin->b->length - 64; } else { return 0; } return r_mem_mem (p, 64, (const ut8 *)s, strlen (s)) != NULL; } static inline int needle(ELFOBJ *bin, const char *s) { if (bin->shstrtab) { ut32 len = bin->shstrtab_size; if (len > 4096) { len = 4096; // avoid slow loading .. can be buggy? } return r_mem_mem ((const ut8*)bin->shstrtab, len, (const ut8*)s, strlen (s)) != NULL; } return 0; } // TODO: must return const char * all those strings must be const char os[LINUX] or so char* Elf_(r_bin_elf_get_osabi_name)(ELFOBJ *bin) { switch (bin->ehdr.e_ident[EI_OSABI]) { case ELFOSABI_LINUX: return strdup("linux"); case ELFOSABI_SOLARIS: return strdup("solaris"); case ELFOSABI_FREEBSD: return strdup("freebsd"); case ELFOSABI_HPUX: return strdup("hpux"); } /* Hack to identify OS */ if (needle (bin, "openbsd")) return strdup ("openbsd"); if (needle (bin, "netbsd")) return strdup ("netbsd"); if (needle (bin, "freebsd")) return strdup ("freebsd"); if (noodle (bin, "BEOS:APP_VERSION")) return strdup ("beos"); if (needle (bin, "GNU")) return strdup ("linux"); return strdup ("linux"); } ut8 *Elf_(r_bin_elf_grab_regstate)(ELFOBJ *bin, int *len) { if (bin->phdr) { int i; int num = bin->ehdr.e_phnum; for (i = 0; i < num; i++) { if (bin->phdr[i].p_type != PT_NOTE) { continue; } int bits = Elf_(r_bin_elf_get_bits)(bin); int regdelta = (bits == 64)? 0x84: 0x40; // x64 vs x32 int regsize = 160; // for x86-64 ut8 *buf = malloc (regsize); if (r_buf_read_at (bin->b, bin->phdr[i].p_offset + regdelta, buf, regsize) != regsize) { free (buf); bprintf ("Cannot read register state from CORE file\n"); return NULL; } if (len) { *len = regsize; } return buf; } } bprintf ("Cannot find NOTE section\n"); return NULL; } int Elf_(r_bin_elf_is_big_endian)(ELFOBJ *bin) { return (bin->ehdr.e_ident[EI_DATA] == ELFDATA2MSB); } /* XXX Init dt_strtab? */ char *Elf_(r_bin_elf_get_rpath)(ELFOBJ *bin) { char *ret = NULL; int j; if (!bin || !bin->phdr || !bin->dyn_buf || !bin->strtab) { return NULL; } for (j = 0; j< bin->dyn_entries; j++) { if (bin->dyn_buf[j].d_tag == DT_RPATH || bin->dyn_buf[j].d_tag == DT_RUNPATH) { if (!(ret = calloc (1, ELF_STRING_LENGTH))) { perror ("malloc (rpath)"); return NULL; } if (bin->dyn_buf[j].d_un.d_val > bin->strtab_size) { free (ret); return NULL; } strncpy (ret, bin->strtab + bin->dyn_buf[j].d_un.d_val, ELF_STRING_LENGTH); ret[ELF_STRING_LENGTH - 1] = '\0'; break; } } return ret; } static size_t get_relocs_num(ELFOBJ *bin) { size_t i, size, ret = 0; /* we need to be careful here, in malformed files the section size might * not be a multiple of a Rel/Rela size; round up so we allocate enough * space. */ #define NUMENTRIES_ROUNDUP(sectionsize, entrysize) (((sectionsize)+(entrysize)-1)/(entrysize)) if (!bin->g_sections) { return 0; } size = bin->is_rela == DT_REL ? sizeof (Elf_(Rel)) : sizeof (Elf_(Rela)); for (i = 0; !bin->g_sections[i].last; i++) { if (!strncmp (bin->g_sections[i].name, ".rela.", strlen (".rela."))) { if (!bin->is_rela) { size = sizeof (Elf_(Rela)); } ret += NUMENTRIES_ROUNDUP (bin->g_sections[i].size, size); } else if (!strncmp (bin->g_sections[i].name, ".rel.", strlen (".rel."))){ if (!bin->is_rela) { size = sizeof (Elf_(Rel)); } ret += NUMENTRIES_ROUNDUP (bin->g_sections[i].size, size); } } return ret; #undef NUMENTRIES_ROUNDUP } static int read_reloc(ELFOBJ *bin, RBinElfReloc *r, int is_rela, ut64 offset) { ut8 *buf = bin->b->buf; int j = 0; if (offset + sizeof (Elf_ (Rela)) > bin->size || offset + sizeof (Elf_(Rela)) < offset) { return -1; } if (is_rela == DT_RELA) { Elf_(Rela) rela; #if R_BIN_ELF64 rela.r_offset = READ64 (buf + offset, j) rela.r_info = READ64 (buf + offset, j) rela.r_addend = READ64 (buf + offset, j) #else rela.r_offset = READ32 (buf + offset, j) rela.r_info = READ32 (buf + offset, j) rela.r_addend = READ32 (buf + offset, j) #endif r->is_rela = is_rela; r->offset = rela.r_offset; r->type = ELF_R_TYPE (rela.r_info); r->sym = ELF_R_SYM (rela.r_info); r->last = 0; r->addend = rela.r_addend; return sizeof (Elf_(Rela)); } else { Elf_(Rel) rel; #if R_BIN_ELF64 rel.r_offset = READ64 (buf + offset, j) rel.r_info = READ64 (buf + offset, j) #else rel.r_offset = READ32 (buf + offset, j) rel.r_info = READ32 (buf + offset, j) #endif r->is_rela = is_rela; r->offset = rel.r_offset; r->type = ELF_R_TYPE (rel.r_info); r->sym = ELF_R_SYM (rel.r_info); r->last = 0; return sizeof (Elf_(Rel)); } } RBinElfReloc* Elf_(r_bin_elf_get_relocs)(ELFOBJ *bin) { int res, rel, rela, i, j; size_t reloc_num = 0; RBinElfReloc *ret = NULL; if (!bin || !bin->g_sections) { return NULL; } reloc_num = get_relocs_num (bin); if (!reloc_num) { return NULL; } bin->reloc_num = reloc_num; ret = (RBinElfReloc*)calloc ((size_t)reloc_num + 1, sizeof(RBinElfReloc)); if (!ret) { return NULL; } #if DEAD_CODE ut64 section_text_offset = Elf_(r_bin_elf_get_section_offset) (bin, ".text"); if (section_text_offset == -1) { section_text_offset = 0; } #endif for (i = 0, rel = 0; !bin->g_sections[i].last && rel < reloc_num ; i++) { bool is_rela = 0 == strncmp (bin->g_sections[i].name, ".rela.", strlen (".rela.")); bool is_rel = 0 == strncmp (bin->g_sections[i].name, ".rel.", strlen (".rel.")); if (!is_rela && !is_rel) { continue; } for (j = 0; j < bin->g_sections[i].size; j += res) { if (bin->g_sections[i].size > bin->size) { break; } if (bin->g_sections[i].offset > bin->size) { break; } if (rel >= reloc_num) { bprintf ("Internal error: ELF relocation buffer too small," "please file a bug report."); break; } if (!bin->is_rela) { rela = is_rela? DT_RELA : DT_REL; } else { rela = bin->is_rela; } res = read_reloc (bin, &ret[rel], rela, bin->g_sections[i].offset + j); if (j + res > bin->g_sections[i].size) { bprintf ("Warning: malformed file, relocation entry #%u is partially beyond the end of section %u.\n", rel, i); } if (bin->ehdr.e_type == ET_REL) { if (bin->g_sections[i].info < bin->ehdr.e_shnum && bin->shdr) { ret[rel].rva = bin->shdr[bin->g_sections[i].info].sh_offset + ret[rel].offset; ret[rel].rva = Elf_(r_bin_elf_p2v) (bin, ret[rel].rva); } else { ret[rel].rva = ret[rel].offset; } } else { ret[rel].rva = ret[rel].offset; ret[rel].offset = Elf_(r_bin_elf_v2p) (bin, ret[rel].offset); } ret[rel].last = 0; if (res < 0) { break; } rel++; } } ret[reloc_num].last = 1; return ret; } RBinElfLib* Elf_(r_bin_elf_get_libs)(ELFOBJ *bin) { RBinElfLib *ret = NULL; int j, k; if (!bin || !bin->phdr || !bin->dyn_buf || !bin->strtab || *(bin->strtab+1) == '0') { return NULL; } for (j = 0, k = 0; j < bin->dyn_entries; j++) if (bin->dyn_buf[j].d_tag == DT_NEEDED) { RBinElfLib *r = realloc (ret, (k + 1) * sizeof (RBinElfLib)); if (!r) { perror ("realloc (libs)"); free (ret); return NULL; } ret = r; if (bin->dyn_buf[j].d_un.d_val > bin->strtab_size) { free (ret); return NULL; } strncpy (ret[k].name, bin->strtab + bin->dyn_buf[j].d_un.d_val, ELF_STRING_LENGTH); ret[k].name[ELF_STRING_LENGTH - 1] = '\0'; ret[k].last = 0; if (ret[k].name[0]) { k++; } } RBinElfLib *r = realloc (ret, (k + 1) * sizeof (RBinElfLib)); if (!r) { perror ("realloc (libs)"); free (ret); return NULL; } ret = r; ret[k].last = 1; return ret; } static RBinElfSection* get_sections_from_phdr(ELFOBJ *bin) { RBinElfSection *ret; int i, num_sections = 0; ut64 reldyn = 0, relava = 0, pltgotva = 0, relva = 0; ut64 reldynsz = 0, relasz = 0, pltgotsz = 0; if (!bin || !bin->phdr || !bin->ehdr.e_phnum) return NULL; for (i = 0; i < bin->dyn_entries; i++) { switch (bin->dyn_buf[i].d_tag) { case DT_REL: reldyn = bin->dyn_buf[i].d_un.d_ptr; num_sections++; break; case DT_RELA: relva = bin->dyn_buf[i].d_un.d_ptr; num_sections++; break; case DT_RELSZ: reldynsz = bin->dyn_buf[i].d_un.d_val; break; case DT_RELASZ: relasz = bin->dyn_buf[i].d_un.d_val; break; case DT_PLTGOT: pltgotva = bin->dyn_buf[i].d_un.d_ptr; num_sections++; break; case DT_PLTRELSZ: pltgotsz = bin->dyn_buf[i].d_un.d_val; break; case DT_JMPREL: relava = bin->dyn_buf[i].d_un.d_ptr; num_sections++; break; default: break; } } ret = calloc (num_sections + 1, sizeof(RBinElfSection)); if (!ret) { return NULL; } i = 0; if (reldyn) { ret[i].offset = Elf_(r_bin_elf_v2p) (bin, reldyn); ret[i].rva = reldyn; ret[i].size = reldynsz; strcpy (ret[i].name, ".rel.dyn"); ret[i].last = 0; i++; } if (relava) { ret[i].offset = Elf_(r_bin_elf_v2p) (bin, relava); ret[i].rva = relava; ret[i].size = pltgotsz; strcpy (ret[i].name, ".rela.plt"); ret[i].last = 0; i++; } if (relva) { ret[i].offset = Elf_(r_bin_elf_v2p) (bin, relva); ret[i].rva = relva; ret[i].size = relasz; strcpy (ret[i].name, ".rel.plt"); ret[i].last = 0; i++; } if (pltgotva) { ret[i].offset = Elf_(r_bin_elf_v2p) (bin, pltgotva); ret[i].rva = pltgotva; ret[i].size = pltgotsz; strcpy (ret[i].name, ".got.plt"); ret[i].last = 0; i++; } ret[i].last = 1; return ret; } RBinElfSection* Elf_(r_bin_elf_get_sections)(ELFOBJ *bin) { RBinElfSection *ret = NULL; char unknown_s[20], invalid_s[20]; int i, nidx, unknown_c=0, invalid_c=0; if (!bin) { return NULL; } if (bin->g_sections) { return bin->g_sections; } if (!bin->shdr) { //we don't give up search in phdr section return get_sections_from_phdr (bin); } if (!(ret = calloc ((bin->ehdr.e_shnum + 1), sizeof (RBinElfSection)))) { return NULL; } for (i = 0; i < bin->ehdr.e_shnum; i++) { ret[i].offset = bin->shdr[i].sh_offset; ret[i].size = bin->shdr[i].sh_size; ret[i].align = bin->shdr[i].sh_addralign; ret[i].flags = bin->shdr[i].sh_flags; ret[i].link = bin->shdr[i].sh_link; ret[i].info = bin->shdr[i].sh_info; ret[i].type = bin->shdr[i].sh_type; if (bin->ehdr.e_type == ET_REL) { ret[i].rva = bin->baddr + bin->shdr[i].sh_offset; } else { ret[i].rva = bin->shdr[i].sh_addr; } nidx = bin->shdr[i].sh_name; #define SHNAME (int)bin->shdr[i].sh_name #define SHNLEN ELF_STRING_LENGTH - 4 #define SHSIZE (int)bin->shstrtab_size if (nidx < 0 || !bin->shstrtab_section || !bin->shstrtab_size || nidx > bin->shstrtab_size) { snprintf (invalid_s, sizeof (invalid_s) - 4, "invalid%d", invalid_c); strncpy (ret[i].name, invalid_s, SHNLEN); invalid_c++; } else { if (bin->shstrtab && (SHNAME > 0) && (SHNAME < SHSIZE)) { strncpy (ret[i].name, &bin->shstrtab[SHNAME], SHNLEN); } else { if (bin->shdr[i].sh_type == SHT_NULL) { //to follow the same behaviour as readelf strncpy (ret[i].name, "", sizeof (ret[i].name) - 4); } else { snprintf (unknown_s, sizeof (unknown_s)-4, "unknown%d", unknown_c); strncpy (ret[i].name, unknown_s, sizeof (ret[i].name)-4); unknown_c++; } } } ret[i].name[ELF_STRING_LENGTH-2] = '\0'; ret[i].last = 0; } ret[i].last = 1; return ret; } static void fill_symbol_bind_and_type (struct r_bin_elf_symbol_t *ret, Elf_(Sym) *sym) { #define s_bind(x) ret->bind = x #define s_type(x) ret->type = x switch (ELF_ST_BIND(sym->st_info)) { case STB_LOCAL: s_bind ("LOCAL"); break; case STB_GLOBAL: s_bind ("GLOBAL"); break; case STB_WEAK: s_bind ("WEAK"); break; case STB_NUM: s_bind ("NUM"); break; case STB_LOOS: s_bind ("LOOS"); break; case STB_HIOS: s_bind ("HIOS"); break; case STB_LOPROC: s_bind ("LOPROC"); break; case STB_HIPROC: s_bind ("HIPROC"); break; default: s_bind ("UNKNOWN"); } switch (ELF_ST_TYPE (sym->st_info)) { case STT_NOTYPE: s_type ("NOTYPE"); break; case STT_OBJECT: s_type ("OBJECT"); break; case STT_FUNC: s_type ("FUNC"); break; case STT_SECTION: s_type ("SECTION"); break; case STT_FILE: s_type ("FILE"); break; case STT_COMMON: s_type ("COMMON"); break; case STT_TLS: s_type ("TLS"); break; case STT_NUM: s_type ("NUM"); break; case STT_LOOS: s_type ("LOOS"); break; case STT_HIOS: s_type ("HIOS"); break; case STT_LOPROC: s_type ("LOPROC"); break; case STT_HIPROC: s_type ("HIPROC"); break; default: s_type ("UNKNOWN"); } } static RBinElfSymbol* get_symbols_from_phdr(ELFOBJ *bin, int type) { Elf_(Sym) *sym = NULL; Elf_(Addr) addr_sym_table = 0; ut8 s[sizeof (Elf_(Sym))] = {0}; RBinElfSymbol *ret = NULL; int i, j, r, tsize, nsym, ret_ctr; ut64 toffset = 0, tmp_offset; ut32 size, sym_size = 0; if (!bin || !bin->phdr || !bin->ehdr.e_phnum) { return NULL; } for (j = 0; j < bin->dyn_entries; j++) { switch (bin->dyn_buf[j].d_tag) { case (DT_SYMTAB): addr_sym_table = Elf_(r_bin_elf_v2p) (bin, bin->dyn_buf[j].d_un.d_ptr); break; case (DT_SYMENT): sym_size = bin->dyn_buf[j].d_un.d_val; break; default: break; } } if (!addr_sym_table) { return NULL; } if (!sym_size) { return NULL; } //since ELF doesn't specify the symbol table size we may read until the end of the buffer nsym = (bin->size - addr_sym_table) / sym_size; if (!UT32_MUL (&size, nsym, sizeof (Elf_ (Sym)))) { goto beach; } if (size < 1) { goto beach; } if (addr_sym_table > bin->size || addr_sym_table + size > bin->size) { goto beach; } if (nsym < 1) { return NULL; } // we reserve room for 4096 and grow as needed. size_t capacity1 = 4096; size_t capacity2 = 4096; sym = (Elf_(Sym)*) calloc (capacity1, sym_size); ret = (RBinElfSymbol *) calloc (capacity2, sizeof (struct r_bin_elf_symbol_t)); if (!sym || !ret) { goto beach; } for (i = 1, ret_ctr = 0; i < nsym; i++) { if (i >= capacity1) { // maybe grow // You take what you want, but you eat what you take. Elf_(Sym)* temp_sym = (Elf_(Sym)*) realloc(sym, (capacity1 * GROWTH_FACTOR) * sym_size); if (!temp_sym) { goto beach; } sym = temp_sym; capacity1 *= GROWTH_FACTOR; } if (ret_ctr >= capacity2) { // maybe grow RBinElfSymbol *temp_ret = realloc (ret, capacity2 * GROWTH_FACTOR * sizeof (struct r_bin_elf_symbol_t)); if (!temp_ret) { goto beach; } ret = temp_ret; capacity2 *= GROWTH_FACTOR; } // read in one entry r = r_buf_read_at (bin->b, addr_sym_table + i * sizeof (Elf_ (Sym)), s, sizeof (Elf_ (Sym))); if (r < 1) { goto beach; } int j = 0; #if R_BIN_ELF64 sym[i].st_name = READ32 (s, j); sym[i].st_info = READ8 (s, j); sym[i].st_other = READ8 (s, j); sym[i].st_shndx = READ16 (s, j); sym[i].st_value = READ64 (s, j); sym[i].st_size = READ64 (s, j); #else sym[i].st_name = READ32 (s, j); sym[i].st_value = READ32 (s, j); sym[i].st_size = READ32 (s, j); sym[i].st_info = READ8 (s, j); sym[i].st_other = READ8 (s, j); sym[i].st_shndx = READ16 (s, j); #endif // zero symbol is always empty // Examine entry and maybe store if (type == R_BIN_ELF_IMPORTS && sym[i].st_shndx == STN_UNDEF) { if (sym[i].st_value) { toffset = sym[i].st_value; } else if ((toffset = get_import_addr (bin, i)) == -1){ toffset = 0; } tsize = 16; } else if (type == R_BIN_ELF_SYMBOLS && sym[i].st_shndx != STN_UNDEF && ELF_ST_TYPE (sym[i].st_info) != STT_SECTION && ELF_ST_TYPE (sym[i].st_info) != STT_FILE) { tsize = sym[i].st_size; toffset = (ut64) sym[i].st_value; } else { continue; } tmp_offset = Elf_(r_bin_elf_v2p) (bin, toffset); if (tmp_offset > bin->size) { goto done; } if (sym[i].st_name + 2 > bin->strtab_size) { // Since we are reading beyond the symbol table what's happening // is that some entry is trying to dereference the strtab beyond its capacity // is not a symbol so is the end goto done; } ret[ret_ctr].offset = tmp_offset; ret[ret_ctr].size = tsize; { int rest = ELF_STRING_LENGTH - 1; int st_name = sym[i].st_name; int maxsize = R_MIN (bin->size, bin->strtab_size); if (st_name < 0 || st_name >= maxsize) { ret[ret_ctr].name[0] = 0; } else { const int len = __strnlen (bin->strtab + st_name, rest); memcpy (ret[ret_ctr].name, &bin->strtab[st_name], len); } } ret[ret_ctr].ordinal = i; ret[ret_ctr].in_shdr = false; ret[ret_ctr].name[ELF_STRING_LENGTH - 2] = '\0'; fill_symbol_bind_and_type (&ret[ret_ctr], &sym[i]); ret[ret_ctr].last = 0; ret_ctr++; } done: ret[ret_ctr].last = 1; // Size everything down to only what is used { nsym = i > 0 ? i : 1; Elf_ (Sym) * temp_sym = (Elf_ (Sym)*) realloc (sym, (nsym * GROWTH_FACTOR) * sym_size); if (!temp_sym) { goto beach; } sym = temp_sym; } { ret_ctr = ret_ctr > 0 ? ret_ctr : 1; RBinElfSymbol *p = (RBinElfSymbol *) realloc (ret, (ret_ctr + 1) * sizeof (RBinElfSymbol)); if (!p) { goto beach; } ret = p; } if (type == R_BIN_ELF_IMPORTS && !bin->imports_by_ord_size) { bin->imports_by_ord_size = ret_ctr + 1; if (ret_ctr > 0) { bin->imports_by_ord = (RBinImport * *) calloc (ret_ctr + 1, sizeof (RBinImport*)); } else { bin->imports_by_ord = NULL; } } else if (type == R_BIN_ELF_SYMBOLS && !bin->symbols_by_ord_size && ret_ctr) { bin->symbols_by_ord_size = ret_ctr + 1; if (ret_ctr > 0) { bin->symbols_by_ord = (RBinSymbol * *) calloc (ret_ctr + 1, sizeof (RBinSymbol*)); }else { bin->symbols_by_ord = NULL; } } free (sym); return ret; beach: free (sym); free (ret); return NULL; } static RBinElfSymbol *Elf_(r_bin_elf_get_phdr_symbols)(ELFOBJ *bin) { if (!bin) { return NULL; } if (bin->phdr_symbols) { return bin->phdr_symbols; } bin->phdr_symbols = get_symbols_from_phdr (bin, R_BIN_ELF_SYMBOLS); return bin->phdr_symbols; } static RBinElfSymbol *Elf_(r_bin_elf_get_phdr_imports)(ELFOBJ *bin) { if (!bin) { return NULL; } if (bin->phdr_imports) { return bin->phdr_imports; } bin->phdr_imports = get_symbols_from_phdr (bin, R_BIN_ELF_IMPORTS); return bin->phdr_imports; } static int Elf_(fix_symbols)(ELFOBJ *bin, int nsym, int type, RBinElfSymbol **sym) { int count = 0; RBinElfSymbol *ret = *sym; RBinElfSymbol *phdr_symbols = (type == R_BIN_ELF_SYMBOLS) ? Elf_(r_bin_elf_get_phdr_symbols) (bin) : Elf_(r_bin_elf_get_phdr_imports) (bin); RBinElfSymbol *tmp, *p; if (phdr_symbols) { RBinElfSymbol *d = ret; while (!d->last) { /* find match in phdr */ p = phdr_symbols; while (!p->last) { if (p->offset && d->offset == p->offset) { p->in_shdr = true; if (*p->name && strcmp (d->name, p->name)) { strcpy (d->name, p->name); } } p++; } d++; } p = phdr_symbols; while (!p->last) { if (!p->in_shdr) { count++; } p++; } /*Take those symbols that are not present in the shdr but yes in phdr*/ /*This should only should happen with fucked up binaries*/ if (count > 0) { /*what happens if a shdr says it has only one symbol? we should look anyway into phdr*/ tmp = (RBinElfSymbol*)realloc (ret, (nsym + count + 1) * sizeof (RBinElfSymbol)); if (!tmp) { return -1; } ret = tmp; ret[nsym--].last = 0; p = phdr_symbols; while (!p->last) { if (!p->in_shdr) { memcpy (&ret[++nsym], p, sizeof (RBinElfSymbol)); } p++; } ret[nsym + 1].last = 1; } *sym = ret; return nsym + 1; } return nsym; } static RBinElfSymbol* Elf_(_r_bin_elf_get_symbols_imports)(ELFOBJ *bin, int type) { ut32 shdr_size; int tsize, nsym, ret_ctr = 0, i, j, r, k, newsize; ut64 toffset; ut32 size = 0; RBinElfSymbol *ret = NULL; Elf_(Shdr) *strtab_section = NULL; Elf_(Sym) *sym = NULL; ut8 s[sizeof (Elf_(Sym))] = { 0 }; char *strtab = NULL; if (!bin || !bin->shdr || !bin->ehdr.e_shnum || bin->ehdr.e_shnum == 0xffff) { return (type == R_BIN_ELF_SYMBOLS) ? Elf_(r_bin_elf_get_phdr_symbols) (bin) : Elf_(r_bin_elf_get_phdr_imports) (bin); } if (!UT32_MUL (&shdr_size, bin->ehdr.e_shnum, sizeof (Elf_(Shdr)))) { return false; } if (shdr_size + 8 > bin->size) { return false; } for (i = 0; i < bin->ehdr.e_shnum; i++) { if ((type == R_BIN_ELF_IMPORTS && bin->shdr[i].sh_type == (bin->ehdr.e_type == ET_REL ? SHT_SYMTAB : SHT_DYNSYM)) || (type == R_BIN_ELF_SYMBOLS && bin->shdr[i].sh_type == (Elf_(r_bin_elf_get_stripped) (bin) ? SHT_DYNSYM : SHT_SYMTAB))) { if (bin->shdr[i].sh_link < 1) { /* oops. fix out of range pointers */ continue; } // hack to avoid asan cry if ((bin->shdr[i].sh_link * sizeof(Elf_(Shdr))) >= shdr_size) { /* oops. fix out of range pointers */ continue; } strtab_section = &bin->shdr[bin->shdr[i].sh_link]; if (strtab_section->sh_size > ST32_MAX || strtab_section->sh_size+8 > bin->size) { bprintf ("size (syms strtab)"); free (ret); free (strtab); return NULL; } if (!strtab) { if (!(strtab = (char *)calloc (1, 8 + strtab_section->sh_size))) { bprintf ("malloc (syms strtab)"); goto beach; } if (strtab_section->sh_offset > bin->size || strtab_section->sh_offset + strtab_section->sh_size > bin->size) { goto beach; } if (r_buf_read_at (bin->b, strtab_section->sh_offset, (ut8*)strtab, strtab_section->sh_size) == -1) { bprintf ("Warning: read (syms strtab)\n"); goto beach; } } newsize = 1 + bin->shdr[i].sh_size; if (newsize < 0 || newsize > bin->size) { bprintf ("invalid shdr %d size\n", i); goto beach; } nsym = (int)(bin->shdr[i].sh_size / sizeof (Elf_(Sym))); if (nsym < 0) { goto beach; } if (!(sym = (Elf_(Sym) *)calloc (nsym, sizeof (Elf_(Sym))))) { bprintf ("calloc (syms)"); goto beach; } if (!UT32_MUL (&size, nsym, sizeof (Elf_(Sym)))) { goto beach; } if (size < 1 || size > bin->size) { goto beach; } if (bin->shdr[i].sh_offset > bin->size) { goto beach; } if (bin->shdr[i].sh_offset + size > bin->size) { goto beach; } for (j = 0; j < nsym; j++) { int k = 0; r = r_buf_read_at (bin->b, bin->shdr[i].sh_offset + j * sizeof (Elf_(Sym)), s, sizeof (Elf_(Sym))); if (r < 1) { bprintf ("Warning: read (sym)\n"); goto beach; } #if R_BIN_ELF64 sym[j].st_name = READ32 (s, k) sym[j].st_info = READ8 (s, k) sym[j].st_other = READ8 (s, k) sym[j].st_shndx = READ16 (s, k) sym[j].st_value = READ64 (s, k) sym[j].st_size = READ64 (s, k) #else sym[j].st_name = READ32 (s, k) sym[j].st_value = READ32 (s, k) sym[j].st_size = READ32 (s, k) sym[j].st_info = READ8 (s, k) sym[j].st_other = READ8 (s, k) sym[j].st_shndx = READ16 (s, k) #endif } free (ret); ret = calloc (nsym, sizeof (RBinElfSymbol)); if (!ret) { bprintf ("Cannot allocate %d symbols\n", nsym); goto beach; } for (k = 1, ret_ctr = 0; k < nsym; k++) { if (type == R_BIN_ELF_IMPORTS && sym[k].st_shndx == STN_UNDEF) { if (sym[k].st_value) { toffset = sym[k].st_value; } else if ((toffset = get_import_addr (bin, k)) == -1){ toffset = 0; } tsize = 16; } else if (type == R_BIN_ELF_SYMBOLS && sym[k].st_shndx != STN_UNDEF && ELF_ST_TYPE (sym[k].st_info) != STT_SECTION && ELF_ST_TYPE (sym[k].st_info) != STT_FILE) { //int idx = sym[k].st_shndx; tsize = sym[k].st_size; toffset = (ut64)sym[k].st_value; } else { continue; } if (bin->ehdr.e_type == ET_REL) { if (sym[k].st_shndx < bin->ehdr.e_shnum) ret[ret_ctr].offset = sym[k].st_value + bin->shdr[sym[k].st_shndx].sh_offset; } else { ret[ret_ctr].offset = Elf_(r_bin_elf_v2p) (bin, toffset); } ret[ret_ctr].size = tsize; if (sym[k].st_name + 2 > strtab_section->sh_size) { bprintf ("Warning: index out of strtab range\n"); goto beach; } { int rest = ELF_STRING_LENGTH - 1; int st_name = sym[k].st_name; int maxsize = R_MIN (bin->b->length, strtab_section->sh_size); if (st_name < 0 || st_name >= maxsize) { ret[ret_ctr].name[0] = 0; } else { const size_t len = __strnlen (strtab + sym[k].st_name, rest); memcpy (ret[ret_ctr].name, &strtab[sym[k].st_name], len); } } ret[ret_ctr].ordinal = k; ret[ret_ctr].name[ELF_STRING_LENGTH - 2] = '\0'; fill_symbol_bind_and_type (&ret[ret_ctr], &sym[k]); ret[ret_ctr].last = 0; ret_ctr++; } ret[ret_ctr].last = 1; // ugly dirty hack :D R_FREE (strtab); R_FREE (sym); } } if (!ret) { return (type == R_BIN_ELF_SYMBOLS) ? Elf_(r_bin_elf_get_phdr_symbols) (bin) : Elf_(r_bin_elf_get_phdr_imports) (bin); } int max = -1; RBinElfSymbol *aux = NULL; nsym = Elf_(fix_symbols) (bin, ret_ctr, type, &ret); if (nsym == -1) { goto beach; } aux = ret; while (!aux->last) { if ((int)aux->ordinal > max) { max = aux->ordinal; } aux++; } nsym = max; if (type == R_BIN_ELF_IMPORTS) { R_FREE (bin->imports_by_ord); bin->imports_by_ord_size = nsym + 1; bin->imports_by_ord = (RBinImport**)calloc (R_MAX (1, nsym + 1), sizeof (RBinImport*)); } else if (type == R_BIN_ELF_SYMBOLS) { R_FREE (bin->symbols_by_ord); bin->symbols_by_ord_size = nsym + 1; bin->symbols_by_ord = (RBinSymbol**)calloc (R_MAX (1, nsym + 1), sizeof (RBinSymbol*)); } return ret; beach: free (ret); free (sym); free (strtab); return NULL; } RBinElfSymbol *Elf_(r_bin_elf_get_symbols)(ELFOBJ *bin) { if (!bin->g_symbols) { bin->g_symbols = Elf_(_r_bin_elf_get_symbols_imports) (bin, R_BIN_ELF_SYMBOLS); } return bin->g_symbols; } RBinElfSymbol *Elf_(r_bin_elf_get_imports)(ELFOBJ *bin) { if (!bin->g_imports) { bin->g_imports = Elf_(_r_bin_elf_get_symbols_imports) (bin, R_BIN_ELF_IMPORTS); } return bin->g_imports; } RBinElfField* Elf_(r_bin_elf_get_fields)(ELFOBJ *bin) { RBinElfField *ret = NULL; int i = 0, j; if (!bin || !(ret = calloc ((bin->ehdr.e_phnum + 3 + 1), sizeof (RBinElfField)))) { return NULL; } strncpy (ret[i].name, "ehdr", ELF_STRING_LENGTH); ret[i].offset = 0; ret[i++].last = 0; strncpy (ret[i].name, "shoff", ELF_STRING_LENGTH); ret[i].offset = bin->ehdr.e_shoff; ret[i++].last = 0; strncpy (ret[i].name, "phoff", ELF_STRING_LENGTH); ret[i].offset = bin->ehdr.e_phoff; ret[i++].last = 0; for (j = 0; bin->phdr && j < bin->ehdr.e_phnum; i++, j++) { snprintf (ret[i].name, ELF_STRING_LENGTH, "phdr_%i", j); ret[i].offset = bin->phdr[j].p_offset; ret[i].last = 0; } ret[i].last = 1; return ret; } void* Elf_(r_bin_elf_free)(ELFOBJ* bin) { int i; if (!bin) { return NULL; } free (bin->phdr); free (bin->shdr); free (bin->strtab); free (bin->dyn_buf); free (bin->shstrtab); free (bin->dynstr); //free (bin->strtab_section); if (bin->imports_by_ord) { for (i = 0; i<bin->imports_by_ord_size; i++) { free (bin->imports_by_ord[i]); } free (bin->imports_by_ord); } if (bin->symbols_by_ord) { for (i = 0; i<bin->symbols_by_ord_size; i++) { free (bin->symbols_by_ord[i]); } free (bin->symbols_by_ord); } r_buf_free (bin->b); if (bin->g_symbols != bin->phdr_symbols) { R_FREE (bin->phdr_symbols); } if (bin->g_imports != bin->phdr_imports) { R_FREE (bin->phdr_imports); } R_FREE (bin->g_sections); R_FREE (bin->g_symbols); R_FREE (bin->g_imports); free (bin); return NULL; } ELFOBJ* Elf_(r_bin_elf_new)(const char* file, bool verbose) { ut8 *buf; int size; ELFOBJ *bin = R_NEW0 (ELFOBJ); if (!bin) { return NULL; } memset (bin, 0, sizeof (ELFOBJ)); bin->file = file; if (!(buf = (ut8*)r_file_slurp (file, &size))) { return Elf_(r_bin_elf_free) (bin); } bin->size = size; bin->verbose = verbose; bin->b = r_buf_new (); if (!r_buf_set_bytes (bin->b, buf, bin->size)) { free (buf); return Elf_(r_bin_elf_free) (bin); } if (!elf_init (bin)) { free (buf); return Elf_(r_bin_elf_free) (bin); } free (buf); return bin; } ELFOBJ* Elf_(r_bin_elf_new_buf)(RBuffer *buf, bool verbose) { ELFOBJ *bin = R_NEW0 (ELFOBJ); bin->kv = sdb_new0 (); bin->b = r_buf_new (); bin->size = (ut32)buf->length; bin->verbose = verbose; if (!r_buf_set_bytes (bin->b, buf->buf, buf->length)) { return Elf_(r_bin_elf_free) (bin); } if (!elf_init (bin)) { return Elf_(r_bin_elf_free) (bin); } return bin; } static int is_in_pphdr (Elf_(Phdr) *p, ut64 addr) { return addr >= p->p_offset && addr < p->p_offset + p->p_memsz; } static int is_in_vphdr (Elf_(Phdr) *p, ut64 addr) { return addr >= p->p_vaddr && addr < p->p_vaddr + p->p_memsz; } /* converts a physical address to the virtual address, looking * at the program headers in the binary bin */ ut64 Elf_(r_bin_elf_p2v) (ELFOBJ *bin, ut64 paddr) { int i; if (!bin) return 0; if (!bin->phdr) { if (bin->ehdr.e_type == ET_REL) { return bin->baddr + paddr; } return paddr; } for (i = 0; i < bin->ehdr.e_phnum; ++i) { Elf_(Phdr) *p = &bin->phdr[i]; if (!p) { break; } if (p->p_type == PT_LOAD && is_in_pphdr (p, paddr)) { if (!p->p_vaddr && !p->p_offset) { continue; } return p->p_vaddr + paddr - p->p_offset; } } return paddr; } /* converts a virtual address to the relative physical address, looking * at the program headers in the binary bin */ ut64 Elf_(r_bin_elf_v2p) (ELFOBJ *bin, ut64 vaddr) { int i; if (!bin) { return 0; } if (!bin->phdr) { if (bin->ehdr.e_type == ET_REL) { return vaddr - bin->baddr; } return vaddr; } for (i = 0; i < bin->ehdr.e_phnum; ++i) { Elf_(Phdr) *p = &bin->phdr[i]; if (!p) { break; } if (p->p_type == PT_LOAD && is_in_vphdr (p, vaddr)) { if (!p->p_offset && !p->p_vaddr) { continue; } return p->p_offset + vaddr - p->p_vaddr; } } return vaddr; }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_2863_0
crossvul-cpp_data_good_3305_0
/* * XDR support for nfsd/protocol version 3. * * Copyright (C) 1995, 1996, 1997 Olaf Kirch <okir@monad.swb.de> * * 2003-08-09 Jamie Lokier: Use htonl() for nanoseconds, not htons()! */ #include <linux/namei.h> #include <linux/sunrpc/svc_xprt.h> #include "xdr3.h" #include "auth.h" #include "netns.h" #include "vfs.h" #define NFSDDBG_FACILITY NFSDDBG_XDR /* * Mapping of S_IF* types to NFS file types */ static u32 nfs3_ftypes[] = { NF3NON, NF3FIFO, NF3CHR, NF3BAD, NF3DIR, NF3BAD, NF3BLK, NF3BAD, NF3REG, NF3BAD, NF3LNK, NF3BAD, NF3SOCK, NF3BAD, NF3LNK, NF3BAD, }; /* * XDR functions for basic NFS types */ static __be32 * encode_time3(__be32 *p, struct timespec *time) { *p++ = htonl((u32) time->tv_sec); *p++ = htonl(time->tv_nsec); return p; } static __be32 * decode_time3(__be32 *p, struct timespec *time) { time->tv_sec = ntohl(*p++); time->tv_nsec = ntohl(*p++); return p; } static __be32 * decode_fh(__be32 *p, struct svc_fh *fhp) { unsigned int size; fh_init(fhp, NFS3_FHSIZE); size = ntohl(*p++); if (size > NFS3_FHSIZE) return NULL; memcpy(&fhp->fh_handle.fh_base, p, size); fhp->fh_handle.fh_size = size; return p + XDR_QUADLEN(size); } /* Helper function for NFSv3 ACL code */ __be32 *nfs3svc_decode_fh(__be32 *p, struct svc_fh *fhp) { return decode_fh(p, fhp); } static __be32 * encode_fh(__be32 *p, struct svc_fh *fhp) { unsigned int size = fhp->fh_handle.fh_size; *p++ = htonl(size); if (size) p[XDR_QUADLEN(size)-1]=0; memcpy(p, &fhp->fh_handle.fh_base, size); return p + XDR_QUADLEN(size); } /* * Decode a file name and make sure that the path contains * no slashes or null bytes. */ static __be32 * decode_filename(__be32 *p, char **namp, unsigned int *lenp) { char *name; unsigned int i; if ((p = xdr_decode_string_inplace(p, namp, lenp, NFS3_MAXNAMLEN)) != NULL) { for (i = 0, name = *namp; i < *lenp; i++, name++) { if (*name == '\0' || *name == '/') return NULL; } } return p; } static __be32 * decode_sattr3(__be32 *p, struct iattr *iap) { u32 tmp; iap->ia_valid = 0; if (*p++) { iap->ia_valid |= ATTR_MODE; iap->ia_mode = ntohl(*p++); } if (*p++) { iap->ia_uid = make_kuid(&init_user_ns, ntohl(*p++)); if (uid_valid(iap->ia_uid)) iap->ia_valid |= ATTR_UID; } if (*p++) { iap->ia_gid = make_kgid(&init_user_ns, ntohl(*p++)); if (gid_valid(iap->ia_gid)) iap->ia_valid |= ATTR_GID; } if (*p++) { u64 newsize; iap->ia_valid |= ATTR_SIZE; p = xdr_decode_hyper(p, &newsize); iap->ia_size = min_t(u64, newsize, NFS_OFFSET_MAX); } if ((tmp = ntohl(*p++)) == 1) { /* set to server time */ iap->ia_valid |= ATTR_ATIME; } else if (tmp == 2) { /* set to client time */ iap->ia_valid |= ATTR_ATIME | ATTR_ATIME_SET; iap->ia_atime.tv_sec = ntohl(*p++); iap->ia_atime.tv_nsec = ntohl(*p++); } if ((tmp = ntohl(*p++)) == 1) { /* set to server time */ iap->ia_valid |= ATTR_MTIME; } else if (tmp == 2) { /* set to client time */ iap->ia_valid |= ATTR_MTIME | ATTR_MTIME_SET; iap->ia_mtime.tv_sec = ntohl(*p++); iap->ia_mtime.tv_nsec = ntohl(*p++); } return p; } static __be32 *encode_fsid(__be32 *p, struct svc_fh *fhp) { u64 f; switch(fsid_source(fhp)) { default: case FSIDSOURCE_DEV: p = xdr_encode_hyper(p, (u64)huge_encode_dev (fhp->fh_dentry->d_sb->s_dev)); break; case FSIDSOURCE_FSID: p = xdr_encode_hyper(p, (u64) fhp->fh_export->ex_fsid); break; case FSIDSOURCE_UUID: f = ((u64*)fhp->fh_export->ex_uuid)[0]; f ^= ((u64*)fhp->fh_export->ex_uuid)[1]; p = xdr_encode_hyper(p, f); break; } return p; } static __be32 * encode_fattr3(struct svc_rqst *rqstp, __be32 *p, struct svc_fh *fhp, struct kstat *stat) { *p++ = htonl(nfs3_ftypes[(stat->mode & S_IFMT) >> 12]); *p++ = htonl((u32) (stat->mode & S_IALLUGO)); *p++ = htonl((u32) stat->nlink); *p++ = htonl((u32) from_kuid(&init_user_ns, stat->uid)); *p++ = htonl((u32) from_kgid(&init_user_ns, stat->gid)); if (S_ISLNK(stat->mode) && stat->size > NFS3_MAXPATHLEN) { p = xdr_encode_hyper(p, (u64) NFS3_MAXPATHLEN); } else { p = xdr_encode_hyper(p, (u64) stat->size); } p = xdr_encode_hyper(p, ((u64)stat->blocks) << 9); *p++ = htonl((u32) MAJOR(stat->rdev)); *p++ = htonl((u32) MINOR(stat->rdev)); p = encode_fsid(p, fhp); p = xdr_encode_hyper(p, stat->ino); p = encode_time3(p, &stat->atime); p = encode_time3(p, &stat->mtime); p = encode_time3(p, &stat->ctime); return p; } static __be32 * encode_saved_post_attr(struct svc_rqst *rqstp, __be32 *p, struct svc_fh *fhp) { /* Attributes to follow */ *p++ = xdr_one; return encode_fattr3(rqstp, p, fhp, &fhp->fh_post_attr); } /* * Encode post-operation attributes. * The inode may be NULL if the call failed because of a stale file * handle. In this case, no attributes are returned. */ static __be32 * encode_post_op_attr(struct svc_rqst *rqstp, __be32 *p, struct svc_fh *fhp) { struct dentry *dentry = fhp->fh_dentry; if (dentry && d_really_is_positive(dentry)) { __be32 err; struct kstat stat; err = fh_getattr(fhp, &stat); if (!err) { *p++ = xdr_one; /* attributes follow */ lease_get_mtime(d_inode(dentry), &stat.mtime); return encode_fattr3(rqstp, p, fhp, &stat); } } *p++ = xdr_zero; return p; } /* Helper for NFSv3 ACLs */ __be32 * nfs3svc_encode_post_op_attr(struct svc_rqst *rqstp, __be32 *p, struct svc_fh *fhp) { return encode_post_op_attr(rqstp, p, fhp); } /* * Enocde weak cache consistency data */ static __be32 * encode_wcc_data(struct svc_rqst *rqstp, __be32 *p, struct svc_fh *fhp) { struct dentry *dentry = fhp->fh_dentry; if (dentry && d_really_is_positive(dentry) && fhp->fh_post_saved) { if (fhp->fh_pre_saved) { *p++ = xdr_one; p = xdr_encode_hyper(p, (u64) fhp->fh_pre_size); p = encode_time3(p, &fhp->fh_pre_mtime); p = encode_time3(p, &fhp->fh_pre_ctime); } else { *p++ = xdr_zero; } return encode_saved_post_attr(rqstp, p, fhp); } /* no pre- or post-attrs */ *p++ = xdr_zero; return encode_post_op_attr(rqstp, p, fhp); } /* * Fill in the post_op attr for the wcc data */ void fill_post_wcc(struct svc_fh *fhp) { __be32 err; if (fhp->fh_post_saved) printk("nfsd: inode locked twice during operation.\n"); err = fh_getattr(fhp, &fhp->fh_post_attr); fhp->fh_post_change = d_inode(fhp->fh_dentry)->i_version; if (err) { fhp->fh_post_saved = false; /* Grab the ctime anyway - set_change_info might use it */ fhp->fh_post_attr.ctime = d_inode(fhp->fh_dentry)->i_ctime; } else fhp->fh_post_saved = true; } /* * XDR decode functions */ int nfs3svc_decode_fhandle(struct svc_rqst *rqstp, __be32 *p, struct nfsd_fhandle *args) { p = decode_fh(p, &args->fh); if (!p) return 0; return xdr_argsize_check(rqstp, p); } int nfs3svc_decode_sattrargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_sattrargs *args) { p = decode_fh(p, &args->fh); if (!p) return 0; p = decode_sattr3(p, &args->attrs); if ((args->check_guard = ntohl(*p++)) != 0) { struct timespec time; p = decode_time3(p, &time); args->guardtime = time.tv_sec; } return xdr_argsize_check(rqstp, p); } int nfs3svc_decode_diropargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_diropargs *args) { if (!(p = decode_fh(p, &args->fh)) || !(p = decode_filename(p, &args->name, &args->len))) return 0; return xdr_argsize_check(rqstp, p); } int nfs3svc_decode_accessargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_accessargs *args) { p = decode_fh(p, &args->fh); if (!p) return 0; args->access = ntohl(*p++); return xdr_argsize_check(rqstp, p); } int nfs3svc_decode_readargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_readargs *args) { unsigned int len; int v; u32 max_blocksize = svc_max_payload(rqstp); p = decode_fh(p, &args->fh); if (!p) return 0; p = xdr_decode_hyper(p, &args->offset); args->count = ntohl(*p++); len = min(args->count, max_blocksize); /* set up the kvec */ v=0; while (len > 0) { struct page *p = *(rqstp->rq_next_page++); rqstp->rq_vec[v].iov_base = page_address(p); rqstp->rq_vec[v].iov_len = min_t(unsigned int, len, PAGE_SIZE); len -= rqstp->rq_vec[v].iov_len; v++; } args->vlen = v; return xdr_argsize_check(rqstp, p); } int nfs3svc_decode_writeargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_writeargs *args) { unsigned int len, v, hdr, dlen; u32 max_blocksize = svc_max_payload(rqstp); struct kvec *head = rqstp->rq_arg.head; struct kvec *tail = rqstp->rq_arg.tail; p = decode_fh(p, &args->fh); if (!p) return 0; p = xdr_decode_hyper(p, &args->offset); args->count = ntohl(*p++); args->stable = ntohl(*p++); len = args->len = ntohl(*p++); if ((void *)p > head->iov_base + head->iov_len) return 0; /* * The count must equal the amount of data passed. */ if (args->count != args->len) return 0; /* * Check to make sure that we got the right number of * bytes. */ hdr = (void*)p - head->iov_base; dlen = head->iov_len + rqstp->rq_arg.page_len + tail->iov_len - hdr; /* * Round the length of the data which was specified up to * the next multiple of XDR units and then compare that * against the length which was actually received. * Note that when RPCSEC/GSS (for example) is used, the * data buffer can be padded so dlen might be larger * than required. It must never be smaller. */ if (dlen < XDR_QUADLEN(len)*4) return 0; if (args->count > max_blocksize) { args->count = max_blocksize; len = args->len = max_blocksize; } rqstp->rq_vec[0].iov_base = (void*)p; rqstp->rq_vec[0].iov_len = head->iov_len - hdr; v = 0; while (len > rqstp->rq_vec[v].iov_len) { len -= rqstp->rq_vec[v].iov_len; v++; rqstp->rq_vec[v].iov_base = page_address(rqstp->rq_pages[v]); rqstp->rq_vec[v].iov_len = PAGE_SIZE; } rqstp->rq_vec[v].iov_len = len; args->vlen = v + 1; return 1; } int nfs3svc_decode_createargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_createargs *args) { if (!(p = decode_fh(p, &args->fh)) || !(p = decode_filename(p, &args->name, &args->len))) return 0; switch (args->createmode = ntohl(*p++)) { case NFS3_CREATE_UNCHECKED: case NFS3_CREATE_GUARDED: p = decode_sattr3(p, &args->attrs); break; case NFS3_CREATE_EXCLUSIVE: args->verf = p; p += 2; break; default: return 0; } return xdr_argsize_check(rqstp, p); } int nfs3svc_decode_mkdirargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_createargs *args) { if (!(p = decode_fh(p, &args->fh)) || !(p = decode_filename(p, &args->name, &args->len))) return 0; p = decode_sattr3(p, &args->attrs); return xdr_argsize_check(rqstp, p); } int nfs3svc_decode_symlinkargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_symlinkargs *args) { unsigned int len, avail; char *old, *new; struct kvec *vec; if (!(p = decode_fh(p, &args->ffh)) || !(p = decode_filename(p, &args->fname, &args->flen)) ) return 0; p = decode_sattr3(p, &args->attrs); /* now decode the pathname, which might be larger than the first page. * As we have to check for nul's anyway, we copy it into a new page * This page appears in the rq_res.pages list, but as pages_len is always * 0, it won't get in the way */ len = ntohl(*p++); if (len == 0 || len > NFS3_MAXPATHLEN || len >= PAGE_SIZE) return 0; args->tname = new = page_address(*(rqstp->rq_next_page++)); args->tlen = len; /* first copy and check from the first page */ old = (char*)p; vec = &rqstp->rq_arg.head[0]; if ((void *)old > vec->iov_base + vec->iov_len) return 0; avail = vec->iov_len - (old - (char*)vec->iov_base); while (len && avail && *old) { *new++ = *old++; len--; avail--; } /* now copy next page if there is one */ if (len && !avail && rqstp->rq_arg.page_len) { avail = min_t(unsigned int, rqstp->rq_arg.page_len, PAGE_SIZE); old = page_address(rqstp->rq_arg.pages[0]); } while (len && avail && *old) { *new++ = *old++; len--; avail--; } *new = '\0'; if (len) return 0; return 1; } int nfs3svc_decode_mknodargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_mknodargs *args) { if (!(p = decode_fh(p, &args->fh)) || !(p = decode_filename(p, &args->name, &args->len))) return 0; args->ftype = ntohl(*p++); if (args->ftype == NF3BLK || args->ftype == NF3CHR || args->ftype == NF3SOCK || args->ftype == NF3FIFO) p = decode_sattr3(p, &args->attrs); if (args->ftype == NF3BLK || args->ftype == NF3CHR) { args->major = ntohl(*p++); args->minor = ntohl(*p++); } return xdr_argsize_check(rqstp, p); } int nfs3svc_decode_renameargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_renameargs *args) { if (!(p = decode_fh(p, &args->ffh)) || !(p = decode_filename(p, &args->fname, &args->flen)) || !(p = decode_fh(p, &args->tfh)) || !(p = decode_filename(p, &args->tname, &args->tlen))) return 0; return xdr_argsize_check(rqstp, p); } int nfs3svc_decode_readlinkargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_readlinkargs *args) { p = decode_fh(p, &args->fh); if (!p) return 0; args->buffer = page_address(*(rqstp->rq_next_page++)); return xdr_argsize_check(rqstp, p); } int nfs3svc_decode_linkargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_linkargs *args) { if (!(p = decode_fh(p, &args->ffh)) || !(p = decode_fh(p, &args->tfh)) || !(p = decode_filename(p, &args->tname, &args->tlen))) return 0; return xdr_argsize_check(rqstp, p); } int nfs3svc_decode_readdirargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_readdirargs *args) { p = decode_fh(p, &args->fh); if (!p) return 0; p = xdr_decode_hyper(p, &args->cookie); args->verf = p; p += 2; args->dircount = ~0; args->count = ntohl(*p++); args->count = min_t(u32, args->count, PAGE_SIZE); args->buffer = page_address(*(rqstp->rq_next_page++)); return xdr_argsize_check(rqstp, p); } int nfs3svc_decode_readdirplusargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_readdirargs *args) { int len; u32 max_blocksize = svc_max_payload(rqstp); p = decode_fh(p, &args->fh); if (!p) return 0; p = xdr_decode_hyper(p, &args->cookie); args->verf = p; p += 2; args->dircount = ntohl(*p++); args->count = ntohl(*p++); len = args->count = min(args->count, max_blocksize); while (len > 0) { struct page *p = *(rqstp->rq_next_page++); if (!args->buffer) args->buffer = page_address(p); len -= PAGE_SIZE; } return xdr_argsize_check(rqstp, p); } int nfs3svc_decode_commitargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_commitargs *args) { p = decode_fh(p, &args->fh); if (!p) return 0; p = xdr_decode_hyper(p, &args->offset); args->count = ntohl(*p++); return xdr_argsize_check(rqstp, p); } /* * XDR encode functions */ /* * There must be an encoding function for void results so svc_process * will work properly. */ int nfs3svc_encode_voidres(struct svc_rqst *rqstp, __be32 *p, void *dummy) { return xdr_ressize_check(rqstp, p); } /* GETATTR */ int nfs3svc_encode_attrstat(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_attrstat *resp) { if (resp->status == 0) { lease_get_mtime(d_inode(resp->fh.fh_dentry), &resp->stat.mtime); p = encode_fattr3(rqstp, p, &resp->fh, &resp->stat); } return xdr_ressize_check(rqstp, p); } /* SETATTR, REMOVE, RMDIR */ int nfs3svc_encode_wccstat(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_attrstat *resp) { p = encode_wcc_data(rqstp, p, &resp->fh); return xdr_ressize_check(rqstp, p); } /* LOOKUP */ int nfs3svc_encode_diropres(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_diropres *resp) { if (resp->status == 0) { p = encode_fh(p, &resp->fh); p = encode_post_op_attr(rqstp, p, &resp->fh); } p = encode_post_op_attr(rqstp, p, &resp->dirfh); return xdr_ressize_check(rqstp, p); } /* ACCESS */ int nfs3svc_encode_accessres(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_accessres *resp) { p = encode_post_op_attr(rqstp, p, &resp->fh); if (resp->status == 0) *p++ = htonl(resp->access); return xdr_ressize_check(rqstp, p); } /* READLINK */ int nfs3svc_encode_readlinkres(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_readlinkres *resp) { p = encode_post_op_attr(rqstp, p, &resp->fh); if (resp->status == 0) { *p++ = htonl(resp->len); xdr_ressize_check(rqstp, p); rqstp->rq_res.page_len = resp->len; if (resp->len & 3) { /* need to pad the tail */ rqstp->rq_res.tail[0].iov_base = p; *p = 0; rqstp->rq_res.tail[0].iov_len = 4 - (resp->len&3); } return 1; } else return xdr_ressize_check(rqstp, p); } /* READ */ int nfs3svc_encode_readres(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_readres *resp) { p = encode_post_op_attr(rqstp, p, &resp->fh); if (resp->status == 0) { *p++ = htonl(resp->count); *p++ = htonl(resp->eof); *p++ = htonl(resp->count); /* xdr opaque count */ xdr_ressize_check(rqstp, p); /* now update rqstp->rq_res to reflect data as well */ rqstp->rq_res.page_len = resp->count; if (resp->count & 3) { /* need to pad the tail */ rqstp->rq_res.tail[0].iov_base = p; *p = 0; rqstp->rq_res.tail[0].iov_len = 4 - (resp->count & 3); } return 1; } else return xdr_ressize_check(rqstp, p); } /* WRITE */ int nfs3svc_encode_writeres(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_writeres *resp) { struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id); p = encode_wcc_data(rqstp, p, &resp->fh); if (resp->status == 0) { *p++ = htonl(resp->count); *p++ = htonl(resp->committed); *p++ = htonl(nn->nfssvc_boot.tv_sec); *p++ = htonl(nn->nfssvc_boot.tv_usec); } return xdr_ressize_check(rqstp, p); } /* CREATE, MKDIR, SYMLINK, MKNOD */ int nfs3svc_encode_createres(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_diropres *resp) { if (resp->status == 0) { *p++ = xdr_one; p = encode_fh(p, &resp->fh); p = encode_post_op_attr(rqstp, p, &resp->fh); } p = encode_wcc_data(rqstp, p, &resp->dirfh); return xdr_ressize_check(rqstp, p); } /* RENAME */ int nfs3svc_encode_renameres(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_renameres *resp) { p = encode_wcc_data(rqstp, p, &resp->ffh); p = encode_wcc_data(rqstp, p, &resp->tfh); return xdr_ressize_check(rqstp, p); } /* LINK */ int nfs3svc_encode_linkres(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_linkres *resp) { p = encode_post_op_attr(rqstp, p, &resp->fh); p = encode_wcc_data(rqstp, p, &resp->tfh); return xdr_ressize_check(rqstp, p); } /* READDIR */ int nfs3svc_encode_readdirres(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_readdirres *resp) { p = encode_post_op_attr(rqstp, p, &resp->fh); if (resp->status == 0) { /* stupid readdir cookie */ memcpy(p, resp->verf, 8); p += 2; xdr_ressize_check(rqstp, p); if (rqstp->rq_res.head[0].iov_len + (2<<2) > PAGE_SIZE) return 1; /*No room for trailer */ rqstp->rq_res.page_len = (resp->count) << 2; /* add the 'tail' to the end of the 'head' page - page 0. */ rqstp->rq_res.tail[0].iov_base = p; *p++ = 0; /* no more entries */ *p++ = htonl(resp->common.err == nfserr_eof); rqstp->rq_res.tail[0].iov_len = 2<<2; return 1; } else return xdr_ressize_check(rqstp, p); } static __be32 * encode_entry_baggage(struct nfsd3_readdirres *cd, __be32 *p, const char *name, int namlen, u64 ino) { *p++ = xdr_one; /* mark entry present */ p = xdr_encode_hyper(p, ino); /* file id */ p = xdr_encode_array(p, name, namlen);/* name length & name */ cd->offset = p; /* remember pointer */ p = xdr_encode_hyper(p, NFS_OFFSET_MAX);/* offset of next entry */ return p; } static __be32 compose_entry_fh(struct nfsd3_readdirres *cd, struct svc_fh *fhp, const char *name, int namlen, u64 ino) { struct svc_export *exp; struct dentry *dparent, *dchild; __be32 rv = nfserr_noent; dparent = cd->fh.fh_dentry; exp = cd->fh.fh_export; if (isdotent(name, namlen)) { if (namlen == 2) { dchild = dget_parent(dparent); /* filesystem root - cannot return filehandle for ".." */ if (dchild == dparent) goto out; } else dchild = dget(dparent); } else dchild = lookup_one_len_unlocked(name, dparent, namlen); if (IS_ERR(dchild)) return rv; if (d_mountpoint(dchild)) goto out; if (d_really_is_negative(dchild)) goto out; if (dchild->d_inode->i_ino != ino) goto out; rv = fh_compose(fhp, exp, dchild, &cd->fh); out: dput(dchild); return rv; } static __be32 *encode_entryplus_baggage(struct nfsd3_readdirres *cd, __be32 *p, const char *name, int namlen, u64 ino) { struct svc_fh *fh = &cd->scratch; __be32 err; fh_init(fh, NFS3_FHSIZE); err = compose_entry_fh(cd, fh, name, namlen, ino); if (err) { *p++ = 0; *p++ = 0; goto out; } p = encode_post_op_attr(cd->rqstp, p, fh); *p++ = xdr_one; /* yes, a file handle follows */ p = encode_fh(p, fh); out: fh_put(fh); return p; } /* * Encode a directory entry. This one works for both normal readdir * and readdirplus. * The normal readdir reply requires 2 (fileid) + 1 (stringlen) * + string + 2 (cookie) + 1 (next) words, i.e. 6 + strlen. * * The readdirplus baggage is 1+21 words for post_op_attr, plus the * file handle. */ #define NFS3_ENTRY_BAGGAGE (2 + 1 + 2 + 1) #define NFS3_ENTRYPLUS_BAGGAGE (1 + 21 + 1 + (NFS3_FHSIZE >> 2)) static int encode_entry(struct readdir_cd *ccd, const char *name, int namlen, loff_t offset, u64 ino, unsigned int d_type, int plus) { struct nfsd3_readdirres *cd = container_of(ccd, struct nfsd3_readdirres, common); __be32 *p = cd->buffer; caddr_t curr_page_addr = NULL; struct page ** page; int slen; /* string (name) length */ int elen; /* estimated entry length in words */ int num_entry_words = 0; /* actual number of words */ if (cd->offset) { u64 offset64 = offset; if (unlikely(cd->offset1)) { /* we ended up with offset on a page boundary */ *cd->offset = htonl(offset64 >> 32); *cd->offset1 = htonl(offset64 & 0xffffffff); cd->offset1 = NULL; } else { xdr_encode_hyper(cd->offset, offset64); } } /* dprintk("encode_entry(%.*s @%ld%s)\n", namlen, name, (long) offset, plus? " plus" : ""); */ /* truncate filename if too long */ namlen = min(namlen, NFS3_MAXNAMLEN); slen = XDR_QUADLEN(namlen); elen = slen + NFS3_ENTRY_BAGGAGE + (plus? NFS3_ENTRYPLUS_BAGGAGE : 0); if (cd->buflen < elen) { cd->common.err = nfserr_toosmall; return -EINVAL; } /* determine which page in rq_respages[] we are currently filling */ for (page = cd->rqstp->rq_respages + 1; page < cd->rqstp->rq_next_page; page++) { curr_page_addr = page_address(*page); if (((caddr_t)cd->buffer >= curr_page_addr) && ((caddr_t)cd->buffer < curr_page_addr + PAGE_SIZE)) break; } if ((caddr_t)(cd->buffer + elen) < (curr_page_addr + PAGE_SIZE)) { /* encode entry in current page */ p = encode_entry_baggage(cd, p, name, namlen, ino); if (plus) p = encode_entryplus_baggage(cd, p, name, namlen, ino); num_entry_words = p - cd->buffer; } else if (*(page+1) != NULL) { /* temporarily encode entry into next page, then move back to * current and next page in rq_respages[] */ __be32 *p1, *tmp; int len1, len2; /* grab next page for temporary storage of entry */ p1 = tmp = page_address(*(page+1)); p1 = encode_entry_baggage(cd, p1, name, namlen, ino); if (plus) p1 = encode_entryplus_baggage(cd, p1, name, namlen, ino); /* determine entry word length and lengths to go in pages */ num_entry_words = p1 - tmp; len1 = curr_page_addr + PAGE_SIZE - (caddr_t)cd->buffer; if ((num_entry_words << 2) < len1) { /* the actual number of words in the entry is less * than elen and can still fit in the current page */ memmove(p, tmp, num_entry_words << 2); p += num_entry_words; /* update offset */ cd->offset = cd->buffer + (cd->offset - tmp); } else { unsigned int offset_r = (cd->offset - tmp) << 2; /* update pointer to offset location. * This is a 64bit quantity, so we need to * deal with 3 cases: * - entirely in first page * - entirely in second page * - 4 bytes in each page */ if (offset_r + 8 <= len1) { cd->offset = p + (cd->offset - tmp); } else if (offset_r >= len1) { cd->offset -= len1 >> 2; } else { /* sitting on the fence */ BUG_ON(offset_r != len1 - 4); cd->offset = p + (cd->offset - tmp); cd->offset1 = tmp; } len2 = (num_entry_words << 2) - len1; /* move from temp page to current and next pages */ memmove(p, tmp, len1); memmove(tmp, (caddr_t)tmp+len1, len2); p = tmp + (len2 >> 2); } } else { cd->common.err = nfserr_toosmall; return -EINVAL; } cd->buflen -= num_entry_words; cd->buffer = p; cd->common.err = nfs_ok; return 0; } int nfs3svc_encode_entry(void *cd, const char *name, int namlen, loff_t offset, u64 ino, unsigned int d_type) { return encode_entry(cd, name, namlen, offset, ino, d_type, 0); } int nfs3svc_encode_entry_plus(void *cd, const char *name, int namlen, loff_t offset, u64 ino, unsigned int d_type) { return encode_entry(cd, name, namlen, offset, ino, d_type, 1); } /* FSSTAT */ int nfs3svc_encode_fsstatres(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_fsstatres *resp) { struct kstatfs *s = &resp->stats; u64 bs = s->f_bsize; *p++ = xdr_zero; /* no post_op_attr */ if (resp->status == 0) { p = xdr_encode_hyper(p, bs * s->f_blocks); /* total bytes */ p = xdr_encode_hyper(p, bs * s->f_bfree); /* free bytes */ p = xdr_encode_hyper(p, bs * s->f_bavail); /* user available bytes */ p = xdr_encode_hyper(p, s->f_files); /* total inodes */ p = xdr_encode_hyper(p, s->f_ffree); /* free inodes */ p = xdr_encode_hyper(p, s->f_ffree); /* user available inodes */ *p++ = htonl(resp->invarsec); /* mean unchanged time */ } return xdr_ressize_check(rqstp, p); } /* FSINFO */ int nfs3svc_encode_fsinfores(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_fsinfores *resp) { *p++ = xdr_zero; /* no post_op_attr */ if (resp->status == 0) { *p++ = htonl(resp->f_rtmax); *p++ = htonl(resp->f_rtpref); *p++ = htonl(resp->f_rtmult); *p++ = htonl(resp->f_wtmax); *p++ = htonl(resp->f_wtpref); *p++ = htonl(resp->f_wtmult); *p++ = htonl(resp->f_dtpref); p = xdr_encode_hyper(p, resp->f_maxfilesize); *p++ = xdr_one; *p++ = xdr_zero; *p++ = htonl(resp->f_properties); } return xdr_ressize_check(rqstp, p); } /* PATHCONF */ int nfs3svc_encode_pathconfres(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_pathconfres *resp) { *p++ = xdr_zero; /* no post_op_attr */ if (resp->status == 0) { *p++ = htonl(resp->p_link_max); *p++ = htonl(resp->p_name_max); *p++ = htonl(resp->p_no_trunc); *p++ = htonl(resp->p_chown_restricted); *p++ = htonl(resp->p_case_insensitive); *p++ = htonl(resp->p_case_preserving); } return xdr_ressize_check(rqstp, p); } /* COMMIT */ int nfs3svc_encode_commitres(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_commitres *resp) { struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id); p = encode_wcc_data(rqstp, p, &resp->fh); /* Write verifier */ if (resp->status == 0) { *p++ = htonl(nn->nfssvc_boot.tv_sec); *p++ = htonl(nn->nfssvc_boot.tv_usec); } return xdr_ressize_check(rqstp, p); } /* * XDR release functions */ int nfs3svc_release_fhandle(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_attrstat *resp) { fh_put(&resp->fh); return 1; } int nfs3svc_release_fhandle2(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_fhandle_pair *resp) { fh_put(&resp->fh1); fh_put(&resp->fh2); return 1; }
./CrossVul/dataset_final_sorted/CWE-119/c/good_3305_0
crossvul-cpp_data_bad_340_9
/* * Copyright (C) 2017 Frank Morgner <frankmorgner@gmail.com> * * This file is part of OpenSC. * * 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 "egk-tool-cmdline.h" #include "libopensc/log.h" #include "libopensc/opensc.h" #include <ctype.h> #include <stdlib.h> #include <string.h> #ifdef _WIN32 #include <io.h> #include <fcntl.h> #endif #ifdef ENABLE_ZLIB #include <zlib.h> int uncompress_gzip(void* uncompressed, size_t *uncompressed_len, const void* compressed, size_t compressed_len) { z_stream stream; memset(&stream, 0, sizeof stream); stream.total_in = compressed_len; stream.avail_in = compressed_len; stream.total_out = *uncompressed_len; stream.avail_out = *uncompressed_len; stream.next_in = (Bytef *) compressed; stream.next_out = (Bytef *) uncompressed; /* 15 window bits, and the +32 tells zlib to to detect if using gzip or zlib */ if (Z_OK == inflateInit2(&stream, (15 + 32)) && Z_STREAM_END == inflate(&stream, Z_FINISH)) { *uncompressed_len = stream.total_out; } else { return SC_ERROR_INVALID_DATA; } inflateEnd(&stream); return SC_SUCCESS; } #else int uncompress_gzip(void* uncompressed, size_t *uncompressed_len, const void* compressed, size_t compressed_len) { return SC_ERROR_NOT_SUPPORTED; } #endif #define PRINT(c) (isprint(c) ? c : '?') void dump_binary(void *buf, size_t buf_len) { #ifdef _WIN32 _setmode(fileno(stdout), _O_BINARY); #endif fwrite(buf, 1, buf_len, stdout); #ifdef _WIN32 _setmode(fileno(stdout), _O_TEXT); #endif } const unsigned char aid_hca[] = {0xD2, 0x76, 0x00, 0x00, 0x01, 0x02}; static int initialize(int reader_id, int verbose, sc_context_t **ctx, sc_reader_t **reader) { unsigned int i, reader_count; int r; if (!ctx || !reader) return SC_ERROR_INVALID_ARGUMENTS; r = sc_establish_context(ctx, ""); if (r < 0 || !*ctx) { fprintf(stderr, "Failed to create initial context: %s", sc_strerror(r)); return r; } (*ctx)->debug = verbose; (*ctx)->flags |= SC_CTX_FLAG_ENABLE_DEFAULT_DRIVER; reader_count = sc_ctx_get_reader_count(*ctx); if (reader_count == 0) { sc_debug(*ctx, SC_LOG_DEBUG_NORMAL, "No reader not found.\n"); return SC_ERROR_NO_READERS_FOUND; } if (reader_id < 0) { /* Automatically try to skip to a reader with a card if reader not specified */ for (i = 0; i < reader_count; i++) { *reader = sc_ctx_get_reader(*ctx, i); if (sc_detect_card_presence(*reader) & SC_READER_CARD_PRESENT) { reader_id = i; sc_debug(*ctx, SC_LOG_DEBUG_NORMAL, "Using the first reader" " with a card: %s", (*reader)->name); break; } } if ((unsigned int) reader_id >= reader_count) { sc_debug(*ctx, SC_LOG_DEBUG_NORMAL, "No card found, using the first reader."); reader_id = 0; } } if ((unsigned int) reader_id >= reader_count) { sc_debug(*ctx, SC_LOG_DEBUG_NORMAL, "Invalid reader number " "(%d), only %d available.\n", reader_id, reader_count); return SC_ERROR_NO_READERS_FOUND; } *reader = sc_ctx_get_reader(*ctx, reader_id); return SC_SUCCESS; } int read_file(struct sc_card *card, char *str_path, unsigned char **data, size_t *data_len) { struct sc_path path; struct sc_file *file; unsigned char *p; int ok = 0; int r; size_t len; sc_format_path(str_path, &path); if (SC_SUCCESS != sc_select_file(card, &path, &file)) { goto err; } len = file ? file->size : 4096; p = realloc(*data, len); if (!p) { goto err; } *data = p; *data_len = len; r = sc_read_binary(card, 0, p, len, 0); if (r < 0) goto err; *data_len = r; ok = 1; err: sc_file_free(file); return ok; } void decode_version(unsigned char *bcd, unsigned int *major, unsigned int *minor, unsigned int *fix) { *major = 0; *minor = 0; *fix = 0; /* decode BCD to decimal */ if ((bcd[0]>>4) < 10 && ((bcd[0]&0xF) < 10) && ((bcd[1]>>4) < 10)) { *major = (bcd[0]>>4)*100 + (bcd[0]&0xF)*10 + (bcd[1]>>4); } if (((bcd[1]&0xF) < 10) && ((bcd[2]>>4) < 10) && ((bcd[2]&0xF) < 10)) { *minor = (bcd[1]&0xF)*100 + (bcd[2]>>4)*10 + (bcd[2]&0xF); } if ((bcd[3]>>4) < 10 && ((bcd[3]&0xF) < 10) && (bcd[4]>>4) < 10 && ((bcd[4]&0xF) < 10)) { *fix = (bcd[3]>>4)*1000 + (bcd[3]&0xF)*100 + (bcd[4]>>4)*10 + (bcd[4]&0xF); } } int main (int argc, char **argv) { struct gengetopt_args_info cmdline; struct sc_path path; struct sc_context *ctx; struct sc_reader *reader = NULL; struct sc_card *card; unsigned char *data = NULL; size_t data_len = 0; int r; if (cmdline_parser(argc, argv, &cmdline) != 0) exit(1); r = initialize(cmdline.reader_arg, cmdline.verbose_given, &ctx, &reader); if (r < 0) { fprintf(stderr, "Can't initialize reader\n"); exit(1); } if (sc_connect_card(reader, &card) < 0) { fprintf(stderr, "Could not connect to card\n"); sc_release_context(ctx); exit(1); } sc_path_set(&path, SC_PATH_TYPE_DF_NAME, aid_hca, sizeof aid_hca, 0, 0); if (SC_SUCCESS != sc_select_file(card, &path, NULL)) goto err; if (cmdline.pd_flag && read_file(card, "D001", &data, &data_len) && data_len >= 2) { size_t len_pd = (data[0] << 8) | data[1]; if (len_pd + 2 <= data_len) { unsigned char uncompressed[1024]; size_t uncompressed_len = sizeof uncompressed; if (uncompress_gzip(uncompressed, &uncompressed_len, data + 2, len_pd) == SC_SUCCESS) { dump_binary(uncompressed, uncompressed_len); } else { dump_binary(data + 2, len_pd); } } } if ((cmdline.vd_flag || cmdline.gvd_flag) && read_file(card, "D001", &data, &data_len) && data_len >= 8) { size_t off_vd = (data[0] << 8) | data[1]; size_t end_vd = (data[2] << 8) | data[3]; size_t off_gvd = (data[4] << 8) | data[5]; size_t end_gvd = (data[6] << 8) | data[7]; size_t len_vd = end_vd - off_vd + 1; size_t len_gvd = end_gvd - off_gvd + 1; if (off_vd <= end_vd && end_vd < data_len && off_gvd <= end_gvd && end_gvd < data_len) { unsigned char uncompressed[1024]; size_t uncompressed_len = sizeof uncompressed; if (cmdline.vd_flag) { if (uncompress_gzip(uncompressed, &uncompressed_len, data + off_vd, len_vd) == SC_SUCCESS) { dump_binary(uncompressed, uncompressed_len); } else { dump_binary(data + off_vd, len_vd); } } if (cmdline.gvd_flag) { if (uncompress_gzip(uncompressed, &uncompressed_len, data + off_gvd, len_gvd) == SC_SUCCESS) { dump_binary(uncompressed, uncompressed_len); } else { dump_binary(data + off_gvd, len_gvd); } } } } if (cmdline.vsd_status_flag && read_file(card, "D00C", &data, &data_len) && data_len >= 25) { char *status; unsigned int major, minor, fix; switch (data[0]) { case '0': status = "Transactions pending"; break; case '1': status = "No transactions pending"; break; default: status = "Unknown"; break; } decode_version(data+15, &major, &minor, &fix); printf( "Status %s\n" "Timestamp %c%c.%c%c.%c%c%c%c at %c%c:%c%c:%c%c\n" "Version %u.%u.%u\n", status, PRINT(data[7]), PRINT(data[8]), PRINT(data[5]), PRINT(data[6]), PRINT(data[1]), PRINT(data[2]), PRINT(data[3]), PRINT(data[4]), PRINT(data[9]), PRINT(data[10]), PRINT(data[11]), PRINT(data[12]), PRINT(data[13]), PRINT(data[14]), major, minor, fix); } err: sc_disconnect_card(card); sc_release_context(ctx); cmdline_parser_free (&cmdline); return 0; }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_340_9
crossvul-cpp_data_good_5486_0
/* * Copyright (c) 1999-2000 Image Power, Inc. and the University of * British Columbia. * Copyright (c) 2001-2003 Michael David Adams. * All rights reserved. */ /* __START_OF_JASPER_LICENSE__ * * JasPer License Version 2.0 * * Copyright (c) 2001-2006 Michael David Adams * Copyright (c) 1999-2000 Image Power, Inc. * Copyright (c) 1999-2000 The University of British Columbia * * All rights reserved. * * Permission is hereby granted, free of charge, to any person (the * "User") obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, and/or sell copies of the Software, and to permit * persons to whom the Software is furnished to do so, subject to the * following conditions: * * 1. The above copyright notices and this permission notice (which * includes the disclaimer below) shall be included in all copies or * substantial portions of the Software. * * 2. The name of a copyright holder shall not be used to endorse or * promote products derived from the Software without specific prior * written permission. * * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY. * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES, * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH, * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. * * __END_OF_JASPER_LICENSE__ */ /* * $Id$ */ /******************************************************************************\ * Includes. \******************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <inttypes.h> #include "jasper/jas_types.h" #include "jasper/jas_math.h" #include "jasper/jas_tvp.h" #include "jasper/jas_malloc.h" #include "jasper/jas_debug.h" #include "jpc_fix.h" #include "jpc_dec.h" #include "jpc_cs.h" #include "jpc_mct.h" #include "jpc_t2dec.h" #include "jpc_t1dec.h" #include "jpc_math.h" /******************************************************************************\ * \******************************************************************************/ #define JPC_MHSOC 0x0001 /* In the main header, expecting a SOC marker segment. */ #define JPC_MHSIZ 0x0002 /* In the main header, expecting a SIZ marker segment. */ #define JPC_MH 0x0004 /* In the main header, expecting "other" marker segments. */ #define JPC_TPHSOT 0x0008 /* In a tile-part header, expecting a SOT marker segment. */ #define JPC_TPH 0x0010 /* In a tile-part header, expecting "other" marker segments. */ #define JPC_MT 0x0020 /* In the main trailer. */ typedef struct { uint_fast16_t id; /* The marker segment type. */ int validstates; /* The states in which this type of marker segment can be validly encountered. */ int (*action)(jpc_dec_t *dec, jpc_ms_t *ms); /* The action to take upon encountering this type of marker segment. */ } jpc_dec_mstabent_t; /******************************************************************************\ * \******************************************************************************/ /* COD/COC parameters have been specified. */ #define JPC_CSET 0x0001 /* QCD/QCC parameters have been specified. */ #define JPC_QSET 0x0002 /* COD/COC parameters set from a COC marker segment. */ #define JPC_COC 0x0004 /* QCD/QCC parameters set from a QCC marker segment. */ #define JPC_QCC 0x0008 /******************************************************************************\ * Local function prototypes. \******************************************************************************/ static int jpc_dec_dump(jpc_dec_t *dec, FILE *out); jpc_ppxstab_t *jpc_ppxstab_create(void); void jpc_ppxstab_destroy(jpc_ppxstab_t *tab); int jpc_ppxstab_grow(jpc_ppxstab_t *tab, int maxents); int jpc_ppxstab_insert(jpc_ppxstab_t *tab, jpc_ppxstabent_t *ent); jpc_streamlist_t *jpc_ppmstabtostreams(jpc_ppxstab_t *tab); int jpc_pptstabwrite(jas_stream_t *out, jpc_ppxstab_t *tab); jpc_ppxstabent_t *jpc_ppxstabent_create(void); void jpc_ppxstabent_destroy(jpc_ppxstabent_t *ent); int jpc_streamlist_numstreams(jpc_streamlist_t *streamlist); jpc_streamlist_t *jpc_streamlist_create(void); int jpc_streamlist_insert(jpc_streamlist_t *streamlist, int streamno, jas_stream_t *stream); jas_stream_t *jpc_streamlist_remove(jpc_streamlist_t *streamlist, int streamno); void jpc_streamlist_destroy(jpc_streamlist_t *streamlist); jas_stream_t *jpc_streamlist_get(jpc_streamlist_t *streamlist, int streamno); static void jpc_dec_cp_resetflags(jpc_dec_cp_t *cp); static jpc_dec_cp_t *jpc_dec_cp_create(uint_fast16_t numcomps); static int jpc_dec_cp_isvalid(jpc_dec_cp_t *cp); static jpc_dec_cp_t *jpc_dec_cp_copy(jpc_dec_cp_t *cp); static int jpc_dec_cp_setfromcod(jpc_dec_cp_t *cp, jpc_cod_t *cod); static int jpc_dec_cp_setfromcoc(jpc_dec_cp_t *cp, jpc_coc_t *coc); static int jpc_dec_cp_setfromcox(jpc_dec_cp_t *cp, jpc_dec_ccp_t *ccp, jpc_coxcp_t *compparms, int flags); static int jpc_dec_cp_setfromqcd(jpc_dec_cp_t *cp, jpc_qcd_t *qcd); static int jpc_dec_cp_setfromqcc(jpc_dec_cp_t *cp, jpc_qcc_t *qcc); static int jpc_dec_cp_setfromqcx(jpc_dec_cp_t *cp, jpc_dec_ccp_t *ccp, jpc_qcxcp_t *compparms, int flags); static int jpc_dec_cp_setfromrgn(jpc_dec_cp_t *cp, jpc_rgn_t *rgn); static int jpc_dec_cp_prepare(jpc_dec_cp_t *cp); static void jpc_dec_cp_destroy(jpc_dec_cp_t *cp); static int jpc_dec_cp_setfrompoc(jpc_dec_cp_t *cp, jpc_poc_t *poc, int reset); static int jpc_pi_addpchgfrompoc(jpc_pi_t *pi, jpc_poc_t *poc); static int jpc_dec_decode(jpc_dec_t *dec); static jpc_dec_t *jpc_dec_create(jpc_dec_importopts_t *impopts, jas_stream_t *in); static void jpc_dec_destroy(jpc_dec_t *dec); static void jpc_dequantize(jas_matrix_t *x, jpc_fix_t absstepsize); static void jpc_undo_roi(jas_matrix_t *x, int roishift, int bgshift, int numbps); static jpc_fix_t jpc_calcabsstepsize(int stepsize, int numbits); static int jpc_dec_tiledecode(jpc_dec_t *dec, jpc_dec_tile_t *tile); static int jpc_dec_tileinit(jpc_dec_t *dec, jpc_dec_tile_t *tile); static int jpc_dec_tilefini(jpc_dec_t *dec, jpc_dec_tile_t *tile); static int jpc_dec_process_soc(jpc_dec_t *dec, jpc_ms_t *ms); static int jpc_dec_process_sot(jpc_dec_t *dec, jpc_ms_t *ms); static int jpc_dec_process_sod(jpc_dec_t *dec, jpc_ms_t *ms); static int jpc_dec_process_eoc(jpc_dec_t *dec, jpc_ms_t *ms); static int jpc_dec_process_siz(jpc_dec_t *dec, jpc_ms_t *ms); static int jpc_dec_process_cod(jpc_dec_t *dec, jpc_ms_t *ms); static int jpc_dec_process_coc(jpc_dec_t *dec, jpc_ms_t *ms); static int jpc_dec_process_rgn(jpc_dec_t *dec, jpc_ms_t *ms); static int jpc_dec_process_qcd(jpc_dec_t *dec, jpc_ms_t *ms); static int jpc_dec_process_qcc(jpc_dec_t *dec, jpc_ms_t *ms); static int jpc_dec_process_poc(jpc_dec_t *dec, jpc_ms_t *ms); static int jpc_dec_process_ppm(jpc_dec_t *dec, jpc_ms_t *ms); static int jpc_dec_process_ppt(jpc_dec_t *dec, jpc_ms_t *ms); static int jpc_dec_process_com(jpc_dec_t *dec, jpc_ms_t *ms); static int jpc_dec_process_unk(jpc_dec_t *dec, jpc_ms_t *ms); static int jpc_dec_process_crg(jpc_dec_t *dec, jpc_ms_t *ms); static jpc_dec_importopts_t *jpc_dec_opts_create(const char *optstr); static void jpc_dec_opts_destroy(jpc_dec_importopts_t *opts); static jpc_dec_mstabent_t *jpc_dec_mstab_lookup(uint_fast16_t id); /******************************************************************************\ * Global data. \******************************************************************************/ jpc_dec_mstabent_t jpc_dec_mstab[] = { {JPC_MS_SOC, JPC_MHSOC, jpc_dec_process_soc}, {JPC_MS_SOT, JPC_MH | JPC_TPHSOT, jpc_dec_process_sot}, {JPC_MS_SOD, JPC_TPH, jpc_dec_process_sod}, {JPC_MS_EOC, JPC_TPHSOT, jpc_dec_process_eoc}, {JPC_MS_SIZ, JPC_MHSIZ, jpc_dec_process_siz}, {JPC_MS_COD, JPC_MH | JPC_TPH, jpc_dec_process_cod}, {JPC_MS_COC, JPC_MH | JPC_TPH, jpc_dec_process_coc}, {JPC_MS_RGN, JPC_MH | JPC_TPH, jpc_dec_process_rgn}, {JPC_MS_QCD, JPC_MH | JPC_TPH, jpc_dec_process_qcd}, {JPC_MS_QCC, JPC_MH | JPC_TPH, jpc_dec_process_qcc}, {JPC_MS_POC, JPC_MH | JPC_TPH, jpc_dec_process_poc}, {JPC_MS_TLM, JPC_MH, 0}, {JPC_MS_PLM, JPC_MH, 0}, {JPC_MS_PLT, JPC_TPH, 0}, {JPC_MS_PPM, JPC_MH, jpc_dec_process_ppm}, {JPC_MS_PPT, JPC_TPH, jpc_dec_process_ppt}, {JPC_MS_SOP, 0, 0}, {JPC_MS_CRG, JPC_MH, jpc_dec_process_crg}, {JPC_MS_COM, JPC_MH | JPC_TPH, jpc_dec_process_com}, {0, JPC_MH | JPC_TPH, jpc_dec_process_unk} }; /******************************************************************************\ * The main entry point for the JPEG-2000 decoder. \******************************************************************************/ jas_image_t *jpc_decode(jas_stream_t *in, const char *optstr) { jpc_dec_importopts_t *opts; jpc_dec_t *dec; jas_image_t *image; dec = 0; opts = 0; JAS_DBGLOG(100, ("jpc_decode(%p, \"%s\")\n", in, optstr)); if (!(opts = jpc_dec_opts_create(optstr))) { goto error; } jpc_initluts(); if (!(dec = jpc_dec_create(opts, in))) { goto error; } jpc_dec_opts_destroy(opts); opts = 0; /* Do most of the work. */ if (jpc_dec_decode(dec)) { goto error; } if (jas_image_numcmpts(dec->image) >= 3) { jas_image_setclrspc(dec->image, JAS_CLRSPC_SRGB); jas_image_setcmpttype(dec->image, 0, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R)); jas_image_setcmpttype(dec->image, 1, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G)); jas_image_setcmpttype(dec->image, 2, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B)); } else { jas_image_setclrspc(dec->image, JAS_CLRSPC_SGRAY); jas_image_setcmpttype(dec->image, 0, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y)); } /* Save the return value. */ image = dec->image; /* Stop the image from being discarded. */ dec->image = 0; /* Destroy decoder. */ jpc_dec_destroy(dec); return image; error: if (opts) { jpc_dec_opts_destroy(opts); } if (dec) { jpc_dec_destroy(dec); } return 0; } typedef enum { OPT_MAXLYRS, OPT_MAXPKTS, OPT_MAXSAMPLES, OPT_DEBUG } optid_t; static jas_taginfo_t decopts[] = { {OPT_MAXLYRS, "maxlyrs"}, {OPT_MAXPKTS, "maxpkts"}, {OPT_MAXSAMPLES, "max_samples"}, {OPT_DEBUG, "debug"}, {-1, 0} }; static jpc_dec_importopts_t *jpc_dec_opts_create(const char *optstr) { jpc_dec_importopts_t *opts; jas_tvparser_t *tvp; opts = 0; if (!(opts = jas_malloc(sizeof(jpc_dec_importopts_t)))) { goto error; } opts->debug = 0; opts->maxlyrs = JPC_MAXLYRS; opts->maxpkts = -1; opts->max_samples = JAS_DEC_DEFAULT_MAX_SAMPLES; if (!(tvp = jas_tvparser_create(optstr ? optstr : ""))) { goto error; } while (!jas_tvparser_next(tvp)) { switch (jas_taginfo_nonull(jas_taginfos_lookup(decopts, jas_tvparser_gettag(tvp)))->id) { case OPT_MAXLYRS: opts->maxlyrs = atoi(jas_tvparser_getval(tvp)); break; case OPT_DEBUG: opts->debug = atoi(jas_tvparser_getval(tvp)); break; case OPT_MAXPKTS: opts->maxpkts = atoi(jas_tvparser_getval(tvp)); break; case OPT_MAXSAMPLES: opts->max_samples = strtoull(jas_tvparser_getval(tvp), 0, 10); break; default: jas_eprintf("warning: ignoring invalid option %s\n", jas_tvparser_gettag(tvp)); break; } } jas_tvparser_destroy(tvp); return opts; error: if (opts) { jpc_dec_opts_destroy(opts); } return 0; } static void jpc_dec_opts_destroy(jpc_dec_importopts_t *opts) { jas_free(opts); } /******************************************************************************\ * Code for table-driven code stream decoder. \******************************************************************************/ static jpc_dec_mstabent_t *jpc_dec_mstab_lookup(uint_fast16_t id) { jpc_dec_mstabent_t *mstabent; for (mstabent = jpc_dec_mstab; mstabent->id != 0; ++mstabent) { if (mstabent->id == id) { break; } } return mstabent; } static int jpc_dec_decode(jpc_dec_t *dec) { jpc_ms_t *ms; jpc_dec_mstabent_t *mstabent; int ret; jpc_cstate_t *cstate; if (!(cstate = jpc_cstate_create())) { return -1; } dec->cstate = cstate; /* Initially, we should expect to encounter a SOC marker segment. */ dec->state = JPC_MHSOC; for (;;) { /* Get the next marker segment in the code stream. */ if (!(ms = jpc_getms(dec->in, cstate))) { jas_eprintf("cannot get marker segment\n"); return -1; } mstabent = jpc_dec_mstab_lookup(ms->id); assert(mstabent); /* Ensure that this type of marker segment is permitted at this point in the code stream. */ if (!(dec->state & mstabent->validstates)) { jas_eprintf("unexpected marker segment type\n"); jpc_ms_destroy(ms); return -1; } /* Process the marker segment. */ if (mstabent->action) { ret = (*mstabent->action)(dec, ms); } else { /* No explicit action is required. */ ret = 0; } /* Destroy the marker segment. */ jpc_ms_destroy(ms); if (ret < 0) { return -1; } else if (ret > 0) { break; } } return 0; } static int jpc_dec_process_crg(jpc_dec_t *dec, jpc_ms_t *ms) { int cmptno; jpc_dec_cmpt_t *cmpt; jpc_crg_t *crg; crg = &ms->parms.crg; for (cmptno = 0, cmpt = dec->cmpts; cmptno < dec->numcomps; ++cmptno, ++cmpt) { /* Ignore the information in the CRG marker segment for now. This information serves no useful purpose for decoding anyhow. Some other parts of the code need to be changed if these lines are uncommented. cmpt->hsubstep = crg->comps[cmptno].hoff; cmpt->vsubstep = crg->comps[cmptno].voff; */ } return 0; } static int jpc_dec_process_soc(jpc_dec_t *dec, jpc_ms_t *ms) { /* Eliminate warnings about unused variables. */ ms = 0; /* We should expect to encounter a SIZ marker segment next. */ dec->state = JPC_MHSIZ; return 0; } static int jpc_dec_process_sot(jpc_dec_t *dec, jpc_ms_t *ms) { jpc_dec_tile_t *tile; jpc_sot_t *sot = &ms->parms.sot; jas_image_cmptparm_t *compinfos; jas_image_cmptparm_t *compinfo; jpc_dec_cmpt_t *cmpt; int cmptno; if (dec->state == JPC_MH) { if (!(compinfos = jas_alloc2(dec->numcomps, sizeof(jas_image_cmptparm_t)))) { abort(); } for (cmptno = 0, cmpt = dec->cmpts, compinfo = compinfos; cmptno < dec->numcomps; ++cmptno, ++cmpt, ++compinfo) { compinfo->tlx = 0; compinfo->tly = 0; compinfo->prec = cmpt->prec; compinfo->sgnd = cmpt->sgnd; compinfo->width = cmpt->width; compinfo->height = cmpt->height; compinfo->hstep = cmpt->hstep; compinfo->vstep = cmpt->vstep; } if (!(dec->image = jas_image_create(dec->numcomps, compinfos, JAS_CLRSPC_UNKNOWN))) { jas_free(compinfos); return -1; } jas_free(compinfos); /* Is the packet header information stored in PPM marker segments in the main header? */ if (dec->ppmstab) { /* Convert the PPM marker segment data into a collection of streams (one stream per tile-part). */ if (!(dec->pkthdrstreams = jpc_ppmstabtostreams(dec->ppmstab))) { abort(); } jpc_ppxstab_destroy(dec->ppmstab); dec->ppmstab = 0; } } if (sot->len > 0) { dec->curtileendoff = jas_stream_getrwcount(dec->in) - ms->len - 4 + sot->len; } else { dec->curtileendoff = 0; } if (JAS_CAST(int, sot->tileno) >= dec->numtiles) { jas_eprintf("invalid tile number in SOT marker segment\n"); return -1; } /* Set the current tile. */ dec->curtile = &dec->tiles[sot->tileno]; tile = dec->curtile; /* Ensure that this is the expected part number. */ if (sot->partno != tile->partno) { return -1; } if (tile->numparts > 0 && sot->partno >= tile->numparts) { return -1; } if (!tile->numparts && sot->numparts > 0) { tile->numparts = sot->numparts; } tile->pptstab = 0; switch (tile->state) { case JPC_TILE_INIT: /* This is the first tile-part for this tile. */ tile->state = JPC_TILE_ACTIVE; assert(!tile->cp); if (!(tile->cp = jpc_dec_cp_copy(dec->cp))) { return -1; } jpc_dec_cp_resetflags(dec->cp); break; default: if (sot->numparts == sot->partno - 1) { tile->state = JPC_TILE_ACTIVELAST; } break; } /* Note: We do not increment the expected tile-part number until all processing for this tile-part is complete. */ /* We should expect to encounter other tile-part header marker segments next. */ dec->state = JPC_TPH; return 0; } static int jpc_dec_process_sod(jpc_dec_t *dec, jpc_ms_t *ms) { jpc_dec_tile_t *tile; int pos; /* Eliminate compiler warnings about unused variables. */ ms = 0; if (!(tile = dec->curtile)) { return -1; } if (!tile->partno) { if (!jpc_dec_cp_isvalid(tile->cp)) { return -1; } jpc_dec_cp_prepare(tile->cp); if (jpc_dec_tileinit(dec, tile)) { return -1; } } /* Are packet headers stored in the main header or tile-part header? */ if (dec->pkthdrstreams) { /* Get the stream containing the packet header data for this tile-part. */ if (!(tile->pkthdrstream = jpc_streamlist_remove(dec->pkthdrstreams, 0))) { return -1; } } if (tile->pptstab) { if (!tile->pkthdrstream) { if (!(tile->pkthdrstream = jas_stream_memopen(0, 0))) { return -1; } } pos = jas_stream_tell(tile->pkthdrstream); jas_stream_seek(tile->pkthdrstream, 0, SEEK_END); if (jpc_pptstabwrite(tile->pkthdrstream, tile->pptstab)) { return -1; } jas_stream_seek(tile->pkthdrstream, pos, SEEK_SET); jpc_ppxstab_destroy(tile->pptstab); tile->pptstab = 0; } if (jas_getdbglevel() >= 10) { jpc_dec_dump(dec, stderr); } if (jpc_dec_decodepkts(dec, (tile->pkthdrstream) ? tile->pkthdrstream : dec->in, dec->in)) { jas_eprintf("jpc_dec_decodepkts failed\n"); return -1; } /* Gobble any unconsumed tile data. */ if (dec->curtileendoff > 0) { long curoff; uint_fast32_t n; curoff = jas_stream_getrwcount(dec->in); if (curoff < dec->curtileendoff) { n = dec->curtileendoff - curoff; jas_eprintf("warning: ignoring trailing garbage (%lu bytes)\n", (unsigned long) n); while (n-- > 0) { if (jas_stream_getc(dec->in) == EOF) { jas_eprintf("read error\n"); return -1; } } } else if (curoff > dec->curtileendoff) { jas_eprintf("warning: not enough tile data (%lu bytes)\n", (unsigned long) curoff - dec->curtileendoff); } } if (tile->numparts > 0 && tile->partno == tile->numparts - 1) { if (jpc_dec_tiledecode(dec, tile)) { return -1; } jpc_dec_tilefini(dec, tile); } dec->curtile = 0; /* Increment the expected tile-part number. */ ++tile->partno; /* We should expect to encounter a SOT marker segment next. */ dec->state = JPC_TPHSOT; return 0; } static int jpc_dec_tileinit(jpc_dec_t *dec, jpc_dec_tile_t *tile) { jpc_dec_tcomp_t *tcomp; int compno; int rlvlno; jpc_dec_rlvl_t *rlvl; jpc_dec_band_t *band; jpc_dec_prc_t *prc; int bndno; jpc_tsfb_band_t *bnd; int bandno; jpc_dec_ccp_t *ccp; int prccnt; jpc_dec_cblk_t *cblk; int cblkcnt; uint_fast32_t tlprcxstart; uint_fast32_t tlprcystart; uint_fast32_t brprcxend; uint_fast32_t brprcyend; uint_fast32_t tlcbgxstart; uint_fast32_t tlcbgystart; uint_fast32_t brcbgxend; uint_fast32_t brcbgyend; uint_fast32_t cbgxstart; uint_fast32_t cbgystart; uint_fast32_t cbgxend; uint_fast32_t cbgyend; uint_fast32_t tlcblkxstart; uint_fast32_t tlcblkystart; uint_fast32_t brcblkxend; uint_fast32_t brcblkyend; uint_fast32_t cblkxstart; uint_fast32_t cblkystart; uint_fast32_t cblkxend; uint_fast32_t cblkyend; uint_fast32_t tmpxstart; uint_fast32_t tmpystart; uint_fast32_t tmpxend; uint_fast32_t tmpyend; jpc_dec_cp_t *cp; jpc_tsfb_band_t bnds[JPC_MAXBANDS]; jpc_pchg_t *pchg; int pchgno; jpc_dec_cmpt_t *cmpt; cp = tile->cp; tile->realmode = 0; if (cp->mctid == JPC_MCT_ICT) { tile->realmode = 1; } for (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno < dec->numcomps; ++compno, ++tcomp, ++cmpt) { ccp = &tile->cp->ccps[compno]; if (ccp->qmfbid == JPC_COX_INS) { tile->realmode = 1; } tcomp->numrlvls = ccp->numrlvls; if (!(tcomp->rlvls = jas_alloc2(tcomp->numrlvls, sizeof(jpc_dec_rlvl_t)))) { return -1; } if (!(tcomp->data = jas_seq2d_create(JPC_CEILDIV(tile->xstart, cmpt->hstep), JPC_CEILDIV(tile->ystart, cmpt->vstep), JPC_CEILDIV(tile->xend, cmpt->hstep), JPC_CEILDIV(tile->yend, cmpt->vstep)))) { return -1; } if (!(tcomp->tsfb = jpc_cod_gettsfb(ccp->qmfbid, tcomp->numrlvls - 1))) { return -1; } { jpc_tsfb_getbands(tcomp->tsfb, jas_seq2d_xstart(tcomp->data), jas_seq2d_ystart(tcomp->data), jas_seq2d_xend(tcomp->data), jas_seq2d_yend(tcomp->data), bnds); } for (rlvlno = 0, rlvl = tcomp->rlvls; rlvlno < tcomp->numrlvls; ++rlvlno, ++rlvl) { rlvl->bands = 0; rlvl->xstart = JPC_CEILDIVPOW2(tcomp->xstart, tcomp->numrlvls - 1 - rlvlno); rlvl->ystart = JPC_CEILDIVPOW2(tcomp->ystart, tcomp->numrlvls - 1 - rlvlno); rlvl->xend = JPC_CEILDIVPOW2(tcomp->xend, tcomp->numrlvls - 1 - rlvlno); rlvl->yend = JPC_CEILDIVPOW2(tcomp->yend, tcomp->numrlvls - 1 - rlvlno); rlvl->prcwidthexpn = ccp->prcwidthexpns[rlvlno]; rlvl->prcheightexpn = ccp->prcheightexpns[rlvlno]; tlprcxstart = JPC_FLOORDIVPOW2(rlvl->xstart, rlvl->prcwidthexpn) << rlvl->prcwidthexpn; tlprcystart = JPC_FLOORDIVPOW2(rlvl->ystart, rlvl->prcheightexpn) << rlvl->prcheightexpn; brprcxend = JPC_CEILDIVPOW2(rlvl->xend, rlvl->prcwidthexpn) << rlvl->prcwidthexpn; brprcyend = JPC_CEILDIVPOW2(rlvl->yend, rlvl->prcheightexpn) << rlvl->prcheightexpn; rlvl->numhprcs = (brprcxend - tlprcxstart) >> rlvl->prcwidthexpn; rlvl->numvprcs = (brprcyend - tlprcystart) >> rlvl->prcheightexpn; rlvl->numprcs = rlvl->numhprcs * rlvl->numvprcs; if (rlvl->xstart >= rlvl->xend || rlvl->ystart >= rlvl->yend) { rlvl->bands = 0; rlvl->numprcs = 0; rlvl->numhprcs = 0; rlvl->numvprcs = 0; continue; } if (!rlvlno) { tlcbgxstart = tlprcxstart; tlcbgystart = tlprcystart; brcbgxend = brprcxend; brcbgyend = brprcyend; rlvl->cbgwidthexpn = rlvl->prcwidthexpn; rlvl->cbgheightexpn = rlvl->prcheightexpn; } else { tlcbgxstart = JPC_CEILDIVPOW2(tlprcxstart, 1); tlcbgystart = JPC_CEILDIVPOW2(tlprcystart, 1); brcbgxend = JPC_CEILDIVPOW2(brprcxend, 1); brcbgyend = JPC_CEILDIVPOW2(brprcyend, 1); rlvl->cbgwidthexpn = rlvl->prcwidthexpn - 1; rlvl->cbgheightexpn = rlvl->prcheightexpn - 1; } rlvl->cblkwidthexpn = JAS_MIN(ccp->cblkwidthexpn, rlvl->cbgwidthexpn); rlvl->cblkheightexpn = JAS_MIN(ccp->cblkheightexpn, rlvl->cbgheightexpn); rlvl->numbands = (!rlvlno) ? 1 : 3; if (!(rlvl->bands = jas_alloc2(rlvl->numbands, sizeof(jpc_dec_band_t)))) { return -1; } for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands; ++bandno, ++band) { bndno = (!rlvlno) ? 0 : (3 * (rlvlno - 1) + bandno + 1); bnd = &bnds[bndno]; band->orient = bnd->orient; band->stepsize = ccp->stepsizes[bndno]; band->analgain = JPC_NOMINALGAIN(ccp->qmfbid, tcomp->numrlvls - 1, rlvlno, band->orient); band->absstepsize = jpc_calcabsstepsize(band->stepsize, cmpt->prec + band->analgain); band->numbps = ccp->numguardbits + JPC_QCX_GETEXPN(band->stepsize) - 1; band->roishift = (ccp->roishift + band->numbps >= JPC_PREC) ? (JPC_PREC - 1 - band->numbps) : ccp->roishift; band->data = 0; band->prcs = 0; if (bnd->xstart == bnd->xend || bnd->ystart == bnd->yend) { continue; } if (!(band->data = jas_seq2d_create(0, 0, 0, 0))) { return -1; } jas_seq2d_bindsub(band->data, tcomp->data, bnd->locxstart, bnd->locystart, bnd->locxend, bnd->locyend); jas_seq2d_setshift(band->data, bnd->xstart, bnd->ystart); assert(rlvl->numprcs); if (!(band->prcs = jas_alloc2(rlvl->numprcs, sizeof(jpc_dec_prc_t)))) { return -1; } /************************************************/ cbgxstart = tlcbgxstart; cbgystart = tlcbgystart; for (prccnt = rlvl->numprcs, prc = band->prcs; prccnt > 0; --prccnt, ++prc) { cbgxend = cbgxstart + (1 << rlvl->cbgwidthexpn); cbgyend = cbgystart + (1 << rlvl->cbgheightexpn); prc->xstart = JAS_MAX(cbgxstart, JAS_CAST(uint_fast32_t, jas_seq2d_xstart(band->data))); prc->ystart = JAS_MAX(cbgystart, JAS_CAST(uint_fast32_t, jas_seq2d_ystart(band->data))); prc->xend = JAS_MIN(cbgxend, JAS_CAST(uint_fast32_t, jas_seq2d_xend(band->data))); prc->yend = JAS_MIN(cbgyend, JAS_CAST(uint_fast32_t, jas_seq2d_yend(band->data))); if (prc->xend > prc->xstart && prc->yend > prc->ystart) { tlcblkxstart = JPC_FLOORDIVPOW2(prc->xstart, rlvl->cblkwidthexpn) << rlvl->cblkwidthexpn; tlcblkystart = JPC_FLOORDIVPOW2(prc->ystart, rlvl->cblkheightexpn) << rlvl->cblkheightexpn; brcblkxend = JPC_CEILDIVPOW2(prc->xend, rlvl->cblkwidthexpn) << rlvl->cblkwidthexpn; brcblkyend = JPC_CEILDIVPOW2(prc->yend, rlvl->cblkheightexpn) << rlvl->cblkheightexpn; prc->numhcblks = (brcblkxend - tlcblkxstart) >> rlvl->cblkwidthexpn; prc->numvcblks = (brcblkyend - tlcblkystart) >> rlvl->cblkheightexpn; prc->numcblks = prc->numhcblks * prc->numvcblks; assert(prc->numcblks > 0); if (!(prc->incltagtree = jpc_tagtree_create( prc->numhcblks, prc->numvcblks))) { return -1; } if (!(prc->numimsbstagtree = jpc_tagtree_create( prc->numhcblks, prc->numvcblks))) { return -1; } if (!(prc->cblks = jas_alloc2(prc->numcblks, sizeof(jpc_dec_cblk_t)))) { return -1; } cblkxstart = cbgxstart; cblkystart = cbgystart; for (cblkcnt = prc->numcblks, cblk = prc->cblks; cblkcnt > 0;) { cblkxend = cblkxstart + (1 << rlvl->cblkwidthexpn); cblkyend = cblkystart + (1 << rlvl->cblkheightexpn); tmpxstart = JAS_MAX(cblkxstart, prc->xstart); tmpystart = JAS_MAX(cblkystart, prc->ystart); tmpxend = JAS_MIN(cblkxend, prc->xend); tmpyend = JAS_MIN(cblkyend, prc->yend); if (tmpxend > tmpxstart && tmpyend > tmpystart) { cblk->firstpassno = -1; cblk->mqdec = 0; cblk->nulldec = 0; cblk->flags = 0; cblk->numpasses = 0; cblk->segs.head = 0; cblk->segs.tail = 0; cblk->curseg = 0; cblk->numimsbs = 0; cblk->numlenbits = 3; cblk->flags = 0; if (!(cblk->data = jas_seq2d_create(0, 0, 0, 0))) { return -1; } jas_seq2d_bindsub(cblk->data, band->data, tmpxstart, tmpystart, tmpxend, tmpyend); ++cblk; --cblkcnt; } cblkxstart += 1 << rlvl->cblkwidthexpn; if (cblkxstart >= cbgxend) { cblkxstart = cbgxstart; cblkystart += 1 << rlvl->cblkheightexpn; } } } else { prc->cblks = 0; prc->incltagtree = 0; prc->numimsbstagtree = 0; } cbgxstart += 1 << rlvl->cbgwidthexpn; if (cbgxstart >= brcbgxend) { cbgxstart = tlcbgxstart; cbgystart += 1 << rlvl->cbgheightexpn; } } /********************************************/ } } } if (!(tile->pi = jpc_dec_pi_create(dec, tile))) { return -1; } for (pchgno = 0; pchgno < jpc_pchglist_numpchgs(tile->cp->pchglist); ++pchgno) { pchg = jpc_pchg_copy(jpc_pchglist_get(tile->cp->pchglist, pchgno)); assert(pchg); jpc_pi_addpchg(tile->pi, pchg); } jpc_pi_init(tile->pi); return 0; } static int jpc_dec_tilefini(jpc_dec_t *dec, jpc_dec_tile_t *tile) { jpc_dec_tcomp_t *tcomp; int compno; int bandno; int rlvlno; jpc_dec_band_t *band; jpc_dec_rlvl_t *rlvl; int prcno; jpc_dec_prc_t *prc; jpc_dec_seg_t *seg; jpc_dec_cblk_t *cblk; int cblkno; if (tile->tcomps) { for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps; ++compno, ++tcomp) { for (rlvlno = 0, rlvl = tcomp->rlvls; rlvlno < tcomp->numrlvls; ++rlvlno, ++rlvl) { if (!rlvl->bands) { continue; } for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands; ++bandno, ++band) { if (band->prcs) { for (prcno = 0, prc = band->prcs; prcno < rlvl->numprcs; ++prcno, ++prc) { if (!prc->cblks) { continue; } for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks; ++cblkno, ++cblk) { while (cblk->segs.head) { seg = cblk->segs.head; jpc_seglist_remove(&cblk->segs, seg); jpc_seg_destroy(seg); } jas_matrix_destroy(cblk->data); if (cblk->mqdec) { jpc_mqdec_destroy(cblk->mqdec); } if (cblk->nulldec) { jpc_bitstream_close(cblk->nulldec); } if (cblk->flags) { jas_matrix_destroy(cblk->flags); } } if (prc->incltagtree) { jpc_tagtree_destroy(prc->incltagtree); } if (prc->numimsbstagtree) { jpc_tagtree_destroy(prc->numimsbstagtree); } if (prc->cblks) { jas_free(prc->cblks); } } } if (band->data) { jas_matrix_destroy(band->data); } if (band->prcs) { jas_free(band->prcs); } } if (rlvl->bands) { jas_free(rlvl->bands); } } if (tcomp->rlvls) { jas_free(tcomp->rlvls); } if (tcomp->data) { jas_matrix_destroy(tcomp->data); } if (tcomp->tsfb) { jpc_tsfb_destroy(tcomp->tsfb); } } } if (tile->cp) { jpc_dec_cp_destroy(tile->cp); //tile->cp = 0; } if (tile->tcomps) { jas_free(tile->tcomps); //tile->tcomps = 0; } if (tile->pi) { jpc_pi_destroy(tile->pi); //tile->pi = 0; } if (tile->pkthdrstream) { jas_stream_close(tile->pkthdrstream); //tile->pkthdrstream = 0; } if (tile->pptstab) { jpc_ppxstab_destroy(tile->pptstab); //tile->pptstab = 0; } tile->state = JPC_TILE_DONE; return 0; } static int jpc_dec_tiledecode(jpc_dec_t *dec, jpc_dec_tile_t *tile) { int i; int j; jpc_dec_tcomp_t *tcomp; jpc_dec_rlvl_t *rlvl; jpc_dec_band_t *band; int compno; int rlvlno; int bandno; int adjust; int v; jpc_dec_ccp_t *ccp; jpc_dec_cmpt_t *cmpt; if (jpc_dec_decodecblks(dec, tile)) { jas_eprintf("jpc_dec_decodecblks failed\n"); return -1; } /* Perform dequantization. */ for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps; ++compno, ++tcomp) { ccp = &tile->cp->ccps[compno]; for (rlvlno = 0, rlvl = tcomp->rlvls; rlvlno < tcomp->numrlvls; ++rlvlno, ++rlvl) { if (!rlvl->bands) { continue; } for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands; ++bandno, ++band) { if (!band->data) { continue; } jpc_undo_roi(band->data, band->roishift, ccp->roishift - band->roishift, band->numbps); if (tile->realmode) { jas_matrix_asl(band->data, JPC_FIX_FRACBITS); jpc_dequantize(band->data, band->absstepsize); } } } } /* Apply an inverse wavelet transform if necessary. */ for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps; ++compno, ++tcomp) { ccp = &tile->cp->ccps[compno]; jpc_tsfb_synthesize(tcomp->tsfb, tcomp->data); } /* Apply an inverse intercomponent transform if necessary. */ switch (tile->cp->mctid) { case JPC_MCT_RCT: if (dec->numcomps < 3) { jas_eprintf("RCT requires at least three components\n"); return -1; } if (!jas_image_cmpt_domains_same(dec->image)) { jas_eprintf("RCT requires all components have the same domain\n"); return -1; } jpc_irct(tile->tcomps[0].data, tile->tcomps[1].data, tile->tcomps[2].data); break; case JPC_MCT_ICT: if (dec->numcomps < 3) { jas_eprintf("ICT requires at least three components\n"); return -1; } if (!jas_image_cmpt_domains_same(dec->image)) { jas_eprintf("RCT requires all components have the same domain\n"); return -1; } jpc_iict(tile->tcomps[0].data, tile->tcomps[1].data, tile->tcomps[2].data); break; } /* Perform rounding and convert to integer values. */ if (tile->realmode) { for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps; ++compno, ++tcomp) { for (i = 0; i < jas_matrix_numrows(tcomp->data); ++i) { for (j = 0; j < jas_matrix_numcols(tcomp->data); ++j) { v = jas_matrix_get(tcomp->data, i, j); v = jpc_fix_round(v); jas_matrix_set(tcomp->data, i, j, jpc_fixtoint(v)); } } } } /* Perform level shift. */ for (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno < dec->numcomps; ++compno, ++tcomp, ++cmpt) { adjust = cmpt->sgnd ? 0 : (1 << (cmpt->prec - 1)); for (i = 0; i < jas_matrix_numrows(tcomp->data); ++i) { for (j = 0; j < jas_matrix_numcols(tcomp->data); ++j) { *jas_matrix_getref(tcomp->data, i, j) += adjust; } } } /* Perform clipping. */ for (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno < dec->numcomps; ++compno, ++tcomp, ++cmpt) { jpc_fix_t mn; jpc_fix_t mx; mn = cmpt->sgnd ? (-(1 << (cmpt->prec - 1))) : (0); mx = cmpt->sgnd ? ((1 << (cmpt->prec - 1)) - 1) : ((1 << cmpt->prec) - 1); jas_matrix_clip(tcomp->data, mn, mx); } /* XXX need to free tsfb struct */ /* Write the data for each component of the image. */ for (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno < dec->numcomps; ++compno, ++tcomp, ++cmpt) { if (jas_image_writecmpt(dec->image, compno, tcomp->xstart - JPC_CEILDIV(dec->xstart, cmpt->hstep), tcomp->ystart - JPC_CEILDIV(dec->ystart, cmpt->vstep), jas_matrix_numcols( tcomp->data), jas_matrix_numrows(tcomp->data), tcomp->data)) { jas_eprintf("write component failed\n"); return -1; } } return 0; } static int jpc_dec_process_eoc(jpc_dec_t *dec, jpc_ms_t *ms) { int tileno; jpc_dec_tile_t *tile; /* Eliminate compiler warnings about unused variables. */ ms = 0; for (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno, ++tile) { if (tile->state == JPC_TILE_ACTIVE) { if (jpc_dec_tiledecode(dec, tile)) { return -1; } } /* If the tile has not yet been finalized, finalize it. */ // OLD CODE: jpc_dec_tilefini(dec, tile); if (tile->state != JPC_TILE_DONE) { jpc_dec_tilefini(dec, tile); } } /* We are done processing the code stream. */ dec->state = JPC_MT; return 1; } static int jpc_dec_process_siz(jpc_dec_t *dec, jpc_ms_t *ms) { jpc_siz_t *siz = &ms->parms.siz; int compno; int tileno; jpc_dec_tile_t *tile; jpc_dec_tcomp_t *tcomp; int htileno; int vtileno; jpc_dec_cmpt_t *cmpt; size_t size; size_t num_samples; size_t num_samples_delta; dec->xstart = siz->xoff; dec->ystart = siz->yoff; dec->xend = siz->width; dec->yend = siz->height; dec->tilewidth = siz->tilewidth; dec->tileheight = siz->tileheight; dec->tilexoff = siz->tilexoff; dec->tileyoff = siz->tileyoff; dec->numcomps = siz->numcomps; if (!(dec->cp = jpc_dec_cp_create(dec->numcomps))) { return -1; } if (!(dec->cmpts = jas_alloc2(dec->numcomps, sizeof(jpc_dec_cmpt_t)))) { return -1; } num_samples = 0; for (compno = 0, cmpt = dec->cmpts; compno < dec->numcomps; ++compno, ++cmpt) { cmpt->prec = siz->comps[compno].prec; cmpt->sgnd = siz->comps[compno].sgnd; cmpt->hstep = siz->comps[compno].hsamp; cmpt->vstep = siz->comps[compno].vsamp; cmpt->width = JPC_CEILDIV(dec->xend, cmpt->hstep) - JPC_CEILDIV(dec->xstart, cmpt->hstep); cmpt->height = JPC_CEILDIV(dec->yend, cmpt->vstep) - JPC_CEILDIV(dec->ystart, cmpt->vstep); cmpt->hsubstep = 0; cmpt->vsubstep = 0; if (!jas_safe_size_mul(cmpt->width, cmpt->height, &num_samples_delta)) { jas_eprintf("image too large\n"); return -1; } if (!jas_safe_size_add(num_samples, num_samples_delta, &num_samples)) { jas_eprintf("image too large\n"); } } if (dec->max_samples > 0 && num_samples > dec->max_samples) { jas_eprintf("maximum number of samples exceeded (%zu > %zu)\n", num_samples, dec->max_samples); return -1; } dec->image = 0; dec->numhtiles = JPC_CEILDIV(dec->xend - dec->tilexoff, dec->tilewidth); dec->numvtiles = JPC_CEILDIV(dec->yend - dec->tileyoff, dec->tileheight); if (!jas_safe_size_mul(dec->numhtiles, dec->numvtiles, &size)) { return -1; } dec->numtiles = size; JAS_DBGLOG(10, ("numtiles = %d; numhtiles = %d; numvtiles = %d;\n", dec->numtiles, dec->numhtiles, dec->numvtiles)); if (!(dec->tiles = jas_alloc2(dec->numtiles, sizeof(jpc_dec_tile_t)))) { return -1; } for (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno, ++tile) { htileno = tileno % dec->numhtiles; vtileno = tileno / dec->numhtiles; tile->realmode = 0; tile->state = JPC_TILE_INIT; tile->xstart = JAS_MAX(dec->tilexoff + htileno * dec->tilewidth, dec->xstart); tile->ystart = JAS_MAX(dec->tileyoff + vtileno * dec->tileheight, dec->ystart); tile->xend = JAS_MIN(dec->tilexoff + (htileno + 1) * dec->tilewidth, dec->xend); tile->yend = JAS_MIN(dec->tileyoff + (vtileno + 1) * dec->tileheight, dec->yend); tile->numparts = 0; tile->partno = 0; tile->pkthdrstream = 0; tile->pkthdrstreampos = 0; tile->pptstab = 0; tile->cp = 0; tile->pi = 0; if (!(tile->tcomps = jas_alloc2(dec->numcomps, sizeof(jpc_dec_tcomp_t)))) { return -1; } for (compno = 0, cmpt = dec->cmpts, tcomp = tile->tcomps; compno < dec->numcomps; ++compno, ++cmpt, ++tcomp) { tcomp->rlvls = 0; tcomp->numrlvls = 0; tcomp->data = 0; tcomp->xstart = JPC_CEILDIV(tile->xstart, cmpt->hstep); tcomp->ystart = JPC_CEILDIV(tile->ystart, cmpt->vstep); tcomp->xend = JPC_CEILDIV(tile->xend, cmpt->hstep); tcomp->yend = JPC_CEILDIV(tile->yend, cmpt->vstep); tcomp->tsfb = 0; } } dec->pkthdrstreams = 0; /* We should expect to encounter other main header marker segments or an SOT marker segment next. */ dec->state = JPC_MH; return 0; } static int jpc_dec_process_cod(jpc_dec_t *dec, jpc_ms_t *ms) { jpc_cod_t *cod = &ms->parms.cod; jpc_dec_tile_t *tile; switch (dec->state) { case JPC_MH: jpc_dec_cp_setfromcod(dec->cp, cod); break; case JPC_TPH: if (!(tile = dec->curtile)) { return -1; } if (tile->partno != 0) { return -1; } jpc_dec_cp_setfromcod(tile->cp, cod); break; } return 0; } static int jpc_dec_process_coc(jpc_dec_t *dec, jpc_ms_t *ms) { jpc_coc_t *coc = &ms->parms.coc; jpc_dec_tile_t *tile; if (JAS_CAST(int, coc->compno) >= dec->numcomps) { jas_eprintf("invalid component number in COC marker segment\n"); return -1; } switch (dec->state) { case JPC_MH: jpc_dec_cp_setfromcoc(dec->cp, coc); break; case JPC_TPH: if (!(tile = dec->curtile)) { return -1; } if (tile->partno > 0) { return -1; } jpc_dec_cp_setfromcoc(tile->cp, coc); break; } return 0; } static int jpc_dec_process_rgn(jpc_dec_t *dec, jpc_ms_t *ms) { jpc_rgn_t *rgn = &ms->parms.rgn; jpc_dec_tile_t *tile; if (JAS_CAST(int, rgn->compno) >= dec->numcomps) { jas_eprintf("invalid component number in RGN marker segment\n"); return -1; } switch (dec->state) { case JPC_MH: jpc_dec_cp_setfromrgn(dec->cp, rgn); break; case JPC_TPH: if (!(tile = dec->curtile)) { return -1; } if (tile->partno > 0) { return -1; } jpc_dec_cp_setfromrgn(tile->cp, rgn); break; } return 0; } static int jpc_dec_process_qcd(jpc_dec_t *dec, jpc_ms_t *ms) { jpc_qcd_t *qcd = &ms->parms.qcd; jpc_dec_tile_t *tile; switch (dec->state) { case JPC_MH: jpc_dec_cp_setfromqcd(dec->cp, qcd); break; case JPC_TPH: if (!(tile = dec->curtile)) { return -1; } if (tile->partno > 0) { return -1; } jpc_dec_cp_setfromqcd(tile->cp, qcd); break; } return 0; } static int jpc_dec_process_qcc(jpc_dec_t *dec, jpc_ms_t *ms) { jpc_qcc_t *qcc = &ms->parms.qcc; jpc_dec_tile_t *tile; if (JAS_CAST(int, qcc->compno) >= dec->numcomps) { jas_eprintf("invalid component number in QCC marker segment\n"); return -1; } switch (dec->state) { case JPC_MH: jpc_dec_cp_setfromqcc(dec->cp, qcc); break; case JPC_TPH: if (!(tile = dec->curtile)) { return -1; } if (tile->partno > 0) { return -1; } jpc_dec_cp_setfromqcc(tile->cp, qcc); break; } return 0; } static int jpc_dec_process_poc(jpc_dec_t *dec, jpc_ms_t *ms) { jpc_poc_t *poc = &ms->parms.poc; jpc_dec_tile_t *tile; switch (dec->state) { case JPC_MH: if (jpc_dec_cp_setfrompoc(dec->cp, poc, 1)) { return -1; } break; case JPC_TPH: if (!(tile = dec->curtile)) { return -1; } if (!tile->partno) { if (jpc_dec_cp_setfrompoc(tile->cp, poc, (!tile->partno))) { return -1; } } else { jpc_pi_addpchgfrompoc(tile->pi, poc); } break; } return 0; } static int jpc_dec_process_ppm(jpc_dec_t *dec, jpc_ms_t *ms) { jpc_ppm_t *ppm = &ms->parms.ppm; jpc_ppxstabent_t *ppmstabent; if (!dec->ppmstab) { if (!(dec->ppmstab = jpc_ppxstab_create())) { return -1; } } if (!(ppmstabent = jpc_ppxstabent_create())) { return -1; } ppmstabent->ind = ppm->ind; ppmstabent->data = ppm->data; ppm->data = 0; ppmstabent->len = ppm->len; if (jpc_ppxstab_insert(dec->ppmstab, ppmstabent)) { return -1; } return 0; } static int jpc_dec_process_ppt(jpc_dec_t *dec, jpc_ms_t *ms) { jpc_ppt_t *ppt = &ms->parms.ppt; jpc_dec_tile_t *tile; jpc_ppxstabent_t *pptstabent; tile = dec->curtile; if (!tile->pptstab) { if (!(tile->pptstab = jpc_ppxstab_create())) { return -1; } } if (!(pptstabent = jpc_ppxstabent_create())) { return -1; } pptstabent->ind = ppt->ind; pptstabent->data = ppt->data; ppt->data = 0; pptstabent->len = ppt->len; if (jpc_ppxstab_insert(tile->pptstab, pptstabent)) { return -1; } return 0; } static int jpc_dec_process_com(jpc_dec_t *dec, jpc_ms_t *ms) { /* Eliminate compiler warnings about unused variables. */ dec = 0; ms = 0; return 0; } static int jpc_dec_process_unk(jpc_dec_t *dec, jpc_ms_t *ms) { /* Eliminate compiler warnings about unused variables. */ dec = 0; jas_eprintf("warning: ignoring unknown marker segment (0x%x)\n", ms->id); jpc_ms_dump(ms, stderr); return 0; } /******************************************************************************\ * \******************************************************************************/ static jpc_dec_cp_t *jpc_dec_cp_create(uint_fast16_t numcomps) { jpc_dec_cp_t *cp; jpc_dec_ccp_t *ccp; int compno; if (!(cp = jas_malloc(sizeof(jpc_dec_cp_t)))) { return 0; } cp->flags = 0; cp->numcomps = numcomps; cp->prgord = 0; cp->numlyrs = 0; cp->mctid = 0; cp->csty = 0; if (!(cp->ccps = jas_alloc2(cp->numcomps, sizeof(jpc_dec_ccp_t)))) { goto error; } if (!(cp->pchglist = jpc_pchglist_create())) { goto error; } for (compno = 0, ccp = cp->ccps; compno < cp->numcomps; ++compno, ++ccp) { ccp->flags = 0; ccp->numrlvls = 0; ccp->cblkwidthexpn = 0; ccp->cblkheightexpn = 0; ccp->qmfbid = 0; ccp->numstepsizes = 0; ccp->numguardbits = 0; ccp->roishift = 0; ccp->cblkctx = 0; } return cp; error: if (cp) { jpc_dec_cp_destroy(cp); } return 0; } static jpc_dec_cp_t *jpc_dec_cp_copy(jpc_dec_cp_t *cp) { jpc_dec_cp_t *newcp; jpc_dec_ccp_t *newccp; jpc_dec_ccp_t *ccp; int compno; if (!(newcp = jpc_dec_cp_create(cp->numcomps))) { return 0; } newcp->flags = cp->flags; newcp->prgord = cp->prgord; newcp->numlyrs = cp->numlyrs; newcp->mctid = cp->mctid; newcp->csty = cp->csty; jpc_pchglist_destroy(newcp->pchglist); newcp->pchglist = 0; if (!(newcp->pchglist = jpc_pchglist_copy(cp->pchglist))) { jas_free(newcp); return 0; } for (compno = 0, newccp = newcp->ccps, ccp = cp->ccps; compno < cp->numcomps; ++compno, ++newccp, ++ccp) { *newccp = *ccp; } return newcp; } static void jpc_dec_cp_resetflags(jpc_dec_cp_t *cp) { int compno; jpc_dec_ccp_t *ccp; cp->flags &= (JPC_CSET | JPC_QSET); for (compno = 0, ccp = cp->ccps; compno < cp->numcomps; ++compno, ++ccp) { ccp->flags = 0; } } static void jpc_dec_cp_destroy(jpc_dec_cp_t *cp) { if (cp->ccps) { jas_free(cp->ccps); } if (cp->pchglist) { jpc_pchglist_destroy(cp->pchglist); } jas_free(cp); } static int jpc_dec_cp_isvalid(jpc_dec_cp_t *cp) { uint_fast16_t compcnt; jpc_dec_ccp_t *ccp; if (!(cp->flags & JPC_CSET) || !(cp->flags & JPC_QSET)) { return 0; } for (compcnt = cp->numcomps, ccp = cp->ccps; compcnt > 0; --compcnt, ++ccp) { /* Is there enough step sizes for the number of bands? */ if ((ccp->qsty != JPC_QCX_SIQNT && JAS_CAST(int, ccp->numstepsizes) < 3 * ccp->numrlvls - 2) || (ccp->qsty == JPC_QCX_SIQNT && ccp->numstepsizes != 1)) { return 0; } } return 1; } static void calcstepsizes(uint_fast16_t refstepsize, int numrlvls, uint_fast16_t *stepsizes) { int bandno; int numbands; uint_fast16_t expn; uint_fast16_t mant; expn = JPC_QCX_GETEXPN(refstepsize); mant = JPC_QCX_GETMANT(refstepsize); numbands = 3 * numrlvls - 2; for (bandno = 0; bandno < numbands; ++bandno) { //jas_eprintf("DEBUG %d %d %d %d %d\n", bandno, expn, numrlvls, bandno, ((numrlvls - 1) - (numrlvls - 1 - ((bandno > 0) ? ((bandno + 2) / 3) : (0))))); stepsizes[bandno] = JPC_QCX_MANT(mant) | JPC_QCX_EXPN(expn + (numrlvls - 1) - (numrlvls - 1 - ((bandno > 0) ? ((bandno + 2) / 3) : (0)))); } } static int jpc_dec_cp_prepare(jpc_dec_cp_t *cp) { jpc_dec_ccp_t *ccp; int compno; int i; for (compno = 0, ccp = cp->ccps; compno < cp->numcomps; ++compno, ++ccp) { if (!(ccp->csty & JPC_COX_PRT)) { for (i = 0; i < JPC_MAXRLVLS; ++i) { ccp->prcwidthexpns[i] = 15; ccp->prcheightexpns[i] = 15; } } if (ccp->qsty == JPC_QCX_SIQNT) { calcstepsizes(ccp->stepsizes[0], ccp->numrlvls, ccp->stepsizes); } } return 0; } static int jpc_dec_cp_setfromcod(jpc_dec_cp_t *cp, jpc_cod_t *cod) { jpc_dec_ccp_t *ccp; int compno; cp->flags |= JPC_CSET; cp->prgord = cod->prg; if (cod->mctrans) { cp->mctid = (cod->compparms.qmfbid == JPC_COX_INS) ? (JPC_MCT_ICT) : (JPC_MCT_RCT); } else { cp->mctid = JPC_MCT_NONE; } cp->numlyrs = cod->numlyrs; cp->csty = cod->csty & (JPC_COD_SOP | JPC_COD_EPH); for (compno = 0, ccp = cp->ccps; compno < cp->numcomps; ++compno, ++ccp) { jpc_dec_cp_setfromcox(cp, ccp, &cod->compparms, 0); } cp->flags |= JPC_CSET; return 0; } static int jpc_dec_cp_setfromcoc(jpc_dec_cp_t *cp, jpc_coc_t *coc) { jpc_dec_cp_setfromcox(cp, &cp->ccps[coc->compno], &coc->compparms, JPC_COC); return 0; } static int jpc_dec_cp_setfromcox(jpc_dec_cp_t *cp, jpc_dec_ccp_t *ccp, jpc_coxcp_t *compparms, int flags) { int rlvlno; /* Eliminate compiler warnings about unused variables. */ cp = 0; if ((flags & JPC_COC) || !(ccp->flags & JPC_COC)) { ccp->numrlvls = compparms->numdlvls + 1; ccp->cblkwidthexpn = JPC_COX_GETCBLKSIZEEXPN( compparms->cblkwidthval); ccp->cblkheightexpn = JPC_COX_GETCBLKSIZEEXPN( compparms->cblkheightval); ccp->qmfbid = compparms->qmfbid; ccp->cblkctx = compparms->cblksty; ccp->csty = compparms->csty & JPC_COX_PRT; for (rlvlno = 0; rlvlno < compparms->numrlvls; ++rlvlno) { ccp->prcwidthexpns[rlvlno] = compparms->rlvls[rlvlno].parwidthval; ccp->prcheightexpns[rlvlno] = compparms->rlvls[rlvlno].parheightval; } ccp->flags |= flags | JPC_CSET; } return 0; } static int jpc_dec_cp_setfromqcd(jpc_dec_cp_t *cp, jpc_qcd_t *qcd) { int compno; jpc_dec_ccp_t *ccp; for (compno = 0, ccp = cp->ccps; compno < cp->numcomps; ++compno, ++ccp) { jpc_dec_cp_setfromqcx(cp, ccp, &qcd->compparms, 0); } cp->flags |= JPC_QSET; return 0; } static int jpc_dec_cp_setfromqcc(jpc_dec_cp_t *cp, jpc_qcc_t *qcc) { return jpc_dec_cp_setfromqcx(cp, &cp->ccps[qcc->compno], &qcc->compparms, JPC_QCC); } static int jpc_dec_cp_setfromqcx(jpc_dec_cp_t *cp, jpc_dec_ccp_t *ccp, jpc_qcxcp_t *compparms, int flags) { int bandno; /* Eliminate compiler warnings about unused variables. */ cp = 0; if ((flags & JPC_QCC) || !(ccp->flags & JPC_QCC)) { ccp->flags |= flags | JPC_QSET; for (bandno = 0; bandno < compparms->numstepsizes; ++bandno) { ccp->stepsizes[bandno] = compparms->stepsizes[bandno]; } ccp->numstepsizes = compparms->numstepsizes; ccp->numguardbits = compparms->numguard; ccp->qsty = compparms->qntsty; } return 0; } static int jpc_dec_cp_setfromrgn(jpc_dec_cp_t *cp, jpc_rgn_t *rgn) { jpc_dec_ccp_t *ccp; ccp = &cp->ccps[rgn->compno]; ccp->roishift = rgn->roishift; return 0; } static int jpc_pi_addpchgfrompoc(jpc_pi_t *pi, jpc_poc_t *poc) { int pchgno; jpc_pchg_t *pchg; for (pchgno = 0; pchgno < poc->numpchgs; ++pchgno) { if (!(pchg = jpc_pchg_copy(&poc->pchgs[pchgno]))) { return -1; } if (jpc_pchglist_insert(pi->pchglist, -1, pchg)) { return -1; } } return 0; } static int jpc_dec_cp_setfrompoc(jpc_dec_cp_t *cp, jpc_poc_t *poc, int reset) { int pchgno; jpc_pchg_t *pchg; if (reset) { while (jpc_pchglist_numpchgs(cp->pchglist) > 0) { pchg = jpc_pchglist_remove(cp->pchglist, 0); jpc_pchg_destroy(pchg); } } for (pchgno = 0; pchgno < poc->numpchgs; ++pchgno) { if (!(pchg = jpc_pchg_copy(&poc->pchgs[pchgno]))) { return -1; } if (jpc_pchglist_insert(cp->pchglist, -1, pchg)) { return -1; } } return 0; } static jpc_fix_t jpc_calcabsstepsize(int stepsize, int numbits) { jpc_fix_t absstepsize; int n; absstepsize = jpc_inttofix(1); n = JPC_FIX_FRACBITS - 11; absstepsize |= (n >= 0) ? (JPC_QCX_GETMANT(stepsize) << n) : (JPC_QCX_GETMANT(stepsize) >> (-n)); n = numbits - JPC_QCX_GETEXPN(stepsize); absstepsize = (n >= 0) ? (absstepsize << n) : (absstepsize >> (-n)); return absstepsize; } static void jpc_dequantize(jas_matrix_t *x, jpc_fix_t absstepsize) { int i; int j; int t; assert(absstepsize >= 0); if (absstepsize == jpc_inttofix(1)) { return; } for (i = 0; i < jas_matrix_numrows(x); ++i) { for (j = 0; j < jas_matrix_numcols(x); ++j) { t = jas_matrix_get(x, i, j); if (t) { t = jpc_fix_mul(t, absstepsize); } else { t = 0; } jas_matrix_set(x, i, j, t); } } } static void jpc_undo_roi(jas_matrix_t *x, int roishift, int bgshift, int numbps) { int i; int j; int thresh; jpc_fix_t val; jpc_fix_t mag; bool warn; uint_fast32_t mask; if (roishift < 0) { /* We could instead return an error here. */ /* I do not think it matters much. */ jas_eprintf("warning: forcing negative ROI shift to zero " "(bitstream is probably corrupt)\n"); roishift = 0; } if (roishift == 0 && bgshift == 0) { return; } thresh = 1 << roishift; warn = false; for (i = 0; i < jas_matrix_numrows(x); ++i) { for (j = 0; j < jas_matrix_numcols(x); ++j) { val = jas_matrix_get(x, i, j); mag = JAS_ABS(val); if (mag >= thresh) { /* We are dealing with ROI data. */ mag >>= roishift; val = (val < 0) ? (-mag) : mag; jas_matrix_set(x, i, j, val); } else { /* We are dealing with non-ROI (i.e., background) data. */ mag <<= bgshift; mask = (JAS_CAST(uint_fast32_t, 1) << numbps) - 1; /* Perform a basic sanity check on the sample value. */ /* Some implementations write garbage in the unused most-significant bit planes introduced by ROI shifting. Here we ensure that any such bits are masked off. */ if (mag & (~mask)) { if (!warn) { jas_eprintf("warning: possibly corrupt code stream\n"); warn = true; } mag &= mask; } val = (val < 0) ? (-mag) : mag; jas_matrix_set(x, i, j, val); } } } } static jpc_dec_t *jpc_dec_create(jpc_dec_importopts_t *impopts, jas_stream_t *in) { jpc_dec_t *dec; if (!(dec = jas_malloc(sizeof(jpc_dec_t)))) { return 0; } dec->image = 0; dec->xstart = 0; dec->ystart = 0; dec->xend = 0; dec->yend = 0; dec->tilewidth = 0; dec->tileheight = 0; dec->tilexoff = 0; dec->tileyoff = 0; dec->numhtiles = 0; dec->numvtiles = 0; dec->numtiles = 0; dec->tiles = 0; dec->curtile = 0; dec->numcomps = 0; dec->in = in; dec->cp = 0; dec->maxlyrs = impopts->maxlyrs; dec->maxpkts = impopts->maxpkts; dec->numpkts = 0; dec->ppmseqno = 0; dec->state = 0; dec->cmpts = 0; dec->pkthdrstreams = 0; dec->ppmstab = 0; dec->curtileendoff = 0; dec->max_samples = impopts->max_samples; return dec; } static void jpc_dec_destroy(jpc_dec_t *dec) { if (dec->cstate) { jpc_cstate_destroy(dec->cstate); } if (dec->pkthdrstreams) { jpc_streamlist_destroy(dec->pkthdrstreams); } if (dec->image) { jas_image_destroy(dec->image); } if (dec->cp) { jpc_dec_cp_destroy(dec->cp); } if (dec->cmpts) { jas_free(dec->cmpts); } if (dec->tiles) { jas_free(dec->tiles); } jas_free(dec); } /******************************************************************************\ * \******************************************************************************/ void jpc_seglist_insert(jpc_dec_seglist_t *list, jpc_dec_seg_t *ins, jpc_dec_seg_t *node) { jpc_dec_seg_t *prev; jpc_dec_seg_t *next; prev = ins; node->prev = prev; next = prev ? (prev->next) : 0; node->prev = prev; node->next = next; if (prev) { prev->next = node; } else { list->head = node; } if (next) { next->prev = node; } else { list->tail = node; } } void jpc_seglist_remove(jpc_dec_seglist_t *list, jpc_dec_seg_t *seg) { jpc_dec_seg_t *prev; jpc_dec_seg_t *next; prev = seg->prev; next = seg->next; if (prev) { prev->next = next; } else { list->head = next; } if (next) { next->prev = prev; } else { list->tail = prev; } seg->prev = 0; seg->next = 0; } jpc_dec_seg_t *jpc_seg_alloc() { jpc_dec_seg_t *seg; if (!(seg = jas_malloc(sizeof(jpc_dec_seg_t)))) { return 0; } seg->prev = 0; seg->next = 0; seg->passno = -1; seg->numpasses = 0; seg->maxpasses = 0; seg->type = JPC_SEG_INVALID; seg->stream = 0; seg->cnt = 0; seg->complete = 0; seg->lyrno = -1; return seg; } void jpc_seg_destroy(jpc_dec_seg_t *seg) { if (seg->stream) { jas_stream_close(seg->stream); } jas_free(seg); } static int jpc_dec_dump(jpc_dec_t *dec, FILE *out) { jpc_dec_tile_t *tile; int tileno; jpc_dec_tcomp_t *tcomp; int compno; jpc_dec_rlvl_t *rlvl; int rlvlno; jpc_dec_band_t *band; int bandno; jpc_dec_prc_t *prc; int prcno; jpc_dec_cblk_t *cblk; int cblkno; assert(!dec->numtiles || dec->tiles); for (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno, ++tile) { assert(!dec->numcomps || tile->tcomps); for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps; ++compno, ++tcomp) { for (rlvlno = 0, rlvl = tcomp->rlvls; rlvlno < tcomp->numrlvls; ++rlvlno, ++rlvl) { fprintf(out, "RESOLUTION LEVEL %d\n", rlvlno); fprintf(out, "xs = %"PRIuFAST32", ys = %"PRIuFAST32", xe = %"PRIuFAST32", ye = %"PRIuFAST32", w = %"PRIuFAST32", h = %"PRIuFAST32"\n", rlvl->xstart, rlvl->ystart, rlvl->xend, rlvl->yend, rlvl->xend - rlvl->xstart, rlvl->yend - rlvl->ystart); assert(!rlvl->numbands || rlvl->bands); for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands; ++bandno, ++band) { fprintf(out, "BAND %d\n", bandno); if (!band->data) { fprintf(out, "band has no data (null pointer)\n"); assert(!band->prcs); continue; } fprintf(out, "xs = %"PRIiFAST32", ys = %"PRIiFAST32", xe = %"PRIiFAST32", ye = %"PRIiFAST32", w = %"PRIiFAST32", h = %"PRIiFAST32"\n", jas_seq2d_xstart(band->data), jas_seq2d_ystart(band->data), jas_seq2d_xend(band->data), jas_seq2d_yend(band->data), jas_seq2d_xend(band->data) - jas_seq2d_xstart(band->data), jas_seq2d_yend(band->data) - jas_seq2d_ystart(band->data)); assert(!rlvl->numprcs || band->prcs); for (prcno = 0, prc = band->prcs; prcno < rlvl->numprcs; ++prcno, ++prc) { fprintf(out, "CODE BLOCK GROUP %d\n", prcno); fprintf(out, "xs = %"PRIuFAST32", ys = %"PRIuFAST32", xe = %"PRIuFAST32", ye = %"PRIuFAST32", w = %"PRIuFAST32", h = %"PRIuFAST32"\n", prc->xstart, prc->ystart, prc->xend, prc->yend, prc->xend - prc->xstart, prc->yend - prc->ystart); assert(!prc->numcblks || prc->cblks); for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks; ++cblkno, ++cblk) { fprintf(out, "CODE BLOCK %d\n", cblkno); fprintf(out, "xs = %"PRIiFAST32", ys = %"PRIiFAST32", xe = %"PRIiFAST32", ye = %"PRIiFAST32", w = %"PRIiFAST32", h = %"PRIiFAST32"\n", jas_seq2d_xstart(cblk->data), jas_seq2d_ystart(cblk->data), jas_seq2d_xend(cblk->data), jas_seq2d_yend(cblk->data), jas_seq2d_xend(cblk->data) - jas_seq2d_xstart(cblk->data), jas_seq2d_yend(cblk->data) - jas_seq2d_ystart(cblk->data)); } } } } } } return 0; } jpc_streamlist_t *jpc_streamlist_create() { jpc_streamlist_t *streamlist; int i; if (!(streamlist = jas_malloc(sizeof(jpc_streamlist_t)))) { return 0; } streamlist->numstreams = 0; streamlist->maxstreams = 100; if (!(streamlist->streams = jas_alloc2(streamlist->maxstreams, sizeof(jas_stream_t *)))) { jas_free(streamlist); return 0; } for (i = 0; i < streamlist->maxstreams; ++i) { streamlist->streams[i] = 0; } return streamlist; } int jpc_streamlist_insert(jpc_streamlist_t *streamlist, int streamno, jas_stream_t *stream) { jas_stream_t **newstreams; int newmaxstreams; int i; /* Grow the array of streams if necessary. */ if (streamlist->numstreams >= streamlist->maxstreams) { newmaxstreams = streamlist->maxstreams + 1024; if (!(newstreams = jas_realloc2(streamlist->streams, (newmaxstreams + 1024), sizeof(jas_stream_t *)))) { return -1; } for (i = streamlist->numstreams; i < streamlist->maxstreams; ++i) { streamlist->streams[i] = 0; } streamlist->maxstreams = newmaxstreams; streamlist->streams = newstreams; } if (streamno != streamlist->numstreams) { /* Can only handle insertion at start of list. */ return -1; } streamlist->streams[streamno] = stream; ++streamlist->numstreams; return 0; } jas_stream_t *jpc_streamlist_remove(jpc_streamlist_t *streamlist, int streamno) { jas_stream_t *stream; int i; if (streamno >= streamlist->numstreams) { abort(); } stream = streamlist->streams[streamno]; for (i = streamno + 1; i < streamlist->numstreams; ++i) { streamlist->streams[i - 1] = streamlist->streams[i]; } --streamlist->numstreams; return stream; } void jpc_streamlist_destroy(jpc_streamlist_t *streamlist) { int streamno; if (streamlist->streams) { for (streamno = 0; streamno < streamlist->numstreams; ++streamno) { jas_stream_close(streamlist->streams[streamno]); } jas_free(streamlist->streams); } jas_free(streamlist); } jas_stream_t *jpc_streamlist_get(jpc_streamlist_t *streamlist, int streamno) { assert(streamno < streamlist->numstreams); return streamlist->streams[streamno]; } int jpc_streamlist_numstreams(jpc_streamlist_t *streamlist) { return streamlist->numstreams; } jpc_ppxstab_t *jpc_ppxstab_create() { jpc_ppxstab_t *tab; if (!(tab = jas_malloc(sizeof(jpc_ppxstab_t)))) { return 0; } tab->numents = 0; tab->maxents = 0; tab->ents = 0; return tab; } void jpc_ppxstab_destroy(jpc_ppxstab_t *tab) { int i; for (i = 0; i < tab->numents; ++i) { jpc_ppxstabent_destroy(tab->ents[i]); } if (tab->ents) { jas_free(tab->ents); } jas_free(tab); } int jpc_ppxstab_grow(jpc_ppxstab_t *tab, int maxents) { jpc_ppxstabent_t **newents; if (tab->maxents < maxents) { newents = (tab->ents) ? jas_realloc2(tab->ents, maxents, sizeof(jpc_ppxstabent_t *)) : jas_alloc2(maxents, sizeof(jpc_ppxstabent_t *)); if (!newents) { return -1; } tab->ents = newents; tab->maxents = maxents; } return 0; } int jpc_ppxstab_insert(jpc_ppxstab_t *tab, jpc_ppxstabent_t *ent) { int inspt; int i; for (i = 0; i < tab->numents; ++i) { if (tab->ents[i]->ind > ent->ind) { break; } } inspt = i; if (tab->numents >= tab->maxents) { if (jpc_ppxstab_grow(tab, tab->maxents + 128)) { return -1; } } for (i = tab->numents; i > inspt; --i) { tab->ents[i] = tab->ents[i - 1]; } tab->ents[i] = ent; ++tab->numents; return 0; } jpc_streamlist_t *jpc_ppmstabtostreams(jpc_ppxstab_t *tab) { jpc_streamlist_t *streams; jas_uchar *dataptr; uint_fast32_t datacnt; uint_fast32_t tpcnt; jpc_ppxstabent_t *ent; int entno; jas_stream_t *stream; int n; if (!(streams = jpc_streamlist_create())) { goto error; } if (!tab->numents) { return streams; } entno = 0; ent = tab->ents[entno]; dataptr = ent->data; datacnt = ent->len; for (;;) { /* Get the length of the packet header data for the current tile-part. */ if (datacnt < 4) { goto error; } if (!(stream = jas_stream_memopen(0, 0))) { goto error; } if (jpc_streamlist_insert(streams, jpc_streamlist_numstreams(streams), stream)) { goto error; } tpcnt = (dataptr[0] << 24) | (dataptr[1] << 16) | (dataptr[2] << 8) | dataptr[3]; datacnt -= 4; dataptr += 4; /* Get the packet header data for the current tile-part. */ while (tpcnt) { if (!datacnt) { if (++entno >= tab->numents) { goto error; } ent = tab->ents[entno]; dataptr = ent->data; datacnt = ent->len; } n = JAS_MIN(tpcnt, datacnt); if (jas_stream_write(stream, dataptr, n) != n) { goto error; } tpcnt -= n; dataptr += n; datacnt -= n; } jas_stream_rewind(stream); if (!datacnt) { if (++entno >= tab->numents) { break; } ent = tab->ents[entno]; dataptr = ent->data; datacnt = ent->len; } } return streams; error: if (streams) { jpc_streamlist_destroy(streams); } return 0; } int jpc_pptstabwrite(jas_stream_t *out, jpc_ppxstab_t *tab) { int i; jpc_ppxstabent_t *ent; for (i = 0; i < tab->numents; ++i) { ent = tab->ents[i]; if (jas_stream_write(out, ent->data, ent->len) != JAS_CAST(int, ent->len)) { return -1; } } return 0; } jpc_ppxstabent_t *jpc_ppxstabent_create() { jpc_ppxstabent_t *ent; if (!(ent = jas_malloc(sizeof(jpc_ppxstabent_t)))) { return 0; } ent->data = 0; ent->len = 0; ent->ind = 0; return ent; } void jpc_ppxstabent_destroy(jpc_ppxstabent_t *ent) { if (ent->data) { jas_free(ent->data); } jas_free(ent); }
./CrossVul/dataset_final_sorted/CWE-119/c/good_5486_0
crossvul-cpp_data_bad_252_0
/** * @file * IMAP CRAM-MD5 authentication method * * @authors * Copyright (C) 1999-2001,2005 Brendan Cully <brendan@kublai.com> * * @copyright * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 2 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ /** * @page imap_auth_cram IMAP CRAM-MD5 authentication method * * IMAP CRAM-MD5 authentication method */ #include "config.h" #include <stdio.h> #include <string.h> #include "imap_private.h" #include "mutt/mutt.h" #include "conn/conn.h" #include "auth.h" #include "globals.h" #include "mutt_account.h" #include "mutt_socket.h" #include "options.h" #include "protos.h" #define MD5_BLOCK_LEN 64 #define MD5_DIGEST_LEN 16 /** * hmac_md5 - produce CRAM-MD5 challenge response * @param[in] password Password to encrypt * @param[in] challenge Challenge from server * @param[out] response Buffer for the response */ static void hmac_md5(const char *password, char *challenge, unsigned char *response) { struct Md5Ctx ctx; unsigned char ipad[MD5_BLOCK_LEN] = { 0 }; unsigned char opad[MD5_BLOCK_LEN] = { 0 }; unsigned char secret[MD5_BLOCK_LEN + 1]; size_t secret_len; secret_len = strlen(password); /* passwords longer than MD5_BLOCK_LEN bytes are substituted with their MD5 * digests */ if (secret_len > MD5_BLOCK_LEN) { unsigned char hash_passwd[MD5_DIGEST_LEN]; mutt_md5_bytes(password, secret_len, hash_passwd); mutt_str_strfcpy((char *) secret, (char *) hash_passwd, MD5_DIGEST_LEN); secret_len = MD5_DIGEST_LEN; } else mutt_str_strfcpy((char *) secret, password, sizeof(secret)); memcpy(ipad, secret, secret_len); memcpy(opad, secret, secret_len); for (int i = 0; i < MD5_BLOCK_LEN; i++) { ipad[i] ^= 0x36; opad[i] ^= 0x5c; } /* inner hash: challenge and ipadded secret */ mutt_md5_init_ctx(&ctx); mutt_md5_process_bytes(ipad, MD5_BLOCK_LEN, &ctx); mutt_md5_process(challenge, &ctx); mutt_md5_finish_ctx(&ctx, response); /* outer hash: inner hash and opadded secret */ mutt_md5_init_ctx(&ctx); mutt_md5_process_bytes(opad, MD5_BLOCK_LEN, &ctx); mutt_md5_process_bytes(response, MD5_DIGEST_LEN, &ctx); mutt_md5_finish_ctx(&ctx, response); } /** * imap_auth_cram_md5 - Authenticate using CRAM-MD5 * @param idata Server data * @param method Name of this authentication method * @retval enum Result, e.g. #IMAP_AUTH_SUCCESS */ enum ImapAuthRes imap_auth_cram_md5(struct ImapData *idata, const char *method) { char ibuf[LONG_STRING * 2], obuf[LONG_STRING]; unsigned char hmac_response[MD5_DIGEST_LEN]; int len; int rc; if (!mutt_bit_isset(idata->capabilities, ACRAM_MD5)) return IMAP_AUTH_UNAVAIL; mutt_message(_("Authenticating (CRAM-MD5)...")); /* get auth info */ if (mutt_account_getlogin(&idata->conn->account) < 0) return IMAP_AUTH_FAILURE; if (mutt_account_getpass(&idata->conn->account) < 0) return IMAP_AUTH_FAILURE; imap_cmd_start(idata, "AUTHENTICATE CRAM-MD5"); /* From RFC2195: * The data encoded in the first ready response contains a presumptively * arbitrary string of random digits, a timestamp, and the fully-qualified * primary host name of the server. The syntax of the unencoded form must * correspond to that of an RFC822 'msg-id' [RFC822] as described in [POP3]. */ do rc = imap_cmd_step(idata); while (rc == IMAP_CMD_CONTINUE); if (rc != IMAP_CMD_RESPOND) { mutt_debug(1, "Invalid response from server: %s\n", ibuf); goto bail; } len = mutt_b64_decode(obuf, idata->buf + 2); if (len == -1) { mutt_debug(1, "Error decoding base64 response.\n"); goto bail; } obuf[len] = '\0'; mutt_debug(2, "CRAM challenge: %s\n", obuf); /* The client makes note of the data and then responds with a string * consisting of the user name, a space, and a 'digest'. The latter is * computed by applying the keyed MD5 algorithm from [KEYED-MD5] where the * key is a shared secret and the digested text is the timestamp (including * angle-brackets). * * Note: The user name shouldn't be quoted. Since the digest can't contain * spaces, there is no ambiguity. Some servers get this wrong, we'll work * around them when the bug report comes in. Until then, we'll remain * blissfully RFC-compliant. */ hmac_md5(idata->conn->account.pass, obuf, hmac_response); /* dubious optimisation I saw elsewhere: make the whole string in one call */ int off = snprintf(obuf, sizeof(obuf), "%s ", idata->conn->account.user); mutt_md5_toascii(hmac_response, obuf + off); mutt_debug(2, "CRAM response: %s\n", obuf); /* ibuf must be long enough to store the base64 encoding of obuf, * plus the additional debris */ mutt_b64_encode(ibuf, obuf, strlen(obuf), sizeof(ibuf) - 2); mutt_str_strcat(ibuf, sizeof(ibuf), "\r\n"); mutt_socket_send(idata->conn, ibuf); do rc = imap_cmd_step(idata); while (rc == IMAP_CMD_CONTINUE); if (rc != IMAP_CMD_OK) { mutt_debug(1, "Error receiving server response.\n"); goto bail; } if (imap_code(idata->buf)) return IMAP_AUTH_SUCCESS; bail: mutt_error(_("CRAM-MD5 authentication failed.")); return IMAP_AUTH_FAILURE; }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_252_0
crossvul-cpp_data_good_1436_0
/* Copyright (C) 2013-2015 Yubico AB 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, 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, see <http://www.gnu.org/licenses/>. */ #include <config.h> #include "internal.h" #include <stdlib.h> #ifdef _WIN32 #include <windows.h> #include <winternl.h> #include <winerror.h> #include <stdio.h> #include <bcrypt.h> #include <sal.h> #pragma comment(lib, "bcrypt.lib") #else #include <unistd.h> #include <string.h> #include <sys/ioctl.h> #include <fcntl.h> #endif #ifdef __linux #include <linux/hidraw.h> #endif #ifdef __linux static uint32_t get_bytes (uint8_t * rpt, size_t len, size_t num_bytes, size_t cur) { /* Return if there aren't enough bytes. */ if (cur + num_bytes >= len) return 0; if (num_bytes == 0) return 0; else if (num_bytes == 1) { return rpt[cur + 1]; } else if (num_bytes == 2) { return (rpt[cur + 2] * 256 + rpt[cur + 1]); } else return 0; } static int get_usage (uint8_t * report_descriptor, size_t size, unsigned short *usage_page, unsigned short *usage) { size_t i = 0; int size_code; int data_len, key_size; int usage_found = 0, usage_page_found = 0; while (i < size) { int key = report_descriptor[i]; int key_cmd = key & 0xfc; if ((key & 0xf0) == 0xf0) { fprintf (stderr, "invalid data received.\n"); return -1; } else { size_code = key & 0x3; switch (size_code) { case 0: case 1: case 2: data_len = size_code; break; case 3: data_len = 4; break; default: /* Can't ever happen since size_code is & 0x3 */ data_len = 0; break; }; key_size = 1; } if (key_cmd == 0x4) { *usage_page = get_bytes (report_descriptor, size, data_len, i); usage_page_found = 1; } if (key_cmd == 0x8) { *usage = get_bytes (report_descriptor, size, data_len, i); usage_found = 1; } if (usage_page_found && usage_found) return 0; /* success */ i += data_len + key_size; } return -1; /* failure */ } #endif static int get_usages (struct hid_device_info *dev, unsigned short *usage_page, unsigned short *usage) { #ifdef __linux int res, desc_size; int ret = U2FH_TRANSPORT_ERROR; struct hidraw_report_descriptor rpt_desc; int handle = open (dev->path, O_RDWR); if (handle > 0) { memset (&rpt_desc, 0, sizeof (rpt_desc)); res = ioctl (handle, HIDIOCGRDESCSIZE, &desc_size); if (res >= 0) { rpt_desc.size = desc_size; res = ioctl (handle, HIDIOCGRDESC, &rpt_desc); if (res >= 0) { res = get_usage (rpt_desc.value, rpt_desc.size, usage_page, usage); if (res >= 0) { ret = U2FH_OK; } } } close (handle); } return ret; #else *usage_page = dev->usage_page; *usage = dev->usage; return U2FH_OK; #endif } static struct u2fdevice * close_device (u2fh_devs * devs, struct u2fdevice *dev) { struct u2fdevice *next = dev->next; hid_close (dev->devh); free (dev->device_path); free (dev->device_string); if (dev == devs->first) { devs->first = next; free (dev); } else { struct u2fdevice *d; for (d = devs->first; d != NULL; d = d->next) { if (d->next == dev) { d->next = next; free (dev); break; } } } return next; } struct u2fdevice * get_device (u2fh_devs * devs, unsigned id) { struct u2fdevice *dev; for (dev = devs->first; dev != NULL; dev = dev->next) { if (dev->id == id) { return dev; } } return NULL; } static struct u2fdevice * new_device (u2fh_devs * devs) { struct u2fdevice *new = malloc (sizeof (struct u2fdevice)); if (new == NULL) { return NULL; } memset (new, 0, sizeof (struct u2fdevice)); new->id = devs->max_id++; if (devs->first == NULL) { devs->first = new; } else { struct u2fdevice *dev; for (dev = devs->first; dev != NULL; dev = dev->next) { if (dev->next == NULL) { break; } } dev->next = new; } return new; } static void close_devices (u2fh_devs * devs) { struct u2fdevice *dev; if (devs == NULL) { return; } dev = devs->first; while (dev) { dev = close_device (devs, dev); } } #if defined(_WIN32) static int obtain_nonce(unsigned char* nonce) { NTSTATUS status; status = BCryptGenRandom(NULL, nonce, 8, BCRYPT_USE_SYSTEM_PREFERRED_RNG); if (!NT_SUCCESS(status)) return (-1); return (0); } #elif defined(HAVE_DEV_URANDOM) static int obtain_nonce(unsigned char* nonce) { int fd = -1; int ok = -1; ssize_t r; if ((fd = open("/dev/urandom", O_RDONLY)) < 0) goto fail; if ((r = read(fd, nonce, 8)) < 0 || r != 8) goto fail; ok = 0; fail: if (fd != -1) close(fd); return (ok); } #else #error "please provide an implementation of obtain_nonce() for your platform" #endif /* _WIN32 */ static int init_device (u2fh_devs * devs, struct u2fdevice *dev) { unsigned char resp[1024]; unsigned char nonce[8]; if (obtain_nonce(nonce) != 0) { return U2FH_TRANSPORT_ERROR; } size_t resplen = sizeof (resp); dev->cid = CID_BROADCAST; if (u2fh_sendrecv (devs, dev->id, U2FHID_INIT, nonce, sizeof (nonce), resp, &resplen) == U2FH_OK) { int offs = sizeof (nonce); /* the response has to be atleast 17 bytes, if it's more we discard that */ if (resplen < 17) { return U2FH_SIZE_ERROR; } /* incoming and outgoing nonce has to match */ if (memcmp (nonce, resp, sizeof (nonce)) != 0) { return U2FH_TRANSPORT_ERROR; } dev->cid = resp[offs] << 24 | resp[offs + 1] << 16 | resp[offs + 2] << 8 | resp[offs + 3]; offs += 4; dev->versionInterface = resp[offs++]; dev->versionMajor = resp[offs++]; dev->versionMinor = resp[offs++]; dev->versionBuild = resp[offs++]; dev->capFlags = resp[offs++]; } else { return U2FH_TRANSPORT_ERROR; } return U2FH_OK; } static int ping_device (u2fh_devs * devs, unsigned index) { unsigned char data[1] = { 0 }; unsigned char resp[1024]; size_t resplen = sizeof (resp); return u2fh_sendrecv (devs, index, U2FHID_PING, data, sizeof (data), resp, &resplen); } /** * u2fh_devs_init: * @devs: pointer to #u2fh_devs type to initialize. * * Initialize device handle. * * Returns: On success %U2FH_OK (integer 0) is returned, on memory * allocation errors %U2FH_MEMORY_ERROR is returned, or another * #u2fh_rc error code is returned. */ u2fh_rc u2fh_devs_init (u2fh_devs ** devs) { u2fh_devs *d; int rc; d = malloc (sizeof (*d)); if (d == NULL) return U2FH_MEMORY_ERROR; memset (d, 0, sizeof (*d)); rc = hid_init (); if (rc != 0) { free (d); return U2FH_TRANSPORT_ERROR; } *devs = d; return U2FH_OK; } /** * u2fh_devs_discover: * @devs: device handle, from u2fh_devs_init(). * @max_index: will on return be set to the maximum index, may be NULL; if * there is 1 device this will be 0, if there are 2 devices this * will be 1, and so on. * * Discover and open new devices. This function can safely be called * several times and will free resources associated with unplugged * devices and open new. * * Returns: On success, %U2FH_OK (integer 0) is returned, when no U2F * device could be found %U2FH_NO_U2F_DEVICE is returned, or another * #u2fh_rc error code. */ u2fh_rc u2fh_devs_discover (u2fh_devs * devs, unsigned *max_index) { struct hid_device_info *di, *cur_dev; u2fh_rc res = U2FH_NO_U2F_DEVICE; struct u2fdevice *dev; di = hid_enumerate (0, 0); for (cur_dev = di; cur_dev; cur_dev = cur_dev->next) { int found = 0; unsigned short usage_page = 0, usage = 0; /* check if we already opened this device */ for (dev = devs->first; dev != NULL; dev = dev->next) { if (strcmp (dev->device_path, cur_dev->path) == 0) { if (ping_device (devs, dev->id) == U2FH_OK) { found = 1; res = U2FH_OK; } else { if (debug) { fprintf (stderr, "Device %s failed ping, dead.\n", dev->device_path); } close_device (devs, dev); } break; } } if (found) { continue; } get_usages (cur_dev, &usage_page, &usage); if (usage_page == FIDO_USAGE_PAGE && usage == FIDO_USAGE_U2FHID) { dev = new_device (devs); dev->devh = hid_open_path (cur_dev->path); if (dev->devh != NULL) { dev->device_path = strdup (cur_dev->path); if (dev->device_path == NULL) { close_device (devs, dev); goto out; } if (init_device (devs, dev) == U2FH_OK) { if (cur_dev->product_string) { size_t len = wcstombs (NULL, cur_dev->product_string, 0); dev->device_string = malloc (len + 1); if (dev->device_string == NULL) { close_device (devs, dev); goto out; } memset (dev->device_string, 0, len + 1); wcstombs (dev->device_string, cur_dev->product_string, len); if (debug) { fprintf (stderr, "device %s discovered as '%s'\n", dev->device_path, dev->device_string); fprintf (stderr, " version (Interface, Major, " "Minor, Build): %d, %d, " "%d, %d capFlags: %d\n", dev->versionInterface, dev->versionMajor, dev->versionMinor, dev->versionBuild, dev->capFlags); } } res = U2FH_OK; continue; } } close_device (devs, dev); } } /* loop through all open devices and make sure we find them in the enumeration */ dev = devs->first; while (dev) { int found = 0; for (cur_dev = di; cur_dev; cur_dev = cur_dev->next) { if (strcmp (cur_dev->path, dev->device_path) == 0) { found = 1; dev = dev->next; break; } } if (!found) { if (debug) { fprintf (stderr, "device %s looks dead.\n", dev->device_path); } dev = close_device (devs, dev); } } out: hid_free_enumeration (di); if (res == U2FH_OK && max_index) *max_index = devs->max_id - 1; return res; } /** * u2fh_devs_done: * @devs: device handle, from u2fh_devs_init(). * * Release all resources associated with @devs. This function must be * called when you are finished with a device handle. */ void u2fh_devs_done (u2fh_devs * devs) { close_devices (devs); hid_exit (); free (devs); } /** * u2fh_get_device_description: * @devs: device_handle, from u2fh_devs_init(). * @index: index of device * @out: buffer for storing device description * @len: maximum amount of data to store in @out. Will be updated. * * Get the device description of the device at @index. Stores the * string in @out. * * Returns: %U2FH_OK on success. */ u2fh_rc u2fh_get_device_description (u2fh_devs * devs, unsigned index, char *out, size_t * len) { size_t i; struct u2fdevice *dev = get_device (devs, index); if (!dev) { return U2FH_NO_U2F_DEVICE; } i = strlen (dev->device_string); if (i < *len) { *len = i; } else { return U2FH_MEMORY_ERROR; } strcpy (out, dev->device_string); return U2FH_OK; } /** * u2fh_is_alive: * @devs: device_handle, from u2fh_devs_init(). * @index: index of device * * Get the liveliness of the device @index. * * Returns: 1 if the device is considered alive, 0 otherwise. */ int u2fh_is_alive (u2fh_devs * devs, unsigned index) { if (!get_device (devs, index)) return 0; return 1; }
./CrossVul/dataset_final_sorted/CWE-119/c/good_1436_0
crossvul-cpp_data_good_105_0
#ifndef NGIFLIB_NO_FILE #include <stdio.h> #endif /* NGIFLIB_NO_FILE */ #include "ngiflib.h" /* decodeur GIF en C portable (pas de pb big/little endian) * Thomas BERNARD. janvier 2004. * (c) 2004-2017 Thomas Bernard. All rights reserved */ /* Fonction de debug */ #ifdef DEBUG void fprintf_ngiflib_img(FILE * f, struct ngiflib_img * i) { fprintf(f, " * ngiflib_img @ %p\n", i); fprintf(f, " next = %p\n", i->next); fprintf(f, " parent = %p\n", i->parent); fprintf(f, " palette = %p\n", i->palette); fprintf(f, " %3d couleurs", i->ncolors); if(i->interlaced) fprintf(f, " interlaced"); fprintf(f, "\n taille : %dx%d, pos (%d,%d)\n", i->width, i->height, i->posX, i->posY); fprintf(f, " sort_flag=%x localpalbits=%d\n", i->sort_flag, i->localpalbits); } #endif /* DEBUG */ void GifImgDestroy(struct ngiflib_img * i) { if(i==NULL) return; if(i->next) GifImgDestroy(i->next); if(i->palette && (i->palette != i->parent->palette)) ngiflib_free(i->palette); ngiflib_free(i); } /* Fonction de debug */ #ifdef DEBUG void fprintf_ngiflib_gif(FILE * f, struct ngiflib_gif * g) { struct ngiflib_img * i; fprintf(f, "* ngiflib_gif @ %p %s\n", g, g->signature); fprintf(f, " %dx%d, %d bits, %d couleurs\n", g->width, g->height, g->imgbits, g->ncolors); fprintf(f, " palette = %p, backgroundcolorindex %d\n", g->palette, g->backgroundindex); fprintf(f, " pixelaspectratio = %d\n", g->pixaspectratio); fprintf(f, " frbuff = %p\n", g->frbuff.p8); fprintf(f, " cur_img = %p\n", g->cur_img); fprintf(f, " %d images :\n", g->nimg); i = g->first_img; while(i) { fprintf_ngiflib_img(f, i); i = i->next; } } #endif /* DEBUG */ void GifDestroy(struct ngiflib_gif * g) { if(g==NULL) return; if(g->palette) ngiflib_free(g->palette); if(g->frbuff.p8) ngiflib_free(g->frbuff.p8); GifImgDestroy(g->first_img); ngiflib_free(g); } /* u8 GetByte(struct ngiflib_gif * g); * fonction qui renvoie un octet du fichier .gif * on pourait optimiser en faisant 2 fonctions. */ static u8 GetByte(struct ngiflib_gif * g) { #ifndef NGIFLIB_NO_FILE if(g->mode & NGIFLIB_MODE_FROM_MEM) { #endif /* NGIFLIB_NO_FILE */ return *(g->input.bytes++); #ifndef NGIFLIB_NO_FILE } else { return (u8)(getc(g->input.file)); } #endif /* NGIFLIB_NO_FILE */ } /* u16 GetWord() * Renvoie un mot de 16bits * N'est pas influencee par l'endianess du CPU ! */ static u16 GetWord(struct ngiflib_gif * g) { u16 r = (u16)GetByte(g); r |= ((u16)GetByte(g) << 8); return r; } /* int GetByteStr(struct ngiflib_gif * g, u8 * p, int n); * prend en argument un pointeur sur la destination * et le nombre d'octet a lire. * Renvoie 0 si l'operation a reussi, -1 sinon. */ static int GetByteStr(struct ngiflib_gif * g, u8 * p, int n) { if(!p) return -1; #ifndef NGIFLIB_NO_FILE if(g->mode & NGIFLIB_MODE_FROM_MEM) { #endif /* NGIFLIB_NO_FILE */ ngiflib_memcpy(p, g->input.bytes, n); g->input.bytes += n; return 0; #ifndef NGIFLIB_NO_FILE } else { size_t read; read = fread(p, 1, n, g->input.file); return ((int)read == n) ? 0 : -1; } #endif /* NGIFLIB_NO_FILE */ } /* void WritePixel(struct ngiflib_img * i, u8 v); * ecrit le pixel de valeur v dans le frame buffer */ static void WritePixel(struct ngiflib_img * i, struct ngiflib_decode_context * context, u8 v) { struct ngiflib_gif * p = i->parent; if(v!=i->gce.transparent_color || !i->gce.transparent_flag) { #ifndef NGIFLIB_INDEXED_ONLY if(p->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ *context->frbuff_p.p8 = v; #ifndef NGIFLIB_INDEXED_ONLY } else *context->frbuff_p.p32 = GifIndexToTrueColor(i->palette, v); #endif /* NGIFLIB_INDEXED_ONLY */ } if(--(context->Xtogo) <= 0) { #ifdef NGIFLIB_ENABLE_CALLBACKS if(p->line_cb) p->line_cb(p, context->line_p, context->curY); #endif /* NGIFLIB_ENABLE_CALLBACKS */ context->Xtogo = i->width; switch(context->pass) { case 0: context->curY++; break; case 1: /* 1st pass : every eighth row starting from 0 */ context->curY += 8; if(context->curY >= p->height) { context->pass++; context->curY = i->posY + 4; } break; case 2: /* 2nd pass : every eighth row starting from 4 */ context->curY += 8; if(context->curY >= p->height) { context->pass++; context->curY = i->posY + 2; } break; case 3: /* 3rd pass : every fourth row starting from 2 */ context->curY += 4; if(context->curY >= p->height) { context->pass++; context->curY = i->posY + 1; } break; case 4: /* 4th pass : every odd row */ context->curY += 2; break; } #ifndef NGIFLIB_INDEXED_ONLY if(p->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ #ifdef NGIFLIB_ENABLE_CALLBACKS context->line_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width; context->frbuff_p.p8 = context->line_p.p8 + i->posX; #else context->frbuff_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ #ifndef NGIFLIB_INDEXED_ONLY } else { #ifdef NGIFLIB_ENABLE_CALLBACKS context->line_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width; context->frbuff_p.p32 = context->line_p.p32 + i->posX; #else context->frbuff_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ } #endif /* NGIFLIB_INDEXED_ONLY */ } else { #ifndef NGIFLIB_INDEXED_ONLY if(p->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ context->frbuff_p.p8++; #ifndef NGIFLIB_INDEXED_ONLY } else { context->frbuff_p.p32++; } #endif /* NGIFLIB_INDEXED_ONLY */ } } /* void WritePixels(struct ngiflib_img * i, const u8 * pixels, u16 n); * ecrit les pixels dans le frame buffer */ static void WritePixels(struct ngiflib_img * i, struct ngiflib_decode_context * context, const u8 * pixels, u16 n) { u16 tocopy; struct ngiflib_gif * p = i->parent; while(n > 0) { tocopy = (context->Xtogo < n) ? context->Xtogo : n; if(!i->gce.transparent_flag) { #ifndef NGIFLIB_INDEXED_ONLY if(p->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ ngiflib_memcpy(context->frbuff_p.p8, pixels, tocopy); pixels += tocopy; context->frbuff_p.p8 += tocopy; #ifndef NGIFLIB_INDEXED_ONLY } else { int j; for(j = (int)tocopy; j > 0; j--) { *(context->frbuff_p.p32++) = GifIndexToTrueColor(i->palette, *pixels++); } } #endif /* NGIFLIB_INDEXED_ONLY */ } else { int j; #ifndef NGIFLIB_INDEXED_ONLY if(p->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ for(j = (int)tocopy; j > 0; j--) { if(*pixels != i->gce.transparent_color) *context->frbuff_p.p8 = *pixels; pixels++; context->frbuff_p.p8++; } #ifndef NGIFLIB_INDEXED_ONLY } else { for(j = (int)tocopy; j > 0; j--) { if(*pixels != i->gce.transparent_color) { *context->frbuff_p.p32 = GifIndexToTrueColor(i->palette, *pixels); } pixels++; context->frbuff_p.p32++; } } #endif /* NGIFLIB_INDEXED_ONLY */ } context->Xtogo -= tocopy; if(context->Xtogo == 0) { #ifdef NGIFLIB_ENABLE_CALLBACKS if(p->line_cb) p->line_cb(p, context->line_p, context->curY); #endif /* NGIFLIB_ENABLE_CALLBACKS */ context->Xtogo = i->width; switch(context->pass) { case 0: context->curY++; break; case 1: /* 1st pass : every eighth row starting from 0 */ context->curY += 8; if(context->curY >= p->height) { context->pass++; context->curY = i->posY + 4; } break; case 2: /* 2nd pass : every eighth row starting from 4 */ context->curY += 8; if(context->curY >= p->height) { context->pass++; context->curY = i->posY + 2; } break; case 3: /* 3rd pass : every fourth row starting from 2 */ context->curY += 4; if(context->curY >= p->height) { context->pass++; context->curY = i->posY + 1; } break; case 4: /* 4th pass : every odd row */ context->curY += 2; break; } #ifndef NGIFLIB_INDEXED_ONLY if(p->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ #ifdef NGIFLIB_ENABLE_CALLBACKS context->line_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width; context->frbuff_p.p8 = context->line_p.p8 + i->posX; #else context->frbuff_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ #ifndef NGIFLIB_INDEXED_ONLY } else { #ifdef NGIFLIB_ENABLE_CALLBACKS context->line_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width; context->frbuff_p.p32 = context->line_p.p32 + i->posX; #else context->frbuff_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ } #endif /* NGIFLIB_INDEXED_ONLY */ } n -= tocopy; } } /* * u16 GetGifWord(struct ngiflib_img * i); * Renvoie un code LZW (taille variable) */ static u16 GetGifWord(struct ngiflib_img * i, struct ngiflib_decode_context * context) { u16 r; int bits_todo; u16 newbyte; bits_todo = (int)context->nbbit - (int)context->restbits; if( bits_todo <= 0) { /* nbbit <= restbits */ r = context->lbyte; context->restbits -= context->nbbit; context->lbyte >>= context->nbbit; } else if( bits_todo > 8 ) { /* nbbit > restbits + 8 */ if(context->restbyte >= 2) { context->restbyte -= 2; r = *context->srcbyte++; } else { if(context->restbyte == 0) { context->restbyte = GetByte(i->parent); #if defined(DEBUG) && !defined(NGIFLIB_NO_FILE) if(i->parent->log) fprintf(i->parent->log, "restbyte = %02X\n", context->restbyte); #endif /* defined(DEBUG) && !defined(NGIFLIB_NO_FILE) */ GetByteStr(i->parent, context->byte_buffer, context->restbyte); context->srcbyte = context->byte_buffer; } r = *context->srcbyte++; if(--context->restbyte == 0) { context->restbyte = GetByte(i->parent); #if defined(DEBUG) && !defined(NGIFLIB_NO_FILE) if(i->parent->log) fprintf(i->parent->log, "restbyte = %02X\n", context->restbyte); #endif /* defined(DEBUG) && !defined(NGIFLIB_NO_FILE) */ GetByteStr(i->parent, context->byte_buffer, context->restbyte); context->srcbyte = context->byte_buffer; } context->restbyte--; } newbyte = *context->srcbyte++; r |= newbyte << 8; r = (r << context->restbits) | context->lbyte; context->restbits = 16 - bits_todo; context->lbyte = newbyte >> (bits_todo - 8); } else /*if( bits_todo > 0 )*/ { /* nbbit > restbits */ if(context->restbyte == 0) { context->restbyte = GetByte(i->parent); #if defined(DEBUG) && !defined(NGIFLIB_NO_FILE) if(i->parent->log) fprintf(i->parent->log, "restbyte = %02X\n", context->restbyte); #endif /* defined(DEBUG) && !defined(NGIFLIB_NO_FILE) */ GetByteStr(i->parent, context->byte_buffer, context->restbyte); context->srcbyte = context->byte_buffer; } newbyte = *context->srcbyte++; context->restbyte--; r = (newbyte << context->restbits) | context->lbyte; context->restbits = 8 - bits_todo; context->lbyte = newbyte >> bits_todo; } return (r & context->max); /* applique le bon masque pour eliminer les bits en trop */ } /* ------------------------------------------------ */ static void FillGifBackGround(struct ngiflib_gif * g) { long n = (long)g->width*g->height; #ifndef NGIFLIB_INDEXED_ONLY u32 bg_truecolor; #endif /* NGIFLIB_INDEXED_ONLY */ if((g->frbuff.p8==NULL)||(g->palette==NULL)) return; #ifndef NGIFLIB_INDEXED_ONLY if(g->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ ngiflib_memset(g->frbuff.p8, g->backgroundindex, n); #ifndef NGIFLIB_INDEXED_ONLY } else { u32 * p = g->frbuff.p32; bg_truecolor = GifIndexToTrueColor(g->palette, g->backgroundindex); while(n-->0) *p++ = bg_truecolor; } #endif /* NGIFLIB_INDEXED_ONLY */ } /* ------------------------------------------------ */ int CheckGif(u8 * b) { return (b[0]=='G')&&(b[1]=='I')&&(b[2]=='F')&&(b[3]=='8'); } /* ------------------------------------------------ */ static int DecodeGifImg(struct ngiflib_img * i) { struct ngiflib_decode_context context; long npix; u8 * stackp; u8 * stack_top; u16 clr; u16 eof; u16 free; u16 act_code = 0; u16 old_code = 0; u16 read_byt; u16 ab_prfx[4096]; u8 ab_suffx[4096]; u8 ab_stack[4096]; u8 flags; u8 casspecial = 0; if(!i) return -1; i->posX = GetWord(i->parent); /* offsetX */ i->posY = GetWord(i->parent); /* offsetY */ i->width = GetWord(i->parent); /* SizeX */ i->height = GetWord(i->parent); /* SizeY */ if((i->width > i->parent->width) || (i->height > i->parent->height)) { #if !defined(NGIFLIB_NO_FILE) if(i->parent->log) fprintf(i->parent->log, "*** ERROR *** Image bigger than global GIF canvas !\n"); #endif return -1; } if((i->posX + i->width) > i->parent->width) { #if !defined(NGIFLIB_NO_FILE) if(i->parent->log) fprintf(i->parent->log, "*** WARNING *** Adjusting X position\n"); #endif i->posX = i->parent->width - i->width; } if((i->posY + i->height) > i->parent->height) { #if !defined(NGIFLIB_NO_FILE) if(i->parent->log) fprintf(i->parent->log, "*** WARNING *** Adjusting Y position\n"); #endif i->posY = i->parent->height - i->height; } context.Xtogo = i->width; context.curY = i->posY; #ifdef NGIFLIB_INDEXED_ONLY #ifdef NGIFLIB_ENABLE_CALLBACKS context.line_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width; context.frbuff_p.p8 = context.line_p.p8 + i->posX; #else context.frbuff_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ #else if(i->parent->mode & NGIFLIB_MODE_INDEXED) { #ifdef NGIFLIB_ENABLE_CALLBACKS context.line_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width; context.frbuff_p.p8 = context.line_p.p8 + i->posX; #else context.frbuff_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ } else { #ifdef NGIFLIB_ENABLE_CALLBACKS context.line_p.p32 = i->parent->frbuff.p32 + (u32)i->posY*i->parent->width; context.frbuff_p.p32 = context.line_p.p32 + i->posX; #else context.frbuff_p.p32 = i->parent->frbuff.p32 + (u32)i->posY*i->parent->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ } #endif /* NGIFLIB_INDEXED_ONLY */ npix = (long)i->width * i->height; flags = GetByte(i->parent); i->interlaced = (flags & 64) >> 6; context.pass = i->interlaced ? 1 : 0; i->sort_flag = (flags & 32) >> 5; /* is local palette sorted by color frequency ? */ i->localpalbits = (flags & 7) + 1; if(flags&128) { /* palette locale */ int k; int localpalsize = 1 << i->localpalbits; #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) fprintf(i->parent->log, "Local palette\n"); #endif /* !defined(NGIFLIB_NO_FILE) */ i->palette = (struct ngiflib_rgb *)ngiflib_malloc(sizeof(struct ngiflib_rgb)*localpalsize); for(k=0; k<localpalsize; k++) { i->palette[k].r = GetByte(i->parent); i->palette[k].g = GetByte(i->parent); i->palette[k].b = GetByte(i->parent); } #ifdef NGIFLIB_ENABLE_CALLBACKS if(i->parent->palette_cb) i->parent->palette_cb(i->parent, i->palette, localpalsize); #endif /* NGIFLIB_ENABLE_CALLBACKS */ } else { i->palette = i->parent->palette; i->localpalbits = i->parent->imgbits; } i->ncolors = 1 << i->localpalbits; i->imgbits = GetByte(i->parent); /* LZW Minimum Code Size */ #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) { if(i->interlaced) fprintf(i->parent->log, "interlaced "); fprintf(i->parent->log, "img pos(%hu,%hu) size %hux%hu palbits=%hhu imgbits=%hhu ncolors=%hu\n", i->posX, i->posY, i->width, i->height, i->localpalbits, i->imgbits, i->ncolors); } #endif /* !defined(NGIFLIB_NO_FILE) */ if(i->imgbits==1) { /* fix for 1bit images ? */ i->imgbits = 2; } clr = 1 << i->imgbits; eof = clr + 1; free = clr + 2; context.nbbit = i->imgbits + 1; context.max = clr + clr - 1; /* (1 << context.nbbit) - 1 */ stackp = stack_top = ab_stack + 4096; context.restbits = 0; /* initialise le "buffer" de lecture */ context.restbyte = 0; /* des codes LZW */ context.lbyte = 0; for(;;) { act_code = GetGifWord(i, &context); if(act_code==eof) { #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) fprintf(i->parent->log, "End of image code\n"); #endif /* !defined(NGIFLIB_NO_FILE) */ return 0; } if(npix==0) { #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) fprintf(i->parent->log, "assez de pixels, On se casse !\n"); #endif /* !defined(NGIFLIB_NO_FILE) */ return 1; } if(act_code==clr) { #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) fprintf(i->parent->log, "Code clear (free=%hu) npix=%ld\n", free, npix); #endif /* !defined(NGIFLIB_NO_FILE) */ /* clear */ free = clr + 2; context.nbbit = i->imgbits + 1; context.max = clr + clr - 1; /* (1 << context.nbbit) - 1 */ act_code = GetGifWord(i, &context); casspecial = (u8)act_code; old_code = act_code; WritePixel(i, &context, casspecial); npix--; } else { read_byt = act_code; if(act_code >= free) { /* code pas encore dans alphabet */ /* printf("Code pas dans alphabet : %d>=%d push %d\n", act_code, free, casspecial); */ *(--stackp) = casspecial; /* dernier debut de chaine ! */ act_code = old_code; } /* printf("actcode=%d\n", act_code); */ while(act_code > clr) { /* code non concret */ /* fillstackloop empile les suffixes ! */ *(--stackp) = ab_suffx[act_code]; act_code = ab_prfx[act_code]; /* prefixe */ } /* act_code est concret */ casspecial = (u8)act_code; /* dernier debut de chaine ! */ *(--stackp) = casspecial; /* push on stack */ WritePixels(i, &context, stackp, stack_top - stackp); /* unstack all pixels at once */ npix -= (stack_top - stackp); stackp = stack_top; /* putchar('\n'); */ if(free < 4096) { /* la taille du dico est 4096 max ! */ ab_prfx[free] = old_code; ab_suffx[free] = (u8)act_code; free++; if((free > context.max) && (context.nbbit < 12)) { context.nbbit++; /* 1 bit de plus pour les codes LZW */ context.max += context.max + 1; } } old_code = read_byt; } } return 0; } /* ------------------------------------------------ * int LoadGif(struct ngiflib_gif *); * s'assurer que nimg=0 au depart ! * retourne : * 0 si GIF termin� * un nombre negatif si ERREUR * 1 si image Decod�e * rappeler pour decoder les images suivantes * ------------------------------------------------ */ int LoadGif(struct ngiflib_gif * g) { struct ngiflib_gce gce; u8 sign; u8 tmp; int i; if(!g) return -1; gce.gce_present = 0; if(g->nimg==0) { GetByteStr(g, g->signature, 6); g->signature[6] = '\0'; if( g->signature[0] != 'G' || g->signature[1] != 'I' || g->signature[2] != 'F' || g->signature[3] != '8') { return -1; } #if !defined(NGIFLIB_NO_FILE) if(g->log) fprintf(g->log, "%s\n", g->signature); #endif /* !defined(NGIFLIB_NO_FILE) */ g->width = GetWord(g); g->height = GetWord(g); /* allocate frame buffer */ #ifndef NGIFLIB_INDEXED_ONLY if((g->mode & NGIFLIB_MODE_INDEXED)==0) g->frbuff.p32 = ngiflib_malloc(4*(long)g->height*(long)g->width); else #endif /* NGIFLIB_INDEXED_ONLY */ g->frbuff.p8 = ngiflib_malloc((long)g->height*(long)g->width); tmp = GetByte(g);/* <Packed Fields> = Global Color Table Flag 1 Bit Color Resolution 3 Bits Sort Flag 1 Bit Size of Global Color Table 3 Bits */ g->colorresolution = ((tmp & 0x70) >> 4) + 1; g->sort_flag = (tmp & 8) >> 3; g->imgbits = (tmp & 7) + 1; /* Global Palette color resolution */ g->ncolors = 1 << g->imgbits; g->backgroundindex = GetByte(g); #if !defined(NGIFLIB_NO_FILE) if(g->log) fprintf(g->log, "%hux%hu %hhubits %hu couleurs bg=%hhu\n", g->width, g->height, g->imgbits, g->ncolors, g->backgroundindex); #endif /* NGIFLIB_INDEXED_ONLY */ g->pixaspectratio = GetByte(g); /* pixel aspect ratio (0 : unspecified) */ if(tmp&0x80) { /* la palette globale suit. */ g->palette = (struct ngiflib_rgb *)ngiflib_malloc(sizeof(struct ngiflib_rgb)*g->ncolors); for(i=0; i<g->ncolors; i++) { g->palette[i].r = GetByte(g); g->palette[i].g = GetByte(g); g->palette[i].b = GetByte(g); #if defined(DEBUG) && !defined(NGIFLIB_NO_FILE) if(g->log) fprintf(g->log, "%3d %02X %02X %02X\n", i, g->palette[i].r,g->palette[i].g,g->palette[i].b); #endif /* defined(DEBUG) && !defined(NGIFLIB_NO_FILE) */ } #ifdef NGIFLIB_ENABLE_CALLBACKS if(g->palette_cb) g->palette_cb(g, g->palette, g->ncolors); #endif /* NGIFLIB_ENABLE_CALLBACKS */ } else { g->palette = NULL; } g->netscape_loop_count = -1; } for(;;) { char appid_auth[11]; u8 id,size; int blockindex; sign = GetByte(g); /* signature du prochain bloc */ #if !defined(NGIFLIB_NO_FILE) if(g->log) fprintf(g->log, "BLOCK SIGNATURE 0x%02X '%c'\n", sign, (sign >= 32) ? sign : '.'); #endif /* NGIFLIB_INDEXED_ONLY */ switch(sign) { case 0x3B: /* END OF GIF */ return 0; case '!': /* Extension introducer 0x21 */ id = GetByte(g); blockindex = 0; #if !defined(NGIFLIB_NO_FILE) if(g->log) fprintf(g->log, "extension (id=0x%02hhx)\n", id); #endif /* NGIFLIB_NO_FILE */ while( (size = GetByte(g)) ) { u8 ext[256]; GetByteStr(g, ext, size); switch(id) { case 0xF9: /* Graphic Control Extension */ /* The scope of this extension is the first graphic * rendering block to follow. */ gce.gce_present = 1; gce.disposal_method = (ext[0] >> 2) & 7; gce.transparent_flag = ext[0] & 1; gce.user_input_flag = (ext[0] >> 1) & 1; gce.delay_time = ext[1] | (ext[2]<<8); gce.transparent_color = ext[3]; #if !defined(NGIFLIB_NO_FILE) if(g->log) fprintf(g->log, "disposal_method=%hhu delay_time=%hu (transp=%hhu)transparent_color=0x%02hhX\n", gce.disposal_method, gce.delay_time, gce.transparent_flag, gce.transparent_color); #endif /* NGIFLIB_INDEXED_ONLY */ /* this propably should be adjusted depending on the disposal_method * of the _previous_ image. */ if(gce.transparent_flag && ((g->nimg == 0) || gce.disposal_method == 2)) { FillGifBackGround(g); } break; case 0xFE: /* Comment Extension. */ #if !defined(NGIFLIB_NO_FILE) if(g->log) { if(blockindex==0) fprintf(g->log, "-------------------- Comment extension --------------------\n"); ext[size] = '\0'; fputs((char *)ext, g->log); } #endif /* NGIFLIB_NO_FILE */ break; case 0xFF: /* application extension */ /* NETSCAPE2.0 extension : * http://www.vurdalakov.net/misc/gif/netscape-looping-application-extension */ if(blockindex==0) { ngiflib_memcpy(appid_auth, ext, 11); #if !defined(NGIFLIB_NO_FILE) if(g->log) { fprintf(g->log, "---------------- Application extension ---------------\n"); fprintf(g->log, "Application identifier : '%.8s', auth code : %02X %02X %02X (", appid_auth, ext[8], ext[9], ext[10]); fputc((ext[8]<32)?' ':ext[8], g->log); fputc((ext[9]<32)?' ':ext[9], g->log); fputc((ext[10]<32)?' ':ext[10], g->log); fprintf(g->log, ")\n"); } #endif /* NGIFLIB_INDEXED_ONLY */ } else { #if !defined(NGIFLIB_NO_FILE) if(g->log) { fprintf(g->log, "Datas (as hex) : "); for(i=0; i<size; i++) { fprintf(g->log, "%02x ", ext[i]); } fprintf(g->log, "\nDatas (as text) : '"); for(i=0; i<size; i++) { putc((ext[i]<32)?' ':ext[i], g->log); } fprintf(g->log, "'\n"); } #endif /* NGIFLIB_INDEXED_ONLY */ if(0 == ngiflib_memcmp(appid_auth, "NETSCAPE2.0", 11)) { /* ext[0] : Sub-block ID */ if(ext[0] == 1) { /* 1 : Netscape Looping Extension. */ g->netscape_loop_count = (int)ext[1] | ((int)ext[2] << 8); #if !defined(NGIFLIB_NO_FILE) if(g->log) { fprintf(g->log, "NETSCAPE loop_count = %d\n", g->netscape_loop_count); } #endif /* NGIFLIB_NO_FILE */ } } } break; case 0x01: /* plain text extension */ #if !defined(NGIFLIB_NO_FILE) if(g->log) { fprintf(g->log, "Plain text extension blockindex=%d\n", blockindex); for(i=0; i<size; i++) { putc((ext[i]<32)?' ':ext[i], g->log); } putc('\n', g->log); } #endif /* NGIFLIB_INDEXED_ONLY */ break; } blockindex++; } switch(id) { case 0x01: /* plain text extension */ case 0xFE: /* Comment Extension. */ case 0xFF: /* application extension */ #if !defined(NGIFLIB_NO_FILE) if(g->log) { fprintf(g->log, "-----------------------------------------------------------\n"); } #endif /* NGIFLIB_NO_FILE */ break; } break; case 0x2C: /* Image separator */ if(g->nimg==0) { g->cur_img = ngiflib_malloc(sizeof(struct ngiflib_img)); g->first_img = g->cur_img; } else { g->cur_img->next = ngiflib_malloc(sizeof(struct ngiflib_img)); g->cur_img = g->cur_img->next; } g->cur_img->next = NULL; g->cur_img->parent = g; if(gce.gce_present) { ngiflib_memcpy(&g->cur_img->gce, &gce, sizeof(struct ngiflib_gce)); } else { ngiflib_memset(&g->cur_img->gce, 0, sizeof(struct ngiflib_gce)); } DecodeGifImg(g->cur_img); g->nimg++; tmp = GetByte(g);/* 0 final */ #if !defined(NGIFLIB_NO_FILE) if(g->log) fprintf(g->log, "ZERO TERMINATOR 0x%02X\n", tmp); #endif /* NGIFLIB_INDEXED_ONLY */ return 1; /* image decod�e */ default: /* unexpected byte */ #if !defined(NGIFLIB_NO_FILE) if(g->log) fprintf(g->log, "unexpected signature 0x%02X\n", sign); #endif /* NGIFLIB_INDEXED_ONLY */ return -1; } } } u32 GifIndexToTrueColor(struct ngiflib_rgb * palette, u8 v) { return palette[v].b | (palette[v].g << 8) | (palette[v].r << 16); }
./CrossVul/dataset_final_sorted/CWE-119/c/good_105_0
crossvul-cpp_data_bad_5766_0
/* * IPVS An implementation of the IP virtual server support for the * LINUX operating system. IPVS is now implemented as a module * over the NetFilter framework. IPVS can be used to build a * high-performance and highly available server based on a * cluster of servers. * * Authors: Wensong Zhang <wensong@linuxvirtualserver.org> * Peter Kese <peter.kese@ijs.si> * Julian Anastasov <ja@ssi.bg> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * Changes: * */ #define KMSG_COMPONENT "IPVS" #define pr_fmt(fmt) KMSG_COMPONENT ": " fmt #include <linux/module.h> #include <linux/init.h> #include <linux/types.h> #include <linux/capability.h> #include <linux/fs.h> #include <linux/sysctl.h> #include <linux/proc_fs.h> #include <linux/workqueue.h> #include <linux/swap.h> #include <linux/seq_file.h> #include <linux/netfilter.h> #include <linux/netfilter_ipv4.h> #include <linux/mutex.h> #include <net/net_namespace.h> #include <net/ip.h> #ifdef CONFIG_IP_VS_IPV6 #include <net/ipv6.h> #include <net/ip6_route.h> #endif #include <net/route.h> #include <net/sock.h> #include <net/genetlink.h> #include <asm/uaccess.h> #include <net/ip_vs.h> /* semaphore for IPVS sockopts. And, [gs]etsockopt may sleep. */ static DEFINE_MUTEX(__ip_vs_mutex); /* lock for service table */ static DEFINE_RWLOCK(__ip_vs_svc_lock); /* lock for table with the real services */ static DEFINE_RWLOCK(__ip_vs_rs_lock); /* lock for state and timeout tables */ static DEFINE_RWLOCK(__ip_vs_securetcp_lock); /* lock for drop entry handling */ static DEFINE_SPINLOCK(__ip_vs_dropentry_lock); /* lock for drop packet handling */ static DEFINE_SPINLOCK(__ip_vs_droppacket_lock); /* 1/rate drop and drop-entry variables */ int ip_vs_drop_rate = 0; int ip_vs_drop_counter = 0; static atomic_t ip_vs_dropentry = ATOMIC_INIT(0); /* number of virtual services */ static int ip_vs_num_services = 0; /* sysctl variables */ static int sysctl_ip_vs_drop_entry = 0; static int sysctl_ip_vs_drop_packet = 0; static int sysctl_ip_vs_secure_tcp = 0; static int sysctl_ip_vs_amemthresh = 1024; static int sysctl_ip_vs_am_droprate = 10; int sysctl_ip_vs_cache_bypass = 0; int sysctl_ip_vs_expire_nodest_conn = 0; int sysctl_ip_vs_expire_quiescent_template = 0; int sysctl_ip_vs_sync_threshold[2] = { 3, 50 }; int sysctl_ip_vs_nat_icmp_send = 0; #ifdef CONFIG_IP_VS_DEBUG static int sysctl_ip_vs_debug_level = 0; int ip_vs_get_debug_level(void) { return sysctl_ip_vs_debug_level; } #endif #ifdef CONFIG_IP_VS_IPV6 /* Taken from rt6_fill_node() in net/ipv6/route.c, is there a better way? */ static int __ip_vs_addr_is_local_v6(const struct in6_addr *addr) { struct rt6_info *rt; struct flowi fl = { .oif = 0, .nl_u = { .ip6_u = { .daddr = *addr, .saddr = { .s6_addr32 = {0, 0, 0, 0} }, } }, }; rt = (struct rt6_info *)ip6_route_output(&init_net, NULL, &fl); if (rt && rt->rt6i_dev && (rt->rt6i_dev->flags & IFF_LOOPBACK)) return 1; return 0; } #endif /* * update_defense_level is called from keventd and from sysctl, * so it needs to protect itself from softirqs */ static void update_defense_level(void) { struct sysinfo i; static int old_secure_tcp = 0; int availmem; int nomem; int to_change = -1; /* we only count free and buffered memory (in pages) */ si_meminfo(&i); availmem = i.freeram + i.bufferram; /* however in linux 2.5 the i.bufferram is total page cache size, we need adjust it */ /* si_swapinfo(&i); */ /* availmem = availmem - (i.totalswap - i.freeswap); */ nomem = (availmem < sysctl_ip_vs_amemthresh); local_bh_disable(); /* drop_entry */ spin_lock(&__ip_vs_dropentry_lock); switch (sysctl_ip_vs_drop_entry) { case 0: atomic_set(&ip_vs_dropentry, 0); break; case 1: if (nomem) { atomic_set(&ip_vs_dropentry, 1); sysctl_ip_vs_drop_entry = 2; } else { atomic_set(&ip_vs_dropentry, 0); } break; case 2: if (nomem) { atomic_set(&ip_vs_dropentry, 1); } else { atomic_set(&ip_vs_dropentry, 0); sysctl_ip_vs_drop_entry = 1; }; break; case 3: atomic_set(&ip_vs_dropentry, 1); break; } spin_unlock(&__ip_vs_dropentry_lock); /* drop_packet */ spin_lock(&__ip_vs_droppacket_lock); switch (sysctl_ip_vs_drop_packet) { case 0: ip_vs_drop_rate = 0; break; case 1: if (nomem) { ip_vs_drop_rate = ip_vs_drop_counter = sysctl_ip_vs_amemthresh / (sysctl_ip_vs_amemthresh-availmem); sysctl_ip_vs_drop_packet = 2; } else { ip_vs_drop_rate = 0; } break; case 2: if (nomem) { ip_vs_drop_rate = ip_vs_drop_counter = sysctl_ip_vs_amemthresh / (sysctl_ip_vs_amemthresh-availmem); } else { ip_vs_drop_rate = 0; sysctl_ip_vs_drop_packet = 1; } break; case 3: ip_vs_drop_rate = sysctl_ip_vs_am_droprate; break; } spin_unlock(&__ip_vs_droppacket_lock); /* secure_tcp */ write_lock(&__ip_vs_securetcp_lock); switch (sysctl_ip_vs_secure_tcp) { case 0: if (old_secure_tcp >= 2) to_change = 0; break; case 1: if (nomem) { if (old_secure_tcp < 2) to_change = 1; sysctl_ip_vs_secure_tcp = 2; } else { if (old_secure_tcp >= 2) to_change = 0; } break; case 2: if (nomem) { if (old_secure_tcp < 2) to_change = 1; } else { if (old_secure_tcp >= 2) to_change = 0; sysctl_ip_vs_secure_tcp = 1; } break; case 3: if (old_secure_tcp < 2) to_change = 1; break; } old_secure_tcp = sysctl_ip_vs_secure_tcp; if (to_change >= 0) ip_vs_protocol_timeout_change(sysctl_ip_vs_secure_tcp>1); write_unlock(&__ip_vs_securetcp_lock); local_bh_enable(); } /* * Timer for checking the defense */ #define DEFENSE_TIMER_PERIOD 1*HZ static void defense_work_handler(struct work_struct *work); static DECLARE_DELAYED_WORK(defense_work, defense_work_handler); static void defense_work_handler(struct work_struct *work) { update_defense_level(); if (atomic_read(&ip_vs_dropentry)) ip_vs_random_dropentry(); schedule_delayed_work(&defense_work, DEFENSE_TIMER_PERIOD); } int ip_vs_use_count_inc(void) { return try_module_get(THIS_MODULE); } void ip_vs_use_count_dec(void) { module_put(THIS_MODULE); } /* * Hash table: for virtual service lookups */ #define IP_VS_SVC_TAB_BITS 8 #define IP_VS_SVC_TAB_SIZE (1 << IP_VS_SVC_TAB_BITS) #define IP_VS_SVC_TAB_MASK (IP_VS_SVC_TAB_SIZE - 1) /* the service table hashed by <protocol, addr, port> */ static struct list_head ip_vs_svc_table[IP_VS_SVC_TAB_SIZE]; /* the service table hashed by fwmark */ static struct list_head ip_vs_svc_fwm_table[IP_VS_SVC_TAB_SIZE]; /* * Hash table: for real service lookups */ #define IP_VS_RTAB_BITS 4 #define IP_VS_RTAB_SIZE (1 << IP_VS_RTAB_BITS) #define IP_VS_RTAB_MASK (IP_VS_RTAB_SIZE - 1) static struct list_head ip_vs_rtable[IP_VS_RTAB_SIZE]; /* * Trash for destinations */ static LIST_HEAD(ip_vs_dest_trash); /* * FTP & NULL virtual service counters */ static atomic_t ip_vs_ftpsvc_counter = ATOMIC_INIT(0); static atomic_t ip_vs_nullsvc_counter = ATOMIC_INIT(0); /* * Returns hash value for virtual service */ static __inline__ unsigned ip_vs_svc_hashkey(int af, unsigned proto, const union nf_inet_addr *addr, __be16 port) { register unsigned porth = ntohs(port); __be32 addr_fold = addr->ip; #ifdef CONFIG_IP_VS_IPV6 if (af == AF_INET6) addr_fold = addr->ip6[0]^addr->ip6[1]^ addr->ip6[2]^addr->ip6[3]; #endif return (proto^ntohl(addr_fold)^(porth>>IP_VS_SVC_TAB_BITS)^porth) & IP_VS_SVC_TAB_MASK; } /* * Returns hash value of fwmark for virtual service lookup */ static __inline__ unsigned ip_vs_svc_fwm_hashkey(__u32 fwmark) { return fwmark & IP_VS_SVC_TAB_MASK; } /* * Hashes a service in the ip_vs_svc_table by <proto,addr,port> * or in the ip_vs_svc_fwm_table by fwmark. * Should be called with locked tables. */ static int ip_vs_svc_hash(struct ip_vs_service *svc) { unsigned hash; if (svc->flags & IP_VS_SVC_F_HASHED) { pr_err("%s(): request for already hashed, called from %pF\n", __func__, __builtin_return_address(0)); return 0; } if (svc->fwmark == 0) { /* * Hash it by <protocol,addr,port> in ip_vs_svc_table */ hash = ip_vs_svc_hashkey(svc->af, svc->protocol, &svc->addr, svc->port); list_add(&svc->s_list, &ip_vs_svc_table[hash]); } else { /* * Hash it by fwmark in ip_vs_svc_fwm_table */ hash = ip_vs_svc_fwm_hashkey(svc->fwmark); list_add(&svc->f_list, &ip_vs_svc_fwm_table[hash]); } svc->flags |= IP_VS_SVC_F_HASHED; /* increase its refcnt because it is referenced by the svc table */ atomic_inc(&svc->refcnt); return 1; } /* * Unhashes a service from ip_vs_svc_table/ip_vs_svc_fwm_table. * Should be called with locked tables. */ static int ip_vs_svc_unhash(struct ip_vs_service *svc) { if (!(svc->flags & IP_VS_SVC_F_HASHED)) { pr_err("%s(): request for unhash flagged, called from %pF\n", __func__, __builtin_return_address(0)); return 0; } if (svc->fwmark == 0) { /* Remove it from the ip_vs_svc_table table */ list_del(&svc->s_list); } else { /* Remove it from the ip_vs_svc_fwm_table table */ list_del(&svc->f_list); } svc->flags &= ~IP_VS_SVC_F_HASHED; atomic_dec(&svc->refcnt); return 1; } /* * Get service by {proto,addr,port} in the service table. */ static inline struct ip_vs_service * __ip_vs_service_get(int af, __u16 protocol, const union nf_inet_addr *vaddr, __be16 vport) { unsigned hash; struct ip_vs_service *svc; /* Check for "full" addressed entries */ hash = ip_vs_svc_hashkey(af, protocol, vaddr, vport); list_for_each_entry(svc, &ip_vs_svc_table[hash], s_list){ if ((svc->af == af) && ip_vs_addr_equal(af, &svc->addr, vaddr) && (svc->port == vport) && (svc->protocol == protocol)) { /* HIT */ atomic_inc(&svc->usecnt); return svc; } } return NULL; } /* * Get service by {fwmark} in the service table. */ static inline struct ip_vs_service * __ip_vs_svc_fwm_get(int af, __u32 fwmark) { unsigned hash; struct ip_vs_service *svc; /* Check for fwmark addressed entries */ hash = ip_vs_svc_fwm_hashkey(fwmark); list_for_each_entry(svc, &ip_vs_svc_fwm_table[hash], f_list) { if (svc->fwmark == fwmark && svc->af == af) { /* HIT */ atomic_inc(&svc->usecnt); return svc; } } return NULL; } struct ip_vs_service * ip_vs_service_get(int af, __u32 fwmark, __u16 protocol, const union nf_inet_addr *vaddr, __be16 vport) { struct ip_vs_service *svc; read_lock(&__ip_vs_svc_lock); /* * Check the table hashed by fwmark first */ if (fwmark && (svc = __ip_vs_svc_fwm_get(af, fwmark))) goto out; /* * Check the table hashed by <protocol,addr,port> * for "full" addressed entries */ svc = __ip_vs_service_get(af, protocol, vaddr, vport); if (svc == NULL && protocol == IPPROTO_TCP && atomic_read(&ip_vs_ftpsvc_counter) && (vport == FTPDATA || ntohs(vport) >= PROT_SOCK)) { /* * Check if ftp service entry exists, the packet * might belong to FTP data connections. */ svc = __ip_vs_service_get(af, protocol, vaddr, FTPPORT); } if (svc == NULL && atomic_read(&ip_vs_nullsvc_counter)) { /* * Check if the catch-all port (port zero) exists */ svc = __ip_vs_service_get(af, protocol, vaddr, 0); } out: read_unlock(&__ip_vs_svc_lock); IP_VS_DBG_BUF(9, "lookup service: fwm %u %s %s:%u %s\n", fwmark, ip_vs_proto_name(protocol), IP_VS_DBG_ADDR(af, vaddr), ntohs(vport), svc ? "hit" : "not hit"); return svc; } static inline void __ip_vs_bind_svc(struct ip_vs_dest *dest, struct ip_vs_service *svc) { atomic_inc(&svc->refcnt); dest->svc = svc; } static inline void __ip_vs_unbind_svc(struct ip_vs_dest *dest) { struct ip_vs_service *svc = dest->svc; dest->svc = NULL; if (atomic_dec_and_test(&svc->refcnt)) kfree(svc); } /* * Returns hash value for real service */ static inline unsigned ip_vs_rs_hashkey(int af, const union nf_inet_addr *addr, __be16 port) { register unsigned porth = ntohs(port); __be32 addr_fold = addr->ip; #ifdef CONFIG_IP_VS_IPV6 if (af == AF_INET6) addr_fold = addr->ip6[0]^addr->ip6[1]^ addr->ip6[2]^addr->ip6[3]; #endif return (ntohl(addr_fold)^(porth>>IP_VS_RTAB_BITS)^porth) & IP_VS_RTAB_MASK; } /* * Hashes ip_vs_dest in ip_vs_rtable by <proto,addr,port>. * should be called with locked tables. */ static int ip_vs_rs_hash(struct ip_vs_dest *dest) { unsigned hash; if (!list_empty(&dest->d_list)) { return 0; } /* * Hash by proto,addr,port, * which are the parameters of the real service. */ hash = ip_vs_rs_hashkey(dest->af, &dest->addr, dest->port); list_add(&dest->d_list, &ip_vs_rtable[hash]); return 1; } /* * UNhashes ip_vs_dest from ip_vs_rtable. * should be called with locked tables. */ static int ip_vs_rs_unhash(struct ip_vs_dest *dest) { /* * Remove it from the ip_vs_rtable table. */ if (!list_empty(&dest->d_list)) { list_del(&dest->d_list); INIT_LIST_HEAD(&dest->d_list); } return 1; } /* * Lookup real service by <proto,addr,port> in the real service table. */ struct ip_vs_dest * ip_vs_lookup_real_service(int af, __u16 protocol, const union nf_inet_addr *daddr, __be16 dport) { unsigned hash; struct ip_vs_dest *dest; /* * Check for "full" addressed entries * Return the first found entry */ hash = ip_vs_rs_hashkey(af, daddr, dport); read_lock(&__ip_vs_rs_lock); list_for_each_entry(dest, &ip_vs_rtable[hash], d_list) { if ((dest->af == af) && ip_vs_addr_equal(af, &dest->addr, daddr) && (dest->port == dport) && ((dest->protocol == protocol) || dest->vfwmark)) { /* HIT */ read_unlock(&__ip_vs_rs_lock); return dest; } } read_unlock(&__ip_vs_rs_lock); return NULL; } /* * Lookup destination by {addr,port} in the given service */ static struct ip_vs_dest * ip_vs_lookup_dest(struct ip_vs_service *svc, const union nf_inet_addr *daddr, __be16 dport) { struct ip_vs_dest *dest; /* * Find the destination for the given service */ list_for_each_entry(dest, &svc->destinations, n_list) { if ((dest->af == svc->af) && ip_vs_addr_equal(svc->af, &dest->addr, daddr) && (dest->port == dport)) { /* HIT */ return dest; } } return NULL; } /* * Find destination by {daddr,dport,vaddr,protocol} * Cretaed to be used in ip_vs_process_message() in * the backup synchronization daemon. It finds the * destination to be bound to the received connection * on the backup. * * ip_vs_lookup_real_service() looked promissing, but * seems not working as expected. */ struct ip_vs_dest *ip_vs_find_dest(int af, const union nf_inet_addr *daddr, __be16 dport, const union nf_inet_addr *vaddr, __be16 vport, __u16 protocol) { struct ip_vs_dest *dest; struct ip_vs_service *svc; svc = ip_vs_service_get(af, 0, protocol, vaddr, vport); if (!svc) return NULL; dest = ip_vs_lookup_dest(svc, daddr, dport); if (dest) atomic_inc(&dest->refcnt); ip_vs_service_put(svc); return dest; } /* * Lookup dest by {svc,addr,port} in the destination trash. * The destination trash is used to hold the destinations that are removed * from the service table but are still referenced by some conn entries. * The reason to add the destination trash is when the dest is temporary * down (either by administrator or by monitor program), the dest can be * picked back from the trash, the remaining connections to the dest can * continue, and the counting information of the dest is also useful for * scheduling. */ static struct ip_vs_dest * ip_vs_trash_get_dest(struct ip_vs_service *svc, const union nf_inet_addr *daddr, __be16 dport) { struct ip_vs_dest *dest, *nxt; /* * Find the destination in trash */ list_for_each_entry_safe(dest, nxt, &ip_vs_dest_trash, n_list) { IP_VS_DBG_BUF(3, "Destination %u/%s:%u still in trash, " "dest->refcnt=%d\n", dest->vfwmark, IP_VS_DBG_ADDR(svc->af, &dest->addr), ntohs(dest->port), atomic_read(&dest->refcnt)); if (dest->af == svc->af && ip_vs_addr_equal(svc->af, &dest->addr, daddr) && dest->port == dport && dest->vfwmark == svc->fwmark && dest->protocol == svc->protocol && (svc->fwmark || (ip_vs_addr_equal(svc->af, &dest->vaddr, &svc->addr) && dest->vport == svc->port))) { /* HIT */ return dest; } /* * Try to purge the destination from trash if not referenced */ if (atomic_read(&dest->refcnt) == 1) { IP_VS_DBG_BUF(3, "Removing destination %u/%s:%u " "from trash\n", dest->vfwmark, IP_VS_DBG_ADDR(svc->af, &dest->addr), ntohs(dest->port)); list_del(&dest->n_list); ip_vs_dst_reset(dest); __ip_vs_unbind_svc(dest); kfree(dest); } } return NULL; } /* * Clean up all the destinations in the trash * Called by the ip_vs_control_cleanup() * * When the ip_vs_control_clearup is activated by ipvs module exit, * the service tables must have been flushed and all the connections * are expired, and the refcnt of each destination in the trash must * be 1, so we simply release them here. */ static void ip_vs_trash_cleanup(void) { struct ip_vs_dest *dest, *nxt; list_for_each_entry_safe(dest, nxt, &ip_vs_dest_trash, n_list) { list_del(&dest->n_list); ip_vs_dst_reset(dest); __ip_vs_unbind_svc(dest); kfree(dest); } } static void ip_vs_zero_stats(struct ip_vs_stats *stats) { spin_lock_bh(&stats->lock); memset(&stats->ustats, 0, sizeof(stats->ustats)); ip_vs_zero_estimator(stats); spin_unlock_bh(&stats->lock); } /* * Update a destination in the given service */ static void __ip_vs_update_dest(struct ip_vs_service *svc, struct ip_vs_dest *dest, struct ip_vs_dest_user_kern *udest) { int conn_flags; /* set the weight and the flags */ atomic_set(&dest->weight, udest->weight); conn_flags = udest->conn_flags | IP_VS_CONN_F_INACTIVE; /* check if local node and update the flags */ #ifdef CONFIG_IP_VS_IPV6 if (svc->af == AF_INET6) { if (__ip_vs_addr_is_local_v6(&udest->addr.in6)) { conn_flags = (conn_flags & ~IP_VS_CONN_F_FWD_MASK) | IP_VS_CONN_F_LOCALNODE; } } else #endif if (inet_addr_type(&init_net, udest->addr.ip) == RTN_LOCAL) { conn_flags = (conn_flags & ~IP_VS_CONN_F_FWD_MASK) | IP_VS_CONN_F_LOCALNODE; } /* set the IP_VS_CONN_F_NOOUTPUT flag if not masquerading/NAT */ if ((conn_flags & IP_VS_CONN_F_FWD_MASK) != 0) { conn_flags |= IP_VS_CONN_F_NOOUTPUT; } else { /* * Put the real service in ip_vs_rtable if not present. * For now only for NAT! */ write_lock_bh(&__ip_vs_rs_lock); ip_vs_rs_hash(dest); write_unlock_bh(&__ip_vs_rs_lock); } atomic_set(&dest->conn_flags, conn_flags); /* bind the service */ if (!dest->svc) { __ip_vs_bind_svc(dest, svc); } else { if (dest->svc != svc) { __ip_vs_unbind_svc(dest); ip_vs_zero_stats(&dest->stats); __ip_vs_bind_svc(dest, svc); } } /* set the dest status flags */ dest->flags |= IP_VS_DEST_F_AVAILABLE; if (udest->u_threshold == 0 || udest->u_threshold > dest->u_threshold) dest->flags &= ~IP_VS_DEST_F_OVERLOAD; dest->u_threshold = udest->u_threshold; dest->l_threshold = udest->l_threshold; } /* * Create a destination for the given service */ static int ip_vs_new_dest(struct ip_vs_service *svc, struct ip_vs_dest_user_kern *udest, struct ip_vs_dest **dest_p) { struct ip_vs_dest *dest; unsigned atype; EnterFunction(2); #ifdef CONFIG_IP_VS_IPV6 if (svc->af == AF_INET6) { atype = ipv6_addr_type(&udest->addr.in6); if ((!(atype & IPV6_ADDR_UNICAST) || atype & IPV6_ADDR_LINKLOCAL) && !__ip_vs_addr_is_local_v6(&udest->addr.in6)) return -EINVAL; } else #endif { atype = inet_addr_type(&init_net, udest->addr.ip); if (atype != RTN_LOCAL && atype != RTN_UNICAST) return -EINVAL; } dest = kzalloc(sizeof(struct ip_vs_dest), GFP_ATOMIC); if (dest == NULL) { pr_err("%s(): no memory.\n", __func__); return -ENOMEM; } dest->af = svc->af; dest->protocol = svc->protocol; dest->vaddr = svc->addr; dest->vport = svc->port; dest->vfwmark = svc->fwmark; ip_vs_addr_copy(svc->af, &dest->addr, &udest->addr); dest->port = udest->port; atomic_set(&dest->activeconns, 0); atomic_set(&dest->inactconns, 0); atomic_set(&dest->persistconns, 0); atomic_set(&dest->refcnt, 0); INIT_LIST_HEAD(&dest->d_list); spin_lock_init(&dest->dst_lock); spin_lock_init(&dest->stats.lock); __ip_vs_update_dest(svc, dest, udest); ip_vs_new_estimator(&dest->stats); *dest_p = dest; LeaveFunction(2); return 0; } /* * Add a destination into an existing service */ static int ip_vs_add_dest(struct ip_vs_service *svc, struct ip_vs_dest_user_kern *udest) { struct ip_vs_dest *dest; union nf_inet_addr daddr; __be16 dport = udest->port; int ret; EnterFunction(2); if (udest->weight < 0) { pr_err("%s(): server weight less than zero\n", __func__); return -ERANGE; } if (udest->l_threshold > udest->u_threshold) { pr_err("%s(): lower threshold is higher than upper threshold\n", __func__); return -ERANGE; } ip_vs_addr_copy(svc->af, &daddr, &udest->addr); /* * Check if the dest already exists in the list */ dest = ip_vs_lookup_dest(svc, &daddr, dport); if (dest != NULL) { IP_VS_DBG(1, "%s(): dest already exists\n", __func__); return -EEXIST; } /* * Check if the dest already exists in the trash and * is from the same service */ dest = ip_vs_trash_get_dest(svc, &daddr, dport); if (dest != NULL) { IP_VS_DBG_BUF(3, "Get destination %s:%u from trash, " "dest->refcnt=%d, service %u/%s:%u\n", IP_VS_DBG_ADDR(svc->af, &daddr), ntohs(dport), atomic_read(&dest->refcnt), dest->vfwmark, IP_VS_DBG_ADDR(svc->af, &dest->vaddr), ntohs(dest->vport)); __ip_vs_update_dest(svc, dest, udest); /* * Get the destination from the trash */ list_del(&dest->n_list); ip_vs_new_estimator(&dest->stats); write_lock_bh(&__ip_vs_svc_lock); /* * Wait until all other svc users go away. */ IP_VS_WAIT_WHILE(atomic_read(&svc->usecnt) > 1); list_add(&dest->n_list, &svc->destinations); svc->num_dests++; /* call the update_service function of its scheduler */ if (svc->scheduler->update_service) svc->scheduler->update_service(svc); write_unlock_bh(&__ip_vs_svc_lock); return 0; } /* * Allocate and initialize the dest structure */ ret = ip_vs_new_dest(svc, udest, &dest); if (ret) { return ret; } /* * Add the dest entry into the list */ atomic_inc(&dest->refcnt); write_lock_bh(&__ip_vs_svc_lock); /* * Wait until all other svc users go away. */ IP_VS_WAIT_WHILE(atomic_read(&svc->usecnt) > 1); list_add(&dest->n_list, &svc->destinations); svc->num_dests++; /* call the update_service function of its scheduler */ if (svc->scheduler->update_service) svc->scheduler->update_service(svc); write_unlock_bh(&__ip_vs_svc_lock); LeaveFunction(2); return 0; } /* * Edit a destination in the given service */ static int ip_vs_edit_dest(struct ip_vs_service *svc, struct ip_vs_dest_user_kern *udest) { struct ip_vs_dest *dest; union nf_inet_addr daddr; __be16 dport = udest->port; EnterFunction(2); if (udest->weight < 0) { pr_err("%s(): server weight less than zero\n", __func__); return -ERANGE; } if (udest->l_threshold > udest->u_threshold) { pr_err("%s(): lower threshold is higher than upper threshold\n", __func__); return -ERANGE; } ip_vs_addr_copy(svc->af, &daddr, &udest->addr); /* * Lookup the destination list */ dest = ip_vs_lookup_dest(svc, &daddr, dport); if (dest == NULL) { IP_VS_DBG(1, "%s(): dest doesn't exist\n", __func__); return -ENOENT; } __ip_vs_update_dest(svc, dest, udest); write_lock_bh(&__ip_vs_svc_lock); /* Wait until all other svc users go away */ IP_VS_WAIT_WHILE(atomic_read(&svc->usecnt) > 1); /* call the update_service, because server weight may be changed */ if (svc->scheduler->update_service) svc->scheduler->update_service(svc); write_unlock_bh(&__ip_vs_svc_lock); LeaveFunction(2); return 0; } /* * Delete a destination (must be already unlinked from the service) */ static void __ip_vs_del_dest(struct ip_vs_dest *dest) { ip_vs_kill_estimator(&dest->stats); /* * Remove it from the d-linked list with the real services. */ write_lock_bh(&__ip_vs_rs_lock); ip_vs_rs_unhash(dest); write_unlock_bh(&__ip_vs_rs_lock); /* * Decrease the refcnt of the dest, and free the dest * if nobody refers to it (refcnt=0). Otherwise, throw * the destination into the trash. */ if (atomic_dec_and_test(&dest->refcnt)) { ip_vs_dst_reset(dest); /* simply decrease svc->refcnt here, let the caller check and release the service if nobody refers to it. Only user context can release destination and service, and only one user context can update virtual service at a time, so the operation here is OK */ atomic_dec(&dest->svc->refcnt); kfree(dest); } else { IP_VS_DBG_BUF(3, "Moving dest %s:%u into trash, " "dest->refcnt=%d\n", IP_VS_DBG_ADDR(dest->af, &dest->addr), ntohs(dest->port), atomic_read(&dest->refcnt)); list_add(&dest->n_list, &ip_vs_dest_trash); atomic_inc(&dest->refcnt); } } /* * Unlink a destination from the given service */ static void __ip_vs_unlink_dest(struct ip_vs_service *svc, struct ip_vs_dest *dest, int svcupd) { dest->flags &= ~IP_VS_DEST_F_AVAILABLE; /* * Remove it from the d-linked destination list. */ list_del(&dest->n_list); svc->num_dests--; /* * Call the update_service function of its scheduler */ if (svcupd && svc->scheduler->update_service) svc->scheduler->update_service(svc); } /* * Delete a destination server in the given service */ static int ip_vs_del_dest(struct ip_vs_service *svc, struct ip_vs_dest_user_kern *udest) { struct ip_vs_dest *dest; __be16 dport = udest->port; EnterFunction(2); dest = ip_vs_lookup_dest(svc, &udest->addr, dport); if (dest == NULL) { IP_VS_DBG(1, "%s(): destination not found!\n", __func__); return -ENOENT; } write_lock_bh(&__ip_vs_svc_lock); /* * Wait until all other svc users go away. */ IP_VS_WAIT_WHILE(atomic_read(&svc->usecnt) > 1); /* * Unlink dest from the service */ __ip_vs_unlink_dest(svc, dest, 1); write_unlock_bh(&__ip_vs_svc_lock); /* * Delete the destination */ __ip_vs_del_dest(dest); LeaveFunction(2); return 0; } /* * Add a service into the service hash table */ static int ip_vs_add_service(struct ip_vs_service_user_kern *u, struct ip_vs_service **svc_p) { int ret = 0; struct ip_vs_scheduler *sched = NULL; struct ip_vs_service *svc = NULL; /* increase the module use count */ ip_vs_use_count_inc(); /* Lookup the scheduler by 'u->sched_name' */ sched = ip_vs_scheduler_get(u->sched_name); if (sched == NULL) { pr_info("Scheduler module ip_vs_%s not found\n", u->sched_name); ret = -ENOENT; goto out_mod_dec; } #ifdef CONFIG_IP_VS_IPV6 if (u->af == AF_INET6 && (u->netmask < 1 || u->netmask > 128)) { ret = -EINVAL; goto out_err; } #endif svc = kzalloc(sizeof(struct ip_vs_service), GFP_ATOMIC); if (svc == NULL) { IP_VS_DBG(1, "%s(): no memory\n", __func__); ret = -ENOMEM; goto out_err; } /* I'm the first user of the service */ atomic_set(&svc->usecnt, 1); atomic_set(&svc->refcnt, 0); svc->af = u->af; svc->protocol = u->protocol; ip_vs_addr_copy(svc->af, &svc->addr, &u->addr); svc->port = u->port; svc->fwmark = u->fwmark; svc->flags = u->flags; svc->timeout = u->timeout * HZ; svc->netmask = u->netmask; INIT_LIST_HEAD(&svc->destinations); rwlock_init(&svc->sched_lock); spin_lock_init(&svc->stats.lock); /* Bind the scheduler */ ret = ip_vs_bind_scheduler(svc, sched); if (ret) goto out_err; sched = NULL; /* Update the virtual service counters */ if (svc->port == FTPPORT) atomic_inc(&ip_vs_ftpsvc_counter); else if (svc->port == 0) atomic_inc(&ip_vs_nullsvc_counter); ip_vs_new_estimator(&svc->stats); /* Count only IPv4 services for old get/setsockopt interface */ if (svc->af == AF_INET) ip_vs_num_services++; /* Hash the service into the service table */ write_lock_bh(&__ip_vs_svc_lock); ip_vs_svc_hash(svc); write_unlock_bh(&__ip_vs_svc_lock); *svc_p = svc; return 0; out_err: if (svc != NULL) { if (svc->scheduler) ip_vs_unbind_scheduler(svc); if (svc->inc) { local_bh_disable(); ip_vs_app_inc_put(svc->inc); local_bh_enable(); } kfree(svc); } ip_vs_scheduler_put(sched); out_mod_dec: /* decrease the module use count */ ip_vs_use_count_dec(); return ret; } /* * Edit a service and bind it with a new scheduler */ static int ip_vs_edit_service(struct ip_vs_service *svc, struct ip_vs_service_user_kern *u) { struct ip_vs_scheduler *sched, *old_sched; int ret = 0; /* * Lookup the scheduler, by 'u->sched_name' */ sched = ip_vs_scheduler_get(u->sched_name); if (sched == NULL) { pr_info("Scheduler module ip_vs_%s not found\n", u->sched_name); return -ENOENT; } old_sched = sched; #ifdef CONFIG_IP_VS_IPV6 if (u->af == AF_INET6 && (u->netmask < 1 || u->netmask > 128)) { ret = -EINVAL; goto out; } #endif write_lock_bh(&__ip_vs_svc_lock); /* * Wait until all other svc users go away. */ IP_VS_WAIT_WHILE(atomic_read(&svc->usecnt) > 1); /* * Set the flags and timeout value */ svc->flags = u->flags | IP_VS_SVC_F_HASHED; svc->timeout = u->timeout * HZ; svc->netmask = u->netmask; old_sched = svc->scheduler; if (sched != old_sched) { /* * Unbind the old scheduler */ if ((ret = ip_vs_unbind_scheduler(svc))) { old_sched = sched; goto out_unlock; } /* * Bind the new scheduler */ if ((ret = ip_vs_bind_scheduler(svc, sched))) { /* * If ip_vs_bind_scheduler fails, restore the old * scheduler. * The main reason of failure is out of memory. * * The question is if the old scheduler can be * restored all the time. TODO: if it cannot be * restored some time, we must delete the service, * otherwise the system may crash. */ ip_vs_bind_scheduler(svc, old_sched); old_sched = sched; goto out_unlock; } } out_unlock: write_unlock_bh(&__ip_vs_svc_lock); #ifdef CONFIG_IP_VS_IPV6 out: #endif if (old_sched) ip_vs_scheduler_put(old_sched); return ret; } /* * Delete a service from the service list * - The service must be unlinked, unlocked and not referenced! * - We are called under _bh lock */ static void __ip_vs_del_service(struct ip_vs_service *svc) { struct ip_vs_dest *dest, *nxt; struct ip_vs_scheduler *old_sched; /* Count only IPv4 services for old get/setsockopt interface */ if (svc->af == AF_INET) ip_vs_num_services--; ip_vs_kill_estimator(&svc->stats); /* Unbind scheduler */ old_sched = svc->scheduler; ip_vs_unbind_scheduler(svc); if (old_sched) ip_vs_scheduler_put(old_sched); /* Unbind app inc */ if (svc->inc) { ip_vs_app_inc_put(svc->inc); svc->inc = NULL; } /* * Unlink the whole destination list */ list_for_each_entry_safe(dest, nxt, &svc->destinations, n_list) { __ip_vs_unlink_dest(svc, dest, 0); __ip_vs_del_dest(dest); } /* * Update the virtual service counters */ if (svc->port == FTPPORT) atomic_dec(&ip_vs_ftpsvc_counter); else if (svc->port == 0) atomic_dec(&ip_vs_nullsvc_counter); /* * Free the service if nobody refers to it */ if (atomic_read(&svc->refcnt) == 0) kfree(svc); /* decrease the module use count */ ip_vs_use_count_dec(); } /* * Delete a service from the service list */ static int ip_vs_del_service(struct ip_vs_service *svc) { if (svc == NULL) return -EEXIST; /* * Unhash it from the service table */ write_lock_bh(&__ip_vs_svc_lock); ip_vs_svc_unhash(svc); /* * Wait until all the svc users go away. */ IP_VS_WAIT_WHILE(atomic_read(&svc->usecnt) > 1); __ip_vs_del_service(svc); write_unlock_bh(&__ip_vs_svc_lock); return 0; } /* * Flush all the virtual services */ static int ip_vs_flush(void) { int idx; struct ip_vs_service *svc, *nxt; /* * Flush the service table hashed by <protocol,addr,port> */ for(idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) { list_for_each_entry_safe(svc, nxt, &ip_vs_svc_table[idx], s_list) { write_lock_bh(&__ip_vs_svc_lock); ip_vs_svc_unhash(svc); /* * Wait until all the svc users go away. */ IP_VS_WAIT_WHILE(atomic_read(&svc->usecnt) > 0); __ip_vs_del_service(svc); write_unlock_bh(&__ip_vs_svc_lock); } } /* * Flush the service table hashed by fwmark */ for(idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) { list_for_each_entry_safe(svc, nxt, &ip_vs_svc_fwm_table[idx], f_list) { write_lock_bh(&__ip_vs_svc_lock); ip_vs_svc_unhash(svc); /* * Wait until all the svc users go away. */ IP_VS_WAIT_WHILE(atomic_read(&svc->usecnt) > 0); __ip_vs_del_service(svc); write_unlock_bh(&__ip_vs_svc_lock); } } return 0; } /* * Zero counters in a service or all services */ static int ip_vs_zero_service(struct ip_vs_service *svc) { struct ip_vs_dest *dest; write_lock_bh(&__ip_vs_svc_lock); list_for_each_entry(dest, &svc->destinations, n_list) { ip_vs_zero_stats(&dest->stats); } ip_vs_zero_stats(&svc->stats); write_unlock_bh(&__ip_vs_svc_lock); return 0; } static int ip_vs_zero_all(void) { int idx; struct ip_vs_service *svc; for(idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) { list_for_each_entry(svc, &ip_vs_svc_table[idx], s_list) { ip_vs_zero_service(svc); } } for(idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) { list_for_each_entry(svc, &ip_vs_svc_fwm_table[idx], f_list) { ip_vs_zero_service(svc); } } ip_vs_zero_stats(&ip_vs_stats); return 0; } static int proc_do_defense_mode(ctl_table *table, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { int *valp = table->data; int val = *valp; int rc; rc = proc_dointvec(table, write, buffer, lenp, ppos); if (write && (*valp != val)) { if ((*valp < 0) || (*valp > 3)) { /* Restore the correct value */ *valp = val; } else { update_defense_level(); } } return rc; } static int proc_do_sync_threshold(ctl_table *table, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { int *valp = table->data; int val[2]; int rc; /* backup the value first */ memcpy(val, valp, sizeof(val)); rc = proc_dointvec(table, write, buffer, lenp, ppos); if (write && (valp[0] < 0 || valp[1] < 0 || valp[0] >= valp[1])) { /* Restore the correct value */ memcpy(valp, val, sizeof(val)); } return rc; } /* * IPVS sysctl table (under the /proc/sys/net/ipv4/vs/) */ static struct ctl_table vs_vars[] = { { .procname = "amemthresh", .data = &sysctl_ip_vs_amemthresh, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, #ifdef CONFIG_IP_VS_DEBUG { .procname = "debug_level", .data = &sysctl_ip_vs_debug_level, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, #endif { .procname = "am_droprate", .data = &sysctl_ip_vs_am_droprate, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "drop_entry", .data = &sysctl_ip_vs_drop_entry, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_do_defense_mode, }, { .procname = "drop_packet", .data = &sysctl_ip_vs_drop_packet, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_do_defense_mode, }, { .procname = "secure_tcp", .data = &sysctl_ip_vs_secure_tcp, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_do_defense_mode, }, #if 0 { .procname = "timeout_established", .data = &vs_timeout_table_dos.timeout[IP_VS_S_ESTABLISHED], .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "timeout_synsent", .data = &vs_timeout_table_dos.timeout[IP_VS_S_SYN_SENT], .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "timeout_synrecv", .data = &vs_timeout_table_dos.timeout[IP_VS_S_SYN_RECV], .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "timeout_finwait", .data = &vs_timeout_table_dos.timeout[IP_VS_S_FIN_WAIT], .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "timeout_timewait", .data = &vs_timeout_table_dos.timeout[IP_VS_S_TIME_WAIT], .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "timeout_close", .data = &vs_timeout_table_dos.timeout[IP_VS_S_CLOSE], .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "timeout_closewait", .data = &vs_timeout_table_dos.timeout[IP_VS_S_CLOSE_WAIT], .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "timeout_lastack", .data = &vs_timeout_table_dos.timeout[IP_VS_S_LAST_ACK], .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "timeout_listen", .data = &vs_timeout_table_dos.timeout[IP_VS_S_LISTEN], .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "timeout_synack", .data = &vs_timeout_table_dos.timeout[IP_VS_S_SYNACK], .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "timeout_udp", .data = &vs_timeout_table_dos.timeout[IP_VS_S_UDP], .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "timeout_icmp", .data = &vs_timeout_table_dos.timeout[IP_VS_S_ICMP], .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, #endif { .procname = "cache_bypass", .data = &sysctl_ip_vs_cache_bypass, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "expire_nodest_conn", .data = &sysctl_ip_vs_expire_nodest_conn, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "expire_quiescent_template", .data = &sysctl_ip_vs_expire_quiescent_template, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "sync_threshold", .data = &sysctl_ip_vs_sync_threshold, .maxlen = sizeof(sysctl_ip_vs_sync_threshold), .mode = 0644, .proc_handler = proc_do_sync_threshold, }, { .procname = "nat_icmp_send", .data = &sysctl_ip_vs_nat_icmp_send, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { } }; const struct ctl_path net_vs_ctl_path[] = { { .procname = "net", }, { .procname = "ipv4", }, { .procname = "vs", }, { } }; EXPORT_SYMBOL_GPL(net_vs_ctl_path); static struct ctl_table_header * sysctl_header; #ifdef CONFIG_PROC_FS struct ip_vs_iter { struct list_head *table; int bucket; }; /* * Write the contents of the VS rule table to a PROCfs file. * (It is kept just for backward compatibility) */ static inline const char *ip_vs_fwd_name(unsigned flags) { switch (flags & IP_VS_CONN_F_FWD_MASK) { case IP_VS_CONN_F_LOCALNODE: return "Local"; case IP_VS_CONN_F_TUNNEL: return "Tunnel"; case IP_VS_CONN_F_DROUTE: return "Route"; default: return "Masq"; } } /* Get the Nth entry in the two lists */ static struct ip_vs_service *ip_vs_info_array(struct seq_file *seq, loff_t pos) { struct ip_vs_iter *iter = seq->private; int idx; struct ip_vs_service *svc; /* look in hash by protocol */ for (idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) { list_for_each_entry(svc, &ip_vs_svc_table[idx], s_list) { if (pos-- == 0){ iter->table = ip_vs_svc_table; iter->bucket = idx; return svc; } } } /* keep looking in fwmark */ for (idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) { list_for_each_entry(svc, &ip_vs_svc_fwm_table[idx], f_list) { if (pos-- == 0) { iter->table = ip_vs_svc_fwm_table; iter->bucket = idx; return svc; } } } return NULL; } static void *ip_vs_info_seq_start(struct seq_file *seq, loff_t *pos) __acquires(__ip_vs_svc_lock) { read_lock_bh(&__ip_vs_svc_lock); return *pos ? ip_vs_info_array(seq, *pos - 1) : SEQ_START_TOKEN; } static void *ip_vs_info_seq_next(struct seq_file *seq, void *v, loff_t *pos) { struct list_head *e; struct ip_vs_iter *iter; struct ip_vs_service *svc; ++*pos; if (v == SEQ_START_TOKEN) return ip_vs_info_array(seq,0); svc = v; iter = seq->private; if (iter->table == ip_vs_svc_table) { /* next service in table hashed by protocol */ if ((e = svc->s_list.next) != &ip_vs_svc_table[iter->bucket]) return list_entry(e, struct ip_vs_service, s_list); while (++iter->bucket < IP_VS_SVC_TAB_SIZE) { list_for_each_entry(svc,&ip_vs_svc_table[iter->bucket], s_list) { return svc; } } iter->table = ip_vs_svc_fwm_table; iter->bucket = -1; goto scan_fwmark; } /* next service in hashed by fwmark */ if ((e = svc->f_list.next) != &ip_vs_svc_fwm_table[iter->bucket]) return list_entry(e, struct ip_vs_service, f_list); scan_fwmark: while (++iter->bucket < IP_VS_SVC_TAB_SIZE) { list_for_each_entry(svc, &ip_vs_svc_fwm_table[iter->bucket], f_list) return svc; } return NULL; } static void ip_vs_info_seq_stop(struct seq_file *seq, void *v) __releases(__ip_vs_svc_lock) { read_unlock_bh(&__ip_vs_svc_lock); } static int ip_vs_info_seq_show(struct seq_file *seq, void *v) { if (v == SEQ_START_TOKEN) { seq_printf(seq, "IP Virtual Server version %d.%d.%d (size=%d)\n", NVERSION(IP_VS_VERSION_CODE), IP_VS_CONN_TAB_SIZE); seq_puts(seq, "Prot LocalAddress:Port Scheduler Flags\n"); seq_puts(seq, " -> RemoteAddress:Port Forward Weight ActiveConn InActConn\n"); } else { const struct ip_vs_service *svc = v; const struct ip_vs_iter *iter = seq->private; const struct ip_vs_dest *dest; if (iter->table == ip_vs_svc_table) { #ifdef CONFIG_IP_VS_IPV6 if (svc->af == AF_INET6) seq_printf(seq, "%s [%pI6]:%04X %s ", ip_vs_proto_name(svc->protocol), &svc->addr.in6, ntohs(svc->port), svc->scheduler->name); else #endif seq_printf(seq, "%s %08X:%04X %s ", ip_vs_proto_name(svc->protocol), ntohl(svc->addr.ip), ntohs(svc->port), svc->scheduler->name); } else { seq_printf(seq, "FWM %08X %s ", svc->fwmark, svc->scheduler->name); } if (svc->flags & IP_VS_SVC_F_PERSISTENT) seq_printf(seq, "persistent %d %08X\n", svc->timeout, ntohl(svc->netmask)); else seq_putc(seq, '\n'); list_for_each_entry(dest, &svc->destinations, n_list) { #ifdef CONFIG_IP_VS_IPV6 if (dest->af == AF_INET6) seq_printf(seq, " -> [%pI6]:%04X" " %-7s %-6d %-10d %-10d\n", &dest->addr.in6, ntohs(dest->port), ip_vs_fwd_name(atomic_read(&dest->conn_flags)), atomic_read(&dest->weight), atomic_read(&dest->activeconns), atomic_read(&dest->inactconns)); else #endif seq_printf(seq, " -> %08X:%04X " "%-7s %-6d %-10d %-10d\n", ntohl(dest->addr.ip), ntohs(dest->port), ip_vs_fwd_name(atomic_read(&dest->conn_flags)), atomic_read(&dest->weight), atomic_read(&dest->activeconns), atomic_read(&dest->inactconns)); } } return 0; } static const struct seq_operations ip_vs_info_seq_ops = { .start = ip_vs_info_seq_start, .next = ip_vs_info_seq_next, .stop = ip_vs_info_seq_stop, .show = ip_vs_info_seq_show, }; static int ip_vs_info_open(struct inode *inode, struct file *file) { return seq_open_private(file, &ip_vs_info_seq_ops, sizeof(struct ip_vs_iter)); } static const struct file_operations ip_vs_info_fops = { .owner = THIS_MODULE, .open = ip_vs_info_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release_private, }; #endif struct ip_vs_stats ip_vs_stats = { .lock = __SPIN_LOCK_UNLOCKED(ip_vs_stats.lock), }; #ifdef CONFIG_PROC_FS static int ip_vs_stats_show(struct seq_file *seq, void *v) { /* 01234567 01234567 01234567 0123456701234567 0123456701234567 */ seq_puts(seq, " Total Incoming Outgoing Incoming Outgoing\n"); seq_printf(seq, " Conns Packets Packets Bytes Bytes\n"); spin_lock_bh(&ip_vs_stats.lock); seq_printf(seq, "%8X %8X %8X %16LX %16LX\n\n", ip_vs_stats.ustats.conns, ip_vs_stats.ustats.inpkts, ip_vs_stats.ustats.outpkts, (unsigned long long) ip_vs_stats.ustats.inbytes, (unsigned long long) ip_vs_stats.ustats.outbytes); /* 01234567 01234567 01234567 0123456701234567 0123456701234567 */ seq_puts(seq, " Conns/s Pkts/s Pkts/s Bytes/s Bytes/s\n"); seq_printf(seq,"%8X %8X %8X %16X %16X\n", ip_vs_stats.ustats.cps, ip_vs_stats.ustats.inpps, ip_vs_stats.ustats.outpps, ip_vs_stats.ustats.inbps, ip_vs_stats.ustats.outbps); spin_unlock_bh(&ip_vs_stats.lock); return 0; } static int ip_vs_stats_seq_open(struct inode *inode, struct file *file) { return single_open(file, ip_vs_stats_show, NULL); } static const struct file_operations ip_vs_stats_fops = { .owner = THIS_MODULE, .open = ip_vs_stats_seq_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; #endif /* * Set timeout values for tcp tcpfin udp in the timeout_table. */ static int ip_vs_set_timeout(struct ip_vs_timeout_user *u) { IP_VS_DBG(2, "Setting timeout tcp:%d tcpfin:%d udp:%d\n", u->tcp_timeout, u->tcp_fin_timeout, u->udp_timeout); #ifdef CONFIG_IP_VS_PROTO_TCP if (u->tcp_timeout) { ip_vs_protocol_tcp.timeout_table[IP_VS_TCP_S_ESTABLISHED] = u->tcp_timeout * HZ; } if (u->tcp_fin_timeout) { ip_vs_protocol_tcp.timeout_table[IP_VS_TCP_S_FIN_WAIT] = u->tcp_fin_timeout * HZ; } #endif #ifdef CONFIG_IP_VS_PROTO_UDP if (u->udp_timeout) { ip_vs_protocol_udp.timeout_table[IP_VS_UDP_S_NORMAL] = u->udp_timeout * HZ; } #endif return 0; } #define SET_CMDID(cmd) (cmd - IP_VS_BASE_CTL) #define SERVICE_ARG_LEN (sizeof(struct ip_vs_service_user)) #define SVCDEST_ARG_LEN (sizeof(struct ip_vs_service_user) + \ sizeof(struct ip_vs_dest_user)) #define TIMEOUT_ARG_LEN (sizeof(struct ip_vs_timeout_user)) #define DAEMON_ARG_LEN (sizeof(struct ip_vs_daemon_user)) #define MAX_ARG_LEN SVCDEST_ARG_LEN static const unsigned char set_arglen[SET_CMDID(IP_VS_SO_SET_MAX)+1] = { [SET_CMDID(IP_VS_SO_SET_ADD)] = SERVICE_ARG_LEN, [SET_CMDID(IP_VS_SO_SET_EDIT)] = SERVICE_ARG_LEN, [SET_CMDID(IP_VS_SO_SET_DEL)] = SERVICE_ARG_LEN, [SET_CMDID(IP_VS_SO_SET_FLUSH)] = 0, [SET_CMDID(IP_VS_SO_SET_ADDDEST)] = SVCDEST_ARG_LEN, [SET_CMDID(IP_VS_SO_SET_DELDEST)] = SVCDEST_ARG_LEN, [SET_CMDID(IP_VS_SO_SET_EDITDEST)] = SVCDEST_ARG_LEN, [SET_CMDID(IP_VS_SO_SET_TIMEOUT)] = TIMEOUT_ARG_LEN, [SET_CMDID(IP_VS_SO_SET_STARTDAEMON)] = DAEMON_ARG_LEN, [SET_CMDID(IP_VS_SO_SET_STOPDAEMON)] = DAEMON_ARG_LEN, [SET_CMDID(IP_VS_SO_SET_ZERO)] = SERVICE_ARG_LEN, }; static void ip_vs_copy_usvc_compat(struct ip_vs_service_user_kern *usvc, struct ip_vs_service_user *usvc_compat) { usvc->af = AF_INET; usvc->protocol = usvc_compat->protocol; usvc->addr.ip = usvc_compat->addr; usvc->port = usvc_compat->port; usvc->fwmark = usvc_compat->fwmark; /* Deep copy of sched_name is not needed here */ usvc->sched_name = usvc_compat->sched_name; usvc->flags = usvc_compat->flags; usvc->timeout = usvc_compat->timeout; usvc->netmask = usvc_compat->netmask; } static void ip_vs_copy_udest_compat(struct ip_vs_dest_user_kern *udest, struct ip_vs_dest_user *udest_compat) { udest->addr.ip = udest_compat->addr; udest->port = udest_compat->port; udest->conn_flags = udest_compat->conn_flags; udest->weight = udest_compat->weight; udest->u_threshold = udest_compat->u_threshold; udest->l_threshold = udest_compat->l_threshold; } static int do_ip_vs_set_ctl(struct sock *sk, int cmd, void __user *user, unsigned int len) { int ret; unsigned char arg[MAX_ARG_LEN]; struct ip_vs_service_user *usvc_compat; struct ip_vs_service_user_kern usvc; struct ip_vs_service *svc; struct ip_vs_dest_user *udest_compat; struct ip_vs_dest_user_kern udest; if (!capable(CAP_NET_ADMIN)) return -EPERM; if (len != set_arglen[SET_CMDID(cmd)]) { pr_err("set_ctl: len %u != %u\n", len, set_arglen[SET_CMDID(cmd)]); return -EINVAL; } if (copy_from_user(arg, user, len) != 0) return -EFAULT; /* increase the module use count */ ip_vs_use_count_inc(); if (mutex_lock_interruptible(&__ip_vs_mutex)) { ret = -ERESTARTSYS; goto out_dec; } if (cmd == IP_VS_SO_SET_FLUSH) { /* Flush the virtual service */ ret = ip_vs_flush(); goto out_unlock; } else if (cmd == IP_VS_SO_SET_TIMEOUT) { /* Set timeout values for (tcp tcpfin udp) */ ret = ip_vs_set_timeout((struct ip_vs_timeout_user *)arg); goto out_unlock; } else if (cmd == IP_VS_SO_SET_STARTDAEMON) { struct ip_vs_daemon_user *dm = (struct ip_vs_daemon_user *)arg; ret = start_sync_thread(dm->state, dm->mcast_ifn, dm->syncid); goto out_unlock; } else if (cmd == IP_VS_SO_SET_STOPDAEMON) { struct ip_vs_daemon_user *dm = (struct ip_vs_daemon_user *)arg; ret = stop_sync_thread(dm->state); goto out_unlock; } usvc_compat = (struct ip_vs_service_user *)arg; udest_compat = (struct ip_vs_dest_user *)(usvc_compat + 1); /* We only use the new structs internally, so copy userspace compat * structs to extended internal versions */ ip_vs_copy_usvc_compat(&usvc, usvc_compat); ip_vs_copy_udest_compat(&udest, udest_compat); if (cmd == IP_VS_SO_SET_ZERO) { /* if no service address is set, zero counters in all */ if (!usvc.fwmark && !usvc.addr.ip && !usvc.port) { ret = ip_vs_zero_all(); goto out_unlock; } } /* Check for valid protocol: TCP or UDP, even for fwmark!=0 */ if (usvc.protocol != IPPROTO_TCP && usvc.protocol != IPPROTO_UDP) { pr_err("set_ctl: invalid protocol: %d %pI4:%d %s\n", usvc.protocol, &usvc.addr.ip, ntohs(usvc.port), usvc.sched_name); ret = -EFAULT; goto out_unlock; } /* Lookup the exact service by <protocol, addr, port> or fwmark */ if (usvc.fwmark == 0) svc = __ip_vs_service_get(usvc.af, usvc.protocol, &usvc.addr, usvc.port); else svc = __ip_vs_svc_fwm_get(usvc.af, usvc.fwmark); if (cmd != IP_VS_SO_SET_ADD && (svc == NULL || svc->protocol != usvc.protocol)) { ret = -ESRCH; goto out_unlock; } switch (cmd) { case IP_VS_SO_SET_ADD: if (svc != NULL) ret = -EEXIST; else ret = ip_vs_add_service(&usvc, &svc); break; case IP_VS_SO_SET_EDIT: ret = ip_vs_edit_service(svc, &usvc); break; case IP_VS_SO_SET_DEL: ret = ip_vs_del_service(svc); if (!ret) goto out_unlock; break; case IP_VS_SO_SET_ZERO: ret = ip_vs_zero_service(svc); break; case IP_VS_SO_SET_ADDDEST: ret = ip_vs_add_dest(svc, &udest); break; case IP_VS_SO_SET_EDITDEST: ret = ip_vs_edit_dest(svc, &udest); break; case IP_VS_SO_SET_DELDEST: ret = ip_vs_del_dest(svc, &udest); break; default: ret = -EINVAL; } if (svc) ip_vs_service_put(svc); out_unlock: mutex_unlock(&__ip_vs_mutex); out_dec: /* decrease the module use count */ ip_vs_use_count_dec(); return ret; } static void ip_vs_copy_stats(struct ip_vs_stats_user *dst, struct ip_vs_stats *src) { spin_lock_bh(&src->lock); memcpy(dst, &src->ustats, sizeof(*dst)); spin_unlock_bh(&src->lock); } static void ip_vs_copy_service(struct ip_vs_service_entry *dst, struct ip_vs_service *src) { dst->protocol = src->protocol; dst->addr = src->addr.ip; dst->port = src->port; dst->fwmark = src->fwmark; strlcpy(dst->sched_name, src->scheduler->name, sizeof(dst->sched_name)); dst->flags = src->flags; dst->timeout = src->timeout / HZ; dst->netmask = src->netmask; dst->num_dests = src->num_dests; ip_vs_copy_stats(&dst->stats, &src->stats); } static inline int __ip_vs_get_service_entries(const struct ip_vs_get_services *get, struct ip_vs_get_services __user *uptr) { int idx, count=0; struct ip_vs_service *svc; struct ip_vs_service_entry entry; int ret = 0; for (idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) { list_for_each_entry(svc, &ip_vs_svc_table[idx], s_list) { /* Only expose IPv4 entries to old interface */ if (svc->af != AF_INET) continue; if (count >= get->num_services) goto out; memset(&entry, 0, sizeof(entry)); ip_vs_copy_service(&entry, svc); if (copy_to_user(&uptr->entrytable[count], &entry, sizeof(entry))) { ret = -EFAULT; goto out; } count++; } } for (idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) { list_for_each_entry(svc, &ip_vs_svc_fwm_table[idx], f_list) { /* Only expose IPv4 entries to old interface */ if (svc->af != AF_INET) continue; if (count >= get->num_services) goto out; memset(&entry, 0, sizeof(entry)); ip_vs_copy_service(&entry, svc); if (copy_to_user(&uptr->entrytable[count], &entry, sizeof(entry))) { ret = -EFAULT; goto out; } count++; } } out: return ret; } static inline int __ip_vs_get_dest_entries(const struct ip_vs_get_dests *get, struct ip_vs_get_dests __user *uptr) { struct ip_vs_service *svc; union nf_inet_addr addr = { .ip = get->addr }; int ret = 0; if (get->fwmark) svc = __ip_vs_svc_fwm_get(AF_INET, get->fwmark); else svc = __ip_vs_service_get(AF_INET, get->protocol, &addr, get->port); if (svc) { int count = 0; struct ip_vs_dest *dest; struct ip_vs_dest_entry entry; list_for_each_entry(dest, &svc->destinations, n_list) { if (count >= get->num_dests) break; entry.addr = dest->addr.ip; entry.port = dest->port; entry.conn_flags = atomic_read(&dest->conn_flags); entry.weight = atomic_read(&dest->weight); entry.u_threshold = dest->u_threshold; entry.l_threshold = dest->l_threshold; entry.activeconns = atomic_read(&dest->activeconns); entry.inactconns = atomic_read(&dest->inactconns); entry.persistconns = atomic_read(&dest->persistconns); ip_vs_copy_stats(&entry.stats, &dest->stats); if (copy_to_user(&uptr->entrytable[count], &entry, sizeof(entry))) { ret = -EFAULT; break; } count++; } ip_vs_service_put(svc); } else ret = -ESRCH; return ret; } static inline void __ip_vs_get_timeouts(struct ip_vs_timeout_user *u) { #ifdef CONFIG_IP_VS_PROTO_TCP u->tcp_timeout = ip_vs_protocol_tcp.timeout_table[IP_VS_TCP_S_ESTABLISHED] / HZ; u->tcp_fin_timeout = ip_vs_protocol_tcp.timeout_table[IP_VS_TCP_S_FIN_WAIT] / HZ; #endif #ifdef CONFIG_IP_VS_PROTO_UDP u->udp_timeout = ip_vs_protocol_udp.timeout_table[IP_VS_UDP_S_NORMAL] / HZ; #endif } #define GET_CMDID(cmd) (cmd - IP_VS_BASE_CTL) #define GET_INFO_ARG_LEN (sizeof(struct ip_vs_getinfo)) #define GET_SERVICES_ARG_LEN (sizeof(struct ip_vs_get_services)) #define GET_SERVICE_ARG_LEN (sizeof(struct ip_vs_service_entry)) #define GET_DESTS_ARG_LEN (sizeof(struct ip_vs_get_dests)) #define GET_TIMEOUT_ARG_LEN (sizeof(struct ip_vs_timeout_user)) #define GET_DAEMON_ARG_LEN (sizeof(struct ip_vs_daemon_user) * 2) static const unsigned char get_arglen[GET_CMDID(IP_VS_SO_GET_MAX)+1] = { [GET_CMDID(IP_VS_SO_GET_VERSION)] = 64, [GET_CMDID(IP_VS_SO_GET_INFO)] = GET_INFO_ARG_LEN, [GET_CMDID(IP_VS_SO_GET_SERVICES)] = GET_SERVICES_ARG_LEN, [GET_CMDID(IP_VS_SO_GET_SERVICE)] = GET_SERVICE_ARG_LEN, [GET_CMDID(IP_VS_SO_GET_DESTS)] = GET_DESTS_ARG_LEN, [GET_CMDID(IP_VS_SO_GET_TIMEOUT)] = GET_TIMEOUT_ARG_LEN, [GET_CMDID(IP_VS_SO_GET_DAEMON)] = GET_DAEMON_ARG_LEN, }; static int do_ip_vs_get_ctl(struct sock *sk, int cmd, void __user *user, int *len) { unsigned char arg[128]; int ret = 0; if (!capable(CAP_NET_ADMIN)) return -EPERM; if (*len < get_arglen[GET_CMDID(cmd)]) { pr_err("get_ctl: len %u < %u\n", *len, get_arglen[GET_CMDID(cmd)]); return -EINVAL; } if (copy_from_user(arg, user, get_arglen[GET_CMDID(cmd)]) != 0) return -EFAULT; if (mutex_lock_interruptible(&__ip_vs_mutex)) return -ERESTARTSYS; switch (cmd) { case IP_VS_SO_GET_VERSION: { char buf[64]; sprintf(buf, "IP Virtual Server version %d.%d.%d (size=%d)", NVERSION(IP_VS_VERSION_CODE), IP_VS_CONN_TAB_SIZE); if (copy_to_user(user, buf, strlen(buf)+1) != 0) { ret = -EFAULT; goto out; } *len = strlen(buf)+1; } break; case IP_VS_SO_GET_INFO: { struct ip_vs_getinfo info; info.version = IP_VS_VERSION_CODE; info.size = IP_VS_CONN_TAB_SIZE; info.num_services = ip_vs_num_services; if (copy_to_user(user, &info, sizeof(info)) != 0) ret = -EFAULT; } break; case IP_VS_SO_GET_SERVICES: { struct ip_vs_get_services *get; int size; get = (struct ip_vs_get_services *)arg; size = sizeof(*get) + sizeof(struct ip_vs_service_entry) * get->num_services; if (*len != size) { pr_err("length: %u != %u\n", *len, size); ret = -EINVAL; goto out; } ret = __ip_vs_get_service_entries(get, user); } break; case IP_VS_SO_GET_SERVICE: { struct ip_vs_service_entry *entry; struct ip_vs_service *svc; union nf_inet_addr addr; entry = (struct ip_vs_service_entry *)arg; addr.ip = entry->addr; if (entry->fwmark) svc = __ip_vs_svc_fwm_get(AF_INET, entry->fwmark); else svc = __ip_vs_service_get(AF_INET, entry->protocol, &addr, entry->port); if (svc) { ip_vs_copy_service(entry, svc); if (copy_to_user(user, entry, sizeof(*entry)) != 0) ret = -EFAULT; ip_vs_service_put(svc); } else ret = -ESRCH; } break; case IP_VS_SO_GET_DESTS: { struct ip_vs_get_dests *get; int size; get = (struct ip_vs_get_dests *)arg; size = sizeof(*get) + sizeof(struct ip_vs_dest_entry) * get->num_dests; if (*len != size) { pr_err("length: %u != %u\n", *len, size); ret = -EINVAL; goto out; } ret = __ip_vs_get_dest_entries(get, user); } break; case IP_VS_SO_GET_TIMEOUT: { struct ip_vs_timeout_user t; __ip_vs_get_timeouts(&t); if (copy_to_user(user, &t, sizeof(t)) != 0) ret = -EFAULT; } break; case IP_VS_SO_GET_DAEMON: { struct ip_vs_daemon_user d[2]; memset(&d, 0, sizeof(d)); if (ip_vs_sync_state & IP_VS_STATE_MASTER) { d[0].state = IP_VS_STATE_MASTER; strlcpy(d[0].mcast_ifn, ip_vs_master_mcast_ifn, sizeof(d[0].mcast_ifn)); d[0].syncid = ip_vs_master_syncid; } if (ip_vs_sync_state & IP_VS_STATE_BACKUP) { d[1].state = IP_VS_STATE_BACKUP; strlcpy(d[1].mcast_ifn, ip_vs_backup_mcast_ifn, sizeof(d[1].mcast_ifn)); d[1].syncid = ip_vs_backup_syncid; } if (copy_to_user(user, &d, sizeof(d)) != 0) ret = -EFAULT; } break; default: ret = -EINVAL; } out: mutex_unlock(&__ip_vs_mutex); return ret; } static struct nf_sockopt_ops ip_vs_sockopts = { .pf = PF_INET, .set_optmin = IP_VS_BASE_CTL, .set_optmax = IP_VS_SO_SET_MAX+1, .set = do_ip_vs_set_ctl, .get_optmin = IP_VS_BASE_CTL, .get_optmax = IP_VS_SO_GET_MAX+1, .get = do_ip_vs_get_ctl, .owner = THIS_MODULE, }; /* * Generic Netlink interface */ /* IPVS genetlink family */ static struct genl_family ip_vs_genl_family = { .id = GENL_ID_GENERATE, .hdrsize = 0, .name = IPVS_GENL_NAME, .version = IPVS_GENL_VERSION, .maxattr = IPVS_CMD_MAX, }; /* Policy used for first-level command attributes */ static const struct nla_policy ip_vs_cmd_policy[IPVS_CMD_ATTR_MAX + 1] = { [IPVS_CMD_ATTR_SERVICE] = { .type = NLA_NESTED }, [IPVS_CMD_ATTR_DEST] = { .type = NLA_NESTED }, [IPVS_CMD_ATTR_DAEMON] = { .type = NLA_NESTED }, [IPVS_CMD_ATTR_TIMEOUT_TCP] = { .type = NLA_U32 }, [IPVS_CMD_ATTR_TIMEOUT_TCP_FIN] = { .type = NLA_U32 }, [IPVS_CMD_ATTR_TIMEOUT_UDP] = { .type = NLA_U32 }, }; /* Policy used for attributes in nested attribute IPVS_CMD_ATTR_DAEMON */ static const struct nla_policy ip_vs_daemon_policy[IPVS_DAEMON_ATTR_MAX + 1] = { [IPVS_DAEMON_ATTR_STATE] = { .type = NLA_U32 }, [IPVS_DAEMON_ATTR_MCAST_IFN] = { .type = NLA_NUL_STRING, .len = IP_VS_IFNAME_MAXLEN }, [IPVS_DAEMON_ATTR_SYNC_ID] = { .type = NLA_U32 }, }; /* Policy used for attributes in nested attribute IPVS_CMD_ATTR_SERVICE */ static const struct nla_policy ip_vs_svc_policy[IPVS_SVC_ATTR_MAX + 1] = { [IPVS_SVC_ATTR_AF] = { .type = NLA_U16 }, [IPVS_SVC_ATTR_PROTOCOL] = { .type = NLA_U16 }, [IPVS_SVC_ATTR_ADDR] = { .type = NLA_BINARY, .len = sizeof(union nf_inet_addr) }, [IPVS_SVC_ATTR_PORT] = { .type = NLA_U16 }, [IPVS_SVC_ATTR_FWMARK] = { .type = NLA_U32 }, [IPVS_SVC_ATTR_SCHED_NAME] = { .type = NLA_NUL_STRING, .len = IP_VS_SCHEDNAME_MAXLEN }, [IPVS_SVC_ATTR_FLAGS] = { .type = NLA_BINARY, .len = sizeof(struct ip_vs_flags) }, [IPVS_SVC_ATTR_TIMEOUT] = { .type = NLA_U32 }, [IPVS_SVC_ATTR_NETMASK] = { .type = NLA_U32 }, [IPVS_SVC_ATTR_STATS] = { .type = NLA_NESTED }, }; /* Policy used for attributes in nested attribute IPVS_CMD_ATTR_DEST */ static const struct nla_policy ip_vs_dest_policy[IPVS_DEST_ATTR_MAX + 1] = { [IPVS_DEST_ATTR_ADDR] = { .type = NLA_BINARY, .len = sizeof(union nf_inet_addr) }, [IPVS_DEST_ATTR_PORT] = { .type = NLA_U16 }, [IPVS_DEST_ATTR_FWD_METHOD] = { .type = NLA_U32 }, [IPVS_DEST_ATTR_WEIGHT] = { .type = NLA_U32 }, [IPVS_DEST_ATTR_U_THRESH] = { .type = NLA_U32 }, [IPVS_DEST_ATTR_L_THRESH] = { .type = NLA_U32 }, [IPVS_DEST_ATTR_ACTIVE_CONNS] = { .type = NLA_U32 }, [IPVS_DEST_ATTR_INACT_CONNS] = { .type = NLA_U32 }, [IPVS_DEST_ATTR_PERSIST_CONNS] = { .type = NLA_U32 }, [IPVS_DEST_ATTR_STATS] = { .type = NLA_NESTED }, }; static int ip_vs_genl_fill_stats(struct sk_buff *skb, int container_type, struct ip_vs_stats *stats) { struct nlattr *nl_stats = nla_nest_start(skb, container_type); if (!nl_stats) return -EMSGSIZE; spin_lock_bh(&stats->lock); NLA_PUT_U32(skb, IPVS_STATS_ATTR_CONNS, stats->ustats.conns); NLA_PUT_U32(skb, IPVS_STATS_ATTR_INPKTS, stats->ustats.inpkts); NLA_PUT_U32(skb, IPVS_STATS_ATTR_OUTPKTS, stats->ustats.outpkts); NLA_PUT_U64(skb, IPVS_STATS_ATTR_INBYTES, stats->ustats.inbytes); NLA_PUT_U64(skb, IPVS_STATS_ATTR_OUTBYTES, stats->ustats.outbytes); NLA_PUT_U32(skb, IPVS_STATS_ATTR_CPS, stats->ustats.cps); NLA_PUT_U32(skb, IPVS_STATS_ATTR_INPPS, stats->ustats.inpps); NLA_PUT_U32(skb, IPVS_STATS_ATTR_OUTPPS, stats->ustats.outpps); NLA_PUT_U32(skb, IPVS_STATS_ATTR_INBPS, stats->ustats.inbps); NLA_PUT_U32(skb, IPVS_STATS_ATTR_OUTBPS, stats->ustats.outbps); spin_unlock_bh(&stats->lock); nla_nest_end(skb, nl_stats); return 0; nla_put_failure: spin_unlock_bh(&stats->lock); nla_nest_cancel(skb, nl_stats); return -EMSGSIZE; } static int ip_vs_genl_fill_service(struct sk_buff *skb, struct ip_vs_service *svc) { struct nlattr *nl_service; struct ip_vs_flags flags = { .flags = svc->flags, .mask = ~0 }; nl_service = nla_nest_start(skb, IPVS_CMD_ATTR_SERVICE); if (!nl_service) return -EMSGSIZE; NLA_PUT_U16(skb, IPVS_SVC_ATTR_AF, svc->af); if (svc->fwmark) { NLA_PUT_U32(skb, IPVS_SVC_ATTR_FWMARK, svc->fwmark); } else { NLA_PUT_U16(skb, IPVS_SVC_ATTR_PROTOCOL, svc->protocol); NLA_PUT(skb, IPVS_SVC_ATTR_ADDR, sizeof(svc->addr), &svc->addr); NLA_PUT_U16(skb, IPVS_SVC_ATTR_PORT, svc->port); } NLA_PUT_STRING(skb, IPVS_SVC_ATTR_SCHED_NAME, svc->scheduler->name); NLA_PUT(skb, IPVS_SVC_ATTR_FLAGS, sizeof(flags), &flags); NLA_PUT_U32(skb, IPVS_SVC_ATTR_TIMEOUT, svc->timeout / HZ); NLA_PUT_U32(skb, IPVS_SVC_ATTR_NETMASK, svc->netmask); if (ip_vs_genl_fill_stats(skb, IPVS_SVC_ATTR_STATS, &svc->stats)) goto nla_put_failure; nla_nest_end(skb, nl_service); return 0; nla_put_failure: nla_nest_cancel(skb, nl_service); return -EMSGSIZE; } static int ip_vs_genl_dump_service(struct sk_buff *skb, struct ip_vs_service *svc, struct netlink_callback *cb) { void *hdr; hdr = genlmsg_put(skb, NETLINK_CB(cb->skb).pid, cb->nlh->nlmsg_seq, &ip_vs_genl_family, NLM_F_MULTI, IPVS_CMD_NEW_SERVICE); if (!hdr) return -EMSGSIZE; if (ip_vs_genl_fill_service(skb, svc) < 0) goto nla_put_failure; return genlmsg_end(skb, hdr); nla_put_failure: genlmsg_cancel(skb, hdr); return -EMSGSIZE; } static int ip_vs_genl_dump_services(struct sk_buff *skb, struct netlink_callback *cb) { int idx = 0, i; int start = cb->args[0]; struct ip_vs_service *svc; mutex_lock(&__ip_vs_mutex); for (i = 0; i < IP_VS_SVC_TAB_SIZE; i++) { list_for_each_entry(svc, &ip_vs_svc_table[i], s_list) { if (++idx <= start) continue; if (ip_vs_genl_dump_service(skb, svc, cb) < 0) { idx--; goto nla_put_failure; } } } for (i = 0; i < IP_VS_SVC_TAB_SIZE; i++) { list_for_each_entry(svc, &ip_vs_svc_fwm_table[i], f_list) { if (++idx <= start) continue; if (ip_vs_genl_dump_service(skb, svc, cb) < 0) { idx--; goto nla_put_failure; } } } nla_put_failure: mutex_unlock(&__ip_vs_mutex); cb->args[0] = idx; return skb->len; } static int ip_vs_genl_parse_service(struct ip_vs_service_user_kern *usvc, struct nlattr *nla, int full_entry) { struct nlattr *attrs[IPVS_SVC_ATTR_MAX + 1]; struct nlattr *nla_af, *nla_port, *nla_fwmark, *nla_protocol, *nla_addr; /* Parse mandatory identifying service fields first */ if (nla == NULL || nla_parse_nested(attrs, IPVS_SVC_ATTR_MAX, nla, ip_vs_svc_policy)) return -EINVAL; nla_af = attrs[IPVS_SVC_ATTR_AF]; nla_protocol = attrs[IPVS_SVC_ATTR_PROTOCOL]; nla_addr = attrs[IPVS_SVC_ATTR_ADDR]; nla_port = attrs[IPVS_SVC_ATTR_PORT]; nla_fwmark = attrs[IPVS_SVC_ATTR_FWMARK]; if (!(nla_af && (nla_fwmark || (nla_port && nla_protocol && nla_addr)))) return -EINVAL; memset(usvc, 0, sizeof(*usvc)); usvc->af = nla_get_u16(nla_af); #ifdef CONFIG_IP_VS_IPV6 if (usvc->af != AF_INET && usvc->af != AF_INET6) #else if (usvc->af != AF_INET) #endif return -EAFNOSUPPORT; if (nla_fwmark) { usvc->protocol = IPPROTO_TCP; usvc->fwmark = nla_get_u32(nla_fwmark); } else { usvc->protocol = nla_get_u16(nla_protocol); nla_memcpy(&usvc->addr, nla_addr, sizeof(usvc->addr)); usvc->port = nla_get_u16(nla_port); usvc->fwmark = 0; } /* If a full entry was requested, check for the additional fields */ if (full_entry) { struct nlattr *nla_sched, *nla_flags, *nla_timeout, *nla_netmask; struct ip_vs_flags flags; struct ip_vs_service *svc; nla_sched = attrs[IPVS_SVC_ATTR_SCHED_NAME]; nla_flags = attrs[IPVS_SVC_ATTR_FLAGS]; nla_timeout = attrs[IPVS_SVC_ATTR_TIMEOUT]; nla_netmask = attrs[IPVS_SVC_ATTR_NETMASK]; if (!(nla_sched && nla_flags && nla_timeout && nla_netmask)) return -EINVAL; nla_memcpy(&flags, nla_flags, sizeof(flags)); /* prefill flags from service if it already exists */ if (usvc->fwmark) svc = __ip_vs_svc_fwm_get(usvc->af, usvc->fwmark); else svc = __ip_vs_service_get(usvc->af, usvc->protocol, &usvc->addr, usvc->port); if (svc) { usvc->flags = svc->flags; ip_vs_service_put(svc); } else usvc->flags = 0; /* set new flags from userland */ usvc->flags = (usvc->flags & ~flags.mask) | (flags.flags & flags.mask); usvc->sched_name = nla_data(nla_sched); usvc->timeout = nla_get_u32(nla_timeout); usvc->netmask = nla_get_u32(nla_netmask); } return 0; } static struct ip_vs_service *ip_vs_genl_find_service(struct nlattr *nla) { struct ip_vs_service_user_kern usvc; int ret; ret = ip_vs_genl_parse_service(&usvc, nla, 0); if (ret) return ERR_PTR(ret); if (usvc.fwmark) return __ip_vs_svc_fwm_get(usvc.af, usvc.fwmark); else return __ip_vs_service_get(usvc.af, usvc.protocol, &usvc.addr, usvc.port); } static int ip_vs_genl_fill_dest(struct sk_buff *skb, struct ip_vs_dest *dest) { struct nlattr *nl_dest; nl_dest = nla_nest_start(skb, IPVS_CMD_ATTR_DEST); if (!nl_dest) return -EMSGSIZE; NLA_PUT(skb, IPVS_DEST_ATTR_ADDR, sizeof(dest->addr), &dest->addr); NLA_PUT_U16(skb, IPVS_DEST_ATTR_PORT, dest->port); NLA_PUT_U32(skb, IPVS_DEST_ATTR_FWD_METHOD, atomic_read(&dest->conn_flags) & IP_VS_CONN_F_FWD_MASK); NLA_PUT_U32(skb, IPVS_DEST_ATTR_WEIGHT, atomic_read(&dest->weight)); NLA_PUT_U32(skb, IPVS_DEST_ATTR_U_THRESH, dest->u_threshold); NLA_PUT_U32(skb, IPVS_DEST_ATTR_L_THRESH, dest->l_threshold); NLA_PUT_U32(skb, IPVS_DEST_ATTR_ACTIVE_CONNS, atomic_read(&dest->activeconns)); NLA_PUT_U32(skb, IPVS_DEST_ATTR_INACT_CONNS, atomic_read(&dest->inactconns)); NLA_PUT_U32(skb, IPVS_DEST_ATTR_PERSIST_CONNS, atomic_read(&dest->persistconns)); if (ip_vs_genl_fill_stats(skb, IPVS_DEST_ATTR_STATS, &dest->stats)) goto nla_put_failure; nla_nest_end(skb, nl_dest); return 0; nla_put_failure: nla_nest_cancel(skb, nl_dest); return -EMSGSIZE; } static int ip_vs_genl_dump_dest(struct sk_buff *skb, struct ip_vs_dest *dest, struct netlink_callback *cb) { void *hdr; hdr = genlmsg_put(skb, NETLINK_CB(cb->skb).pid, cb->nlh->nlmsg_seq, &ip_vs_genl_family, NLM_F_MULTI, IPVS_CMD_NEW_DEST); if (!hdr) return -EMSGSIZE; if (ip_vs_genl_fill_dest(skb, dest) < 0) goto nla_put_failure; return genlmsg_end(skb, hdr); nla_put_failure: genlmsg_cancel(skb, hdr); return -EMSGSIZE; } static int ip_vs_genl_dump_dests(struct sk_buff *skb, struct netlink_callback *cb) { int idx = 0; int start = cb->args[0]; struct ip_vs_service *svc; struct ip_vs_dest *dest; struct nlattr *attrs[IPVS_CMD_ATTR_MAX + 1]; mutex_lock(&__ip_vs_mutex); /* Try to find the service for which to dump destinations */ if (nlmsg_parse(cb->nlh, GENL_HDRLEN, attrs, IPVS_CMD_ATTR_MAX, ip_vs_cmd_policy)) goto out_err; svc = ip_vs_genl_find_service(attrs[IPVS_CMD_ATTR_SERVICE]); if (IS_ERR(svc) || svc == NULL) goto out_err; /* Dump the destinations */ list_for_each_entry(dest, &svc->destinations, n_list) { if (++idx <= start) continue; if (ip_vs_genl_dump_dest(skb, dest, cb) < 0) { idx--; goto nla_put_failure; } } nla_put_failure: cb->args[0] = idx; ip_vs_service_put(svc); out_err: mutex_unlock(&__ip_vs_mutex); return skb->len; } static int ip_vs_genl_parse_dest(struct ip_vs_dest_user_kern *udest, struct nlattr *nla, int full_entry) { struct nlattr *attrs[IPVS_DEST_ATTR_MAX + 1]; struct nlattr *nla_addr, *nla_port; /* Parse mandatory identifying destination fields first */ if (nla == NULL || nla_parse_nested(attrs, IPVS_DEST_ATTR_MAX, nla, ip_vs_dest_policy)) return -EINVAL; nla_addr = attrs[IPVS_DEST_ATTR_ADDR]; nla_port = attrs[IPVS_DEST_ATTR_PORT]; if (!(nla_addr && nla_port)) return -EINVAL; memset(udest, 0, sizeof(*udest)); nla_memcpy(&udest->addr, nla_addr, sizeof(udest->addr)); udest->port = nla_get_u16(nla_port); /* If a full entry was requested, check for the additional fields */ if (full_entry) { struct nlattr *nla_fwd, *nla_weight, *nla_u_thresh, *nla_l_thresh; nla_fwd = attrs[IPVS_DEST_ATTR_FWD_METHOD]; nla_weight = attrs[IPVS_DEST_ATTR_WEIGHT]; nla_u_thresh = attrs[IPVS_DEST_ATTR_U_THRESH]; nla_l_thresh = attrs[IPVS_DEST_ATTR_L_THRESH]; if (!(nla_fwd && nla_weight && nla_u_thresh && nla_l_thresh)) return -EINVAL; udest->conn_flags = nla_get_u32(nla_fwd) & IP_VS_CONN_F_FWD_MASK; udest->weight = nla_get_u32(nla_weight); udest->u_threshold = nla_get_u32(nla_u_thresh); udest->l_threshold = nla_get_u32(nla_l_thresh); } return 0; } static int ip_vs_genl_fill_daemon(struct sk_buff *skb, __be32 state, const char *mcast_ifn, __be32 syncid) { struct nlattr *nl_daemon; nl_daemon = nla_nest_start(skb, IPVS_CMD_ATTR_DAEMON); if (!nl_daemon) return -EMSGSIZE; NLA_PUT_U32(skb, IPVS_DAEMON_ATTR_STATE, state); NLA_PUT_STRING(skb, IPVS_DAEMON_ATTR_MCAST_IFN, mcast_ifn); NLA_PUT_U32(skb, IPVS_DAEMON_ATTR_SYNC_ID, syncid); nla_nest_end(skb, nl_daemon); return 0; nla_put_failure: nla_nest_cancel(skb, nl_daemon); return -EMSGSIZE; } static int ip_vs_genl_dump_daemon(struct sk_buff *skb, __be32 state, const char *mcast_ifn, __be32 syncid, struct netlink_callback *cb) { void *hdr; hdr = genlmsg_put(skb, NETLINK_CB(cb->skb).pid, cb->nlh->nlmsg_seq, &ip_vs_genl_family, NLM_F_MULTI, IPVS_CMD_NEW_DAEMON); if (!hdr) return -EMSGSIZE; if (ip_vs_genl_fill_daemon(skb, state, mcast_ifn, syncid)) goto nla_put_failure; return genlmsg_end(skb, hdr); nla_put_failure: genlmsg_cancel(skb, hdr); return -EMSGSIZE; } static int ip_vs_genl_dump_daemons(struct sk_buff *skb, struct netlink_callback *cb) { mutex_lock(&__ip_vs_mutex); if ((ip_vs_sync_state & IP_VS_STATE_MASTER) && !cb->args[0]) { if (ip_vs_genl_dump_daemon(skb, IP_VS_STATE_MASTER, ip_vs_master_mcast_ifn, ip_vs_master_syncid, cb) < 0) goto nla_put_failure; cb->args[0] = 1; } if ((ip_vs_sync_state & IP_VS_STATE_BACKUP) && !cb->args[1]) { if (ip_vs_genl_dump_daemon(skb, IP_VS_STATE_BACKUP, ip_vs_backup_mcast_ifn, ip_vs_backup_syncid, cb) < 0) goto nla_put_failure; cb->args[1] = 1; } nla_put_failure: mutex_unlock(&__ip_vs_mutex); return skb->len; } static int ip_vs_genl_new_daemon(struct nlattr **attrs) { if (!(attrs[IPVS_DAEMON_ATTR_STATE] && attrs[IPVS_DAEMON_ATTR_MCAST_IFN] && attrs[IPVS_DAEMON_ATTR_SYNC_ID])) return -EINVAL; return start_sync_thread(nla_get_u32(attrs[IPVS_DAEMON_ATTR_STATE]), nla_data(attrs[IPVS_DAEMON_ATTR_MCAST_IFN]), nla_get_u32(attrs[IPVS_DAEMON_ATTR_SYNC_ID])); } static int ip_vs_genl_del_daemon(struct nlattr **attrs) { if (!attrs[IPVS_DAEMON_ATTR_STATE]) return -EINVAL; return stop_sync_thread(nla_get_u32(attrs[IPVS_DAEMON_ATTR_STATE])); } static int ip_vs_genl_set_config(struct nlattr **attrs) { struct ip_vs_timeout_user t; __ip_vs_get_timeouts(&t); if (attrs[IPVS_CMD_ATTR_TIMEOUT_TCP]) t.tcp_timeout = nla_get_u32(attrs[IPVS_CMD_ATTR_TIMEOUT_TCP]); if (attrs[IPVS_CMD_ATTR_TIMEOUT_TCP_FIN]) t.tcp_fin_timeout = nla_get_u32(attrs[IPVS_CMD_ATTR_TIMEOUT_TCP_FIN]); if (attrs[IPVS_CMD_ATTR_TIMEOUT_UDP]) t.udp_timeout = nla_get_u32(attrs[IPVS_CMD_ATTR_TIMEOUT_UDP]); return ip_vs_set_timeout(&t); } static int ip_vs_genl_set_cmd(struct sk_buff *skb, struct genl_info *info) { struct ip_vs_service *svc = NULL; struct ip_vs_service_user_kern usvc; struct ip_vs_dest_user_kern udest; int ret = 0, cmd; int need_full_svc = 0, need_full_dest = 0; cmd = info->genlhdr->cmd; mutex_lock(&__ip_vs_mutex); if (cmd == IPVS_CMD_FLUSH) { ret = ip_vs_flush(); goto out; } else if (cmd == IPVS_CMD_SET_CONFIG) { ret = ip_vs_genl_set_config(info->attrs); goto out; } else if (cmd == IPVS_CMD_NEW_DAEMON || cmd == IPVS_CMD_DEL_DAEMON) { struct nlattr *daemon_attrs[IPVS_DAEMON_ATTR_MAX + 1]; if (!info->attrs[IPVS_CMD_ATTR_DAEMON] || nla_parse_nested(daemon_attrs, IPVS_DAEMON_ATTR_MAX, info->attrs[IPVS_CMD_ATTR_DAEMON], ip_vs_daemon_policy)) { ret = -EINVAL; goto out; } if (cmd == IPVS_CMD_NEW_DAEMON) ret = ip_vs_genl_new_daemon(daemon_attrs); else ret = ip_vs_genl_del_daemon(daemon_attrs); goto out; } else if (cmd == IPVS_CMD_ZERO && !info->attrs[IPVS_CMD_ATTR_SERVICE]) { ret = ip_vs_zero_all(); goto out; } /* All following commands require a service argument, so check if we * received a valid one. We need a full service specification when * adding / editing a service. Only identifying members otherwise. */ if (cmd == IPVS_CMD_NEW_SERVICE || cmd == IPVS_CMD_SET_SERVICE) need_full_svc = 1; ret = ip_vs_genl_parse_service(&usvc, info->attrs[IPVS_CMD_ATTR_SERVICE], need_full_svc); if (ret) goto out; /* Lookup the exact service by <protocol, addr, port> or fwmark */ if (usvc.fwmark == 0) svc = __ip_vs_service_get(usvc.af, usvc.protocol, &usvc.addr, usvc.port); else svc = __ip_vs_svc_fwm_get(usvc.af, usvc.fwmark); /* Unless we're adding a new service, the service must already exist */ if ((cmd != IPVS_CMD_NEW_SERVICE) && (svc == NULL)) { ret = -ESRCH; goto out; } /* Destination commands require a valid destination argument. For * adding / editing a destination, we need a full destination * specification. */ if (cmd == IPVS_CMD_NEW_DEST || cmd == IPVS_CMD_SET_DEST || cmd == IPVS_CMD_DEL_DEST) { if (cmd != IPVS_CMD_DEL_DEST) need_full_dest = 1; ret = ip_vs_genl_parse_dest(&udest, info->attrs[IPVS_CMD_ATTR_DEST], need_full_dest); if (ret) goto out; } switch (cmd) { case IPVS_CMD_NEW_SERVICE: if (svc == NULL) ret = ip_vs_add_service(&usvc, &svc); else ret = -EEXIST; break; case IPVS_CMD_SET_SERVICE: ret = ip_vs_edit_service(svc, &usvc); break; case IPVS_CMD_DEL_SERVICE: ret = ip_vs_del_service(svc); break; case IPVS_CMD_NEW_DEST: ret = ip_vs_add_dest(svc, &udest); break; case IPVS_CMD_SET_DEST: ret = ip_vs_edit_dest(svc, &udest); break; case IPVS_CMD_DEL_DEST: ret = ip_vs_del_dest(svc, &udest); break; case IPVS_CMD_ZERO: ret = ip_vs_zero_service(svc); break; default: ret = -EINVAL; } out: if (svc) ip_vs_service_put(svc); mutex_unlock(&__ip_vs_mutex); return ret; } static int ip_vs_genl_get_cmd(struct sk_buff *skb, struct genl_info *info) { struct sk_buff *msg; void *reply; int ret, cmd, reply_cmd; cmd = info->genlhdr->cmd; if (cmd == IPVS_CMD_GET_SERVICE) reply_cmd = IPVS_CMD_NEW_SERVICE; else if (cmd == IPVS_CMD_GET_INFO) reply_cmd = IPVS_CMD_SET_INFO; else if (cmd == IPVS_CMD_GET_CONFIG) reply_cmd = IPVS_CMD_SET_CONFIG; else { pr_err("unknown Generic Netlink command\n"); return -EINVAL; } msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL); if (!msg) return -ENOMEM; mutex_lock(&__ip_vs_mutex); reply = genlmsg_put_reply(msg, info, &ip_vs_genl_family, 0, reply_cmd); if (reply == NULL) goto nla_put_failure; switch (cmd) { case IPVS_CMD_GET_SERVICE: { struct ip_vs_service *svc; svc = ip_vs_genl_find_service(info->attrs[IPVS_CMD_ATTR_SERVICE]); if (IS_ERR(svc)) { ret = PTR_ERR(svc); goto out_err; } else if (svc) { ret = ip_vs_genl_fill_service(msg, svc); ip_vs_service_put(svc); if (ret) goto nla_put_failure; } else { ret = -ESRCH; goto out_err; } break; } case IPVS_CMD_GET_CONFIG: { struct ip_vs_timeout_user t; __ip_vs_get_timeouts(&t); #ifdef CONFIG_IP_VS_PROTO_TCP NLA_PUT_U32(msg, IPVS_CMD_ATTR_TIMEOUT_TCP, t.tcp_timeout); NLA_PUT_U32(msg, IPVS_CMD_ATTR_TIMEOUT_TCP_FIN, t.tcp_fin_timeout); #endif #ifdef CONFIG_IP_VS_PROTO_UDP NLA_PUT_U32(msg, IPVS_CMD_ATTR_TIMEOUT_UDP, t.udp_timeout); #endif break; } case IPVS_CMD_GET_INFO: NLA_PUT_U32(msg, IPVS_INFO_ATTR_VERSION, IP_VS_VERSION_CODE); NLA_PUT_U32(msg, IPVS_INFO_ATTR_CONN_TAB_SIZE, IP_VS_CONN_TAB_SIZE); break; } genlmsg_end(msg, reply); ret = genlmsg_reply(msg, info); goto out; nla_put_failure: pr_err("not enough space in Netlink message\n"); ret = -EMSGSIZE; out_err: nlmsg_free(msg); out: mutex_unlock(&__ip_vs_mutex); return ret; } static struct genl_ops ip_vs_genl_ops[] __read_mostly = { { .cmd = IPVS_CMD_NEW_SERVICE, .flags = GENL_ADMIN_PERM, .policy = ip_vs_cmd_policy, .doit = ip_vs_genl_set_cmd, }, { .cmd = IPVS_CMD_SET_SERVICE, .flags = GENL_ADMIN_PERM, .policy = ip_vs_cmd_policy, .doit = ip_vs_genl_set_cmd, }, { .cmd = IPVS_CMD_DEL_SERVICE, .flags = GENL_ADMIN_PERM, .policy = ip_vs_cmd_policy, .doit = ip_vs_genl_set_cmd, }, { .cmd = IPVS_CMD_GET_SERVICE, .flags = GENL_ADMIN_PERM, .doit = ip_vs_genl_get_cmd, .dumpit = ip_vs_genl_dump_services, .policy = ip_vs_cmd_policy, }, { .cmd = IPVS_CMD_NEW_DEST, .flags = GENL_ADMIN_PERM, .policy = ip_vs_cmd_policy, .doit = ip_vs_genl_set_cmd, }, { .cmd = IPVS_CMD_SET_DEST, .flags = GENL_ADMIN_PERM, .policy = ip_vs_cmd_policy, .doit = ip_vs_genl_set_cmd, }, { .cmd = IPVS_CMD_DEL_DEST, .flags = GENL_ADMIN_PERM, .policy = ip_vs_cmd_policy, .doit = ip_vs_genl_set_cmd, }, { .cmd = IPVS_CMD_GET_DEST, .flags = GENL_ADMIN_PERM, .policy = ip_vs_cmd_policy, .dumpit = ip_vs_genl_dump_dests, }, { .cmd = IPVS_CMD_NEW_DAEMON, .flags = GENL_ADMIN_PERM, .policy = ip_vs_cmd_policy, .doit = ip_vs_genl_set_cmd, }, { .cmd = IPVS_CMD_DEL_DAEMON, .flags = GENL_ADMIN_PERM, .policy = ip_vs_cmd_policy, .doit = ip_vs_genl_set_cmd, }, { .cmd = IPVS_CMD_GET_DAEMON, .flags = GENL_ADMIN_PERM, .dumpit = ip_vs_genl_dump_daemons, }, { .cmd = IPVS_CMD_SET_CONFIG, .flags = GENL_ADMIN_PERM, .policy = ip_vs_cmd_policy, .doit = ip_vs_genl_set_cmd, }, { .cmd = IPVS_CMD_GET_CONFIG, .flags = GENL_ADMIN_PERM, .doit = ip_vs_genl_get_cmd, }, { .cmd = IPVS_CMD_GET_INFO, .flags = GENL_ADMIN_PERM, .doit = ip_vs_genl_get_cmd, }, { .cmd = IPVS_CMD_ZERO, .flags = GENL_ADMIN_PERM, .policy = ip_vs_cmd_policy, .doit = ip_vs_genl_set_cmd, }, { .cmd = IPVS_CMD_FLUSH, .flags = GENL_ADMIN_PERM, .doit = ip_vs_genl_set_cmd, }, }; static int __init ip_vs_genl_register(void) { return genl_register_family_with_ops(&ip_vs_genl_family, ip_vs_genl_ops, ARRAY_SIZE(ip_vs_genl_ops)); } static void ip_vs_genl_unregister(void) { genl_unregister_family(&ip_vs_genl_family); } /* End of Generic Netlink interface definitions */ int __init ip_vs_control_init(void) { int ret; int idx; EnterFunction(2); ret = nf_register_sockopt(&ip_vs_sockopts); if (ret) { pr_err("cannot register sockopt.\n"); return ret; } ret = ip_vs_genl_register(); if (ret) { pr_err("cannot register Generic Netlink interface.\n"); nf_unregister_sockopt(&ip_vs_sockopts); return ret; } proc_net_fops_create(&init_net, "ip_vs", 0, &ip_vs_info_fops); proc_net_fops_create(&init_net, "ip_vs_stats",0, &ip_vs_stats_fops); sysctl_header = register_sysctl_paths(net_vs_ctl_path, vs_vars); /* Initialize ip_vs_svc_table, ip_vs_svc_fwm_table, ip_vs_rtable */ for(idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) { INIT_LIST_HEAD(&ip_vs_svc_table[idx]); INIT_LIST_HEAD(&ip_vs_svc_fwm_table[idx]); } for(idx = 0; idx < IP_VS_RTAB_SIZE; idx++) { INIT_LIST_HEAD(&ip_vs_rtable[idx]); } ip_vs_new_estimator(&ip_vs_stats); /* Hook the defense timer */ schedule_delayed_work(&defense_work, DEFENSE_TIMER_PERIOD); LeaveFunction(2); return 0; } void ip_vs_control_cleanup(void) { EnterFunction(2); ip_vs_trash_cleanup(); cancel_rearming_delayed_work(&defense_work); cancel_work_sync(&defense_work.work); ip_vs_kill_estimator(&ip_vs_stats); unregister_sysctl_table(sysctl_header); proc_net_remove(&init_net, "ip_vs_stats"); proc_net_remove(&init_net, "ip_vs"); ip_vs_genl_unregister(); nf_unregister_sockopt(&ip_vs_sockopts); LeaveFunction(2); }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_5766_0
crossvul-cpp_data_good_3317_0
/* * Copyright (c) 1999-2013 Petko Manolov (petkan@nucleusys.com) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * ChangeLog: * .... Most of the time spent on reading sources & docs. * v0.2.x First official release for the Linux kernel. * v0.3.0 Beutified and structured, some bugs fixed. * v0.3.x URBifying bulk requests and bugfixing. First relatively * stable release. Still can touch device's registers only * from top-halves. * v0.4.0 Control messages remained unurbified are now URBs. * Now we can touch the HW at any time. * v0.4.9 Control urbs again use process context to wait. Argh... * Some long standing bugs (enable_net_traffic) fixed. * Also nasty trick about resubmiting control urb from * interrupt context used. Please let me know how it * behaves. Pegasus II support added since this version. * TODO: suppressing HCD warnings spewage on disconnect. * v0.4.13 Ethernet address is now set at probe(), not at open() * time as this seems to break dhcpd. * v0.5.0 branch to 2.5.x kernels * v0.5.1 ethtool support added * v0.5.5 rx socket buffers are in a pool and the their allocation * is out of the interrupt routine. * ... * v0.9.3 simplified [get|set]_register(s), async update registers * logic revisited, receive skb_pool removed. */ #include <linux/sched.h> #include <linux/slab.h> #include <linux/init.h> #include <linux/delay.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/ethtool.h> #include <linux/mii.h> #include <linux/usb.h> #include <linux/module.h> #include <asm/byteorder.h> #include <linux/uaccess.h> #include "pegasus.h" /* * Version Information */ #define DRIVER_VERSION "v0.9.3 (2013/04/25)" #define DRIVER_AUTHOR "Petko Manolov <petkan@nucleusys.com>" #define DRIVER_DESC "Pegasus/Pegasus II USB Ethernet driver" static const char driver_name[] = "pegasus"; #undef PEGASUS_WRITE_EEPROM #define BMSR_MEDIA (BMSR_10HALF | BMSR_10FULL | BMSR_100HALF | \ BMSR_100FULL | BMSR_ANEGCAPABLE) static bool loopback; static bool mii_mode; static char *devid; static struct usb_eth_dev usb_dev_id[] = { #define PEGASUS_DEV(pn, vid, pid, flags) \ {.name = pn, .vendor = vid, .device = pid, .private = flags}, #define PEGASUS_DEV_CLASS(pn, vid, pid, dclass, flags) \ PEGASUS_DEV(pn, vid, pid, flags) #include "pegasus.h" #undef PEGASUS_DEV #undef PEGASUS_DEV_CLASS {NULL, 0, 0, 0}, {NULL, 0, 0, 0} }; static struct usb_device_id pegasus_ids[] = { #define PEGASUS_DEV(pn, vid, pid, flags) \ {.match_flags = USB_DEVICE_ID_MATCH_DEVICE, .idVendor = vid, .idProduct = pid}, /* * The Belkin F8T012xx1 bluetooth adaptor has the same vendor and product * IDs as the Belkin F5D5050, so we need to teach the pegasus driver to * ignore adaptors belonging to the "Wireless" class 0xE0. For this one * case anyway, seeing as the pegasus is for "Wired" adaptors. */ #define PEGASUS_DEV_CLASS(pn, vid, pid, dclass, flags) \ {.match_flags = (USB_DEVICE_ID_MATCH_DEVICE | USB_DEVICE_ID_MATCH_DEV_CLASS), \ .idVendor = vid, .idProduct = pid, .bDeviceClass = dclass}, #include "pegasus.h" #undef PEGASUS_DEV #undef PEGASUS_DEV_CLASS {}, {} }; MODULE_AUTHOR(DRIVER_AUTHOR); MODULE_DESCRIPTION(DRIVER_DESC); MODULE_LICENSE("GPL"); module_param(loopback, bool, 0); module_param(mii_mode, bool, 0); module_param(devid, charp, 0); MODULE_PARM_DESC(loopback, "Enable MAC loopback mode (bit 0)"); MODULE_PARM_DESC(mii_mode, "Enable HomePNA mode (bit 0),default=MII mode = 0"); MODULE_PARM_DESC(devid, "The format is: 'DEV_name:VendorID:DeviceID:Flags'"); /* use ethtool to change the level for any given device */ static int msg_level = -1; module_param(msg_level, int, 0); MODULE_PARM_DESC(msg_level, "Override default message level"); MODULE_DEVICE_TABLE(usb, pegasus_ids); static const struct net_device_ops pegasus_netdev_ops; /*****/ static void async_ctrl_callback(struct urb *urb) { struct usb_ctrlrequest *req = (struct usb_ctrlrequest *)urb->context; int status = urb->status; if (status < 0) dev_dbg(&urb->dev->dev, "%s failed with %d", __func__, status); kfree(req); usb_free_urb(urb); } static int get_registers(pegasus_t *pegasus, __u16 indx, __u16 size, void *data) { u8 *buf; int ret; buf = kmalloc(size, GFP_NOIO); if (!buf) return -ENOMEM; ret = usb_control_msg(pegasus->usb, usb_rcvctrlpipe(pegasus->usb, 0), PEGASUS_REQ_GET_REGS, PEGASUS_REQT_READ, 0, indx, buf, size, 1000); if (ret < 0) netif_dbg(pegasus, drv, pegasus->net, "%s returned %d\n", __func__, ret); else if (ret <= size) memcpy(data, buf, ret); kfree(buf); return ret; } static int set_registers(pegasus_t *pegasus, __u16 indx, __u16 size, const void *data) { u8 *buf; int ret; buf = kmemdup(data, size, GFP_NOIO); if (!buf) return -ENOMEM; ret = usb_control_msg(pegasus->usb, usb_sndctrlpipe(pegasus->usb, 0), PEGASUS_REQ_SET_REGS, PEGASUS_REQT_WRITE, 0, indx, buf, size, 100); if (ret < 0) netif_dbg(pegasus, drv, pegasus->net, "%s returned %d\n", __func__, ret); kfree(buf); return ret; } static int set_register(pegasus_t *pegasus, __u16 indx, __u8 data) { u8 *buf; int ret; buf = kmemdup(&data, 1, GFP_NOIO); if (!buf) return -ENOMEM; ret = usb_control_msg(pegasus->usb, usb_sndctrlpipe(pegasus->usb, 0), PEGASUS_REQ_SET_REG, PEGASUS_REQT_WRITE, data, indx, buf, 1, 1000); if (ret < 0) netif_dbg(pegasus, drv, pegasus->net, "%s returned %d\n", __func__, ret); kfree(buf); return ret; } static int update_eth_regs_async(pegasus_t *pegasus) { int ret = -ENOMEM; struct urb *async_urb; struct usb_ctrlrequest *req; req = kmalloc(sizeof(struct usb_ctrlrequest), GFP_ATOMIC); if (req == NULL) return ret; async_urb = usb_alloc_urb(0, GFP_ATOMIC); if (async_urb == NULL) { kfree(req); return ret; } req->bRequestType = PEGASUS_REQT_WRITE; req->bRequest = PEGASUS_REQ_SET_REGS; req->wValue = cpu_to_le16(0); req->wIndex = cpu_to_le16(EthCtrl0); req->wLength = cpu_to_le16(3); usb_fill_control_urb(async_urb, pegasus->usb, usb_sndctrlpipe(pegasus->usb, 0), (void *)req, pegasus->eth_regs, 3, async_ctrl_callback, req); ret = usb_submit_urb(async_urb, GFP_ATOMIC); if (ret) { if (ret == -ENODEV) netif_device_detach(pegasus->net); netif_err(pegasus, drv, pegasus->net, "%s returned %d\n", __func__, ret); } return ret; } static int __mii_op(pegasus_t *p, __u8 phy, __u8 indx, __u16 *regd, __u8 cmd) { int i; __u8 data[4] = { phy, 0, 0, indx }; __le16 regdi; int ret = -ETIMEDOUT; if (cmd & PHY_WRITE) { __le16 *t = (__le16 *) & data[1]; *t = cpu_to_le16(*regd); } set_register(p, PhyCtrl, 0); set_registers(p, PhyAddr, sizeof(data), data); set_register(p, PhyCtrl, (indx | cmd)); for (i = 0; i < REG_TIMEOUT; i++) { ret = get_registers(p, PhyCtrl, 1, data); if (ret < 0) goto fail; if (data[0] & PHY_DONE) break; } if (i >= REG_TIMEOUT) goto fail; if (cmd & PHY_READ) { ret = get_registers(p, PhyData, 2, &regdi); *regd = le16_to_cpu(regdi); return ret; } return 0; fail: netif_dbg(p, drv, p->net, "%s failed\n", __func__); return ret; } /* Returns non-negative int on success, error on failure */ static int read_mii_word(pegasus_t *pegasus, __u8 phy, __u8 indx, __u16 *regd) { return __mii_op(pegasus, phy, indx, regd, PHY_READ); } /* Returns zero on success, error on failure */ static int write_mii_word(pegasus_t *pegasus, __u8 phy, __u8 indx, __u16 *regd) { return __mii_op(pegasus, phy, indx, regd, PHY_WRITE); } static int mdio_read(struct net_device *dev, int phy_id, int loc) { pegasus_t *pegasus = netdev_priv(dev); u16 res; read_mii_word(pegasus, phy_id, loc, &res); return (int)res; } static void mdio_write(struct net_device *dev, int phy_id, int loc, int val) { pegasus_t *pegasus = netdev_priv(dev); u16 data = val; write_mii_word(pegasus, phy_id, loc, &data); } static int read_eprom_word(pegasus_t *pegasus, __u8 index, __u16 *retdata) { int i; __u8 tmp; __le16 retdatai; int ret; set_register(pegasus, EpromCtrl, 0); set_register(pegasus, EpromOffset, index); set_register(pegasus, EpromCtrl, EPROM_READ); for (i = 0; i < REG_TIMEOUT; i++) { ret = get_registers(pegasus, EpromCtrl, 1, &tmp); if (tmp & EPROM_DONE) break; if (ret == -ESHUTDOWN) goto fail; } if (i >= REG_TIMEOUT) goto fail; ret = get_registers(pegasus, EpromData, 2, &retdatai); *retdata = le16_to_cpu(retdatai); return ret; fail: netif_warn(pegasus, drv, pegasus->net, "%s failed\n", __func__); return -ETIMEDOUT; } #ifdef PEGASUS_WRITE_EEPROM static inline void enable_eprom_write(pegasus_t *pegasus) { __u8 tmp; get_registers(pegasus, EthCtrl2, 1, &tmp); set_register(pegasus, EthCtrl2, tmp | EPROM_WR_ENABLE); } static inline void disable_eprom_write(pegasus_t *pegasus) { __u8 tmp; get_registers(pegasus, EthCtrl2, 1, &tmp); set_register(pegasus, EpromCtrl, 0); set_register(pegasus, EthCtrl2, tmp & ~EPROM_WR_ENABLE); } static int write_eprom_word(pegasus_t *pegasus, __u8 index, __u16 data) { int i; __u8 tmp, d[4] = { 0x3f, 0, 0, EPROM_WRITE }; int ret; __le16 le_data = cpu_to_le16(data); set_registers(pegasus, EpromOffset, 4, d); enable_eprom_write(pegasus); set_register(pegasus, EpromOffset, index); set_registers(pegasus, EpromData, 2, &le_data); set_register(pegasus, EpromCtrl, EPROM_WRITE); for (i = 0; i < REG_TIMEOUT; i++) { ret = get_registers(pegasus, EpromCtrl, 1, &tmp); if (ret == -ESHUTDOWN) goto fail; if (tmp & EPROM_DONE) break; } disable_eprom_write(pegasus); if (i >= REG_TIMEOUT) goto fail; return ret; fail: netif_warn(pegasus, drv, pegasus->net, "%s failed\n", __func__); return -ETIMEDOUT; } #endif /* PEGASUS_WRITE_EEPROM */ static inline void get_node_id(pegasus_t *pegasus, __u8 *id) { int i; __u16 w16; for (i = 0; i < 3; i++) { read_eprom_word(pegasus, i, &w16); ((__le16 *) id)[i] = cpu_to_le16(w16); } } static void set_ethernet_addr(pegasus_t *pegasus) { __u8 node_id[6]; if (pegasus->features & PEGASUS_II) { get_registers(pegasus, 0x10, sizeof(node_id), node_id); } else { get_node_id(pegasus, node_id); set_registers(pegasus, EthID, sizeof(node_id), node_id); } memcpy(pegasus->net->dev_addr, node_id, sizeof(node_id)); } static inline int reset_mac(pegasus_t *pegasus) { __u8 data = 0x8; int i; set_register(pegasus, EthCtrl1, data); for (i = 0; i < REG_TIMEOUT; i++) { get_registers(pegasus, EthCtrl1, 1, &data); if (~data & 0x08) { if (loopback) break; if (mii_mode && (pegasus->features & HAS_HOME_PNA)) set_register(pegasus, Gpio1, 0x34); else set_register(pegasus, Gpio1, 0x26); set_register(pegasus, Gpio0, pegasus->features); set_register(pegasus, Gpio0, DEFAULT_GPIO_SET); break; } } if (i == REG_TIMEOUT) return -ETIMEDOUT; if (usb_dev_id[pegasus->dev_index].vendor == VENDOR_LINKSYS || usb_dev_id[pegasus->dev_index].vendor == VENDOR_DLINK) { set_register(pegasus, Gpio0, 0x24); set_register(pegasus, Gpio0, 0x26); } if (usb_dev_id[pegasus->dev_index].vendor == VENDOR_ELCON) { __u16 auxmode; read_mii_word(pegasus, 3, 0x1b, &auxmode); auxmode |= 4; write_mii_word(pegasus, 3, 0x1b, &auxmode); } return 0; } static int enable_net_traffic(struct net_device *dev, struct usb_device *usb) { __u16 linkpart; __u8 data[4]; pegasus_t *pegasus = netdev_priv(dev); int ret; read_mii_word(pegasus, pegasus->phy, MII_LPA, &linkpart); data[0] = 0xc8; /* TX & RX enable, append status, no CRC */ data[1] = 0; if (linkpart & (ADVERTISE_100FULL | ADVERTISE_10FULL)) data[1] |= 0x20; /* set full duplex */ if (linkpart & (ADVERTISE_100FULL | ADVERTISE_100HALF)) data[1] |= 0x10; /* set 100 Mbps */ if (mii_mode) data[1] = 0; data[2] = loopback ? 0x09 : 0x01; memcpy(pegasus->eth_regs, data, sizeof(data)); ret = set_registers(pegasus, EthCtrl0, 3, data); if (usb_dev_id[pegasus->dev_index].vendor == VENDOR_LINKSYS || usb_dev_id[pegasus->dev_index].vendor == VENDOR_LINKSYS2 || usb_dev_id[pegasus->dev_index].vendor == VENDOR_DLINK) { u16 auxmode; read_mii_word(pegasus, 0, 0x1b, &auxmode); auxmode |= 4; write_mii_word(pegasus, 0, 0x1b, &auxmode); } return ret; } static void read_bulk_callback(struct urb *urb) { pegasus_t *pegasus = urb->context; struct net_device *net; int rx_status, count = urb->actual_length; int status = urb->status; u8 *buf = urb->transfer_buffer; __u16 pkt_len; if (!pegasus) return; net = pegasus->net; if (!netif_device_present(net) || !netif_running(net)) return; switch (status) { case 0: break; case -ETIME: netif_dbg(pegasus, rx_err, net, "reset MAC\n"); pegasus->flags &= ~PEGASUS_RX_BUSY; break; case -EPIPE: /* stall, or disconnect from TT */ /* FIXME schedule work to clear the halt */ netif_warn(pegasus, rx_err, net, "no rx stall recovery\n"); return; case -ENOENT: case -ECONNRESET: case -ESHUTDOWN: netif_dbg(pegasus, ifdown, net, "rx unlink, %d\n", status); return; default: netif_dbg(pegasus, rx_err, net, "RX status %d\n", status); goto goon; } if (count < 4) goto goon; rx_status = buf[count - 2]; if (rx_status & 0x1e) { netif_dbg(pegasus, rx_err, net, "RX packet error %x\n", rx_status); pegasus->stats.rx_errors++; if (rx_status & 0x06) /* long or runt */ pegasus->stats.rx_length_errors++; if (rx_status & 0x08) pegasus->stats.rx_crc_errors++; if (rx_status & 0x10) /* extra bits */ pegasus->stats.rx_frame_errors++; goto goon; } if (pegasus->chip == 0x8513) { pkt_len = le32_to_cpu(*(__le32 *)urb->transfer_buffer); pkt_len &= 0x0fff; pegasus->rx_skb->data += 2; } else { pkt_len = buf[count - 3] << 8; pkt_len += buf[count - 4]; pkt_len &= 0xfff; pkt_len -= 4; } /* * If the packet is unreasonably long, quietly drop it rather than * kernel panicing by calling skb_put. */ if (pkt_len > PEGASUS_MTU) goto goon; /* * at this point we are sure pegasus->rx_skb != NULL * so we go ahead and pass up the packet. */ skb_put(pegasus->rx_skb, pkt_len); pegasus->rx_skb->protocol = eth_type_trans(pegasus->rx_skb, net); netif_rx(pegasus->rx_skb); pegasus->stats.rx_packets++; pegasus->stats.rx_bytes += pkt_len; if (pegasus->flags & PEGASUS_UNPLUG) return; pegasus->rx_skb = __netdev_alloc_skb_ip_align(pegasus->net, PEGASUS_MTU, GFP_ATOMIC); if (pegasus->rx_skb == NULL) goto tl_sched; goon: usb_fill_bulk_urb(pegasus->rx_urb, pegasus->usb, usb_rcvbulkpipe(pegasus->usb, 1), pegasus->rx_skb->data, PEGASUS_MTU, read_bulk_callback, pegasus); rx_status = usb_submit_urb(pegasus->rx_urb, GFP_ATOMIC); if (rx_status == -ENODEV) netif_device_detach(pegasus->net); else if (rx_status) { pegasus->flags |= PEGASUS_RX_URB_FAIL; goto tl_sched; } else { pegasus->flags &= ~PEGASUS_RX_URB_FAIL; } return; tl_sched: tasklet_schedule(&pegasus->rx_tl); } static void rx_fixup(unsigned long data) { pegasus_t *pegasus; int status; pegasus = (pegasus_t *) data; if (pegasus->flags & PEGASUS_UNPLUG) return; if (pegasus->flags & PEGASUS_RX_URB_FAIL) if (pegasus->rx_skb) goto try_again; if (pegasus->rx_skb == NULL) pegasus->rx_skb = __netdev_alloc_skb_ip_align(pegasus->net, PEGASUS_MTU, GFP_ATOMIC); if (pegasus->rx_skb == NULL) { netif_warn(pegasus, rx_err, pegasus->net, "low on memory\n"); tasklet_schedule(&pegasus->rx_tl); return; } usb_fill_bulk_urb(pegasus->rx_urb, pegasus->usb, usb_rcvbulkpipe(pegasus->usb, 1), pegasus->rx_skb->data, PEGASUS_MTU, read_bulk_callback, pegasus); try_again: status = usb_submit_urb(pegasus->rx_urb, GFP_ATOMIC); if (status == -ENODEV) netif_device_detach(pegasus->net); else if (status) { pegasus->flags |= PEGASUS_RX_URB_FAIL; tasklet_schedule(&pegasus->rx_tl); } else { pegasus->flags &= ~PEGASUS_RX_URB_FAIL; } } static void write_bulk_callback(struct urb *urb) { pegasus_t *pegasus = urb->context; struct net_device *net; int status = urb->status; if (!pegasus) return; net = pegasus->net; if (!netif_device_present(net) || !netif_running(net)) return; switch (status) { case -EPIPE: /* FIXME schedule_work() to clear the tx halt */ netif_stop_queue(net); netif_warn(pegasus, tx_err, net, "no tx stall recovery\n"); return; case -ENOENT: case -ECONNRESET: case -ESHUTDOWN: netif_dbg(pegasus, ifdown, net, "tx unlink, %d\n", status); return; default: netif_info(pegasus, tx_err, net, "TX status %d\n", status); /* FALL THROUGH */ case 0: break; } netif_trans_update(net); /* prevent tx timeout */ netif_wake_queue(net); } static void intr_callback(struct urb *urb) { pegasus_t *pegasus = urb->context; struct net_device *net; int res, status = urb->status; if (!pegasus) return; net = pegasus->net; switch (status) { case 0: break; case -ECONNRESET: /* unlink */ case -ENOENT: case -ESHUTDOWN: return; default: /* some Pegasus-I products report LOTS of data * toggle errors... avoid log spamming */ netif_dbg(pegasus, timer, net, "intr status %d\n", status); } if (urb->actual_length >= 6) { u8 *d = urb->transfer_buffer; /* byte 0 == tx_status1, reg 2B */ if (d[0] & (TX_UNDERRUN|EXCESSIVE_COL |LATE_COL|JABBER_TIMEOUT)) { pegasus->stats.tx_errors++; if (d[0] & TX_UNDERRUN) pegasus->stats.tx_fifo_errors++; if (d[0] & (EXCESSIVE_COL | JABBER_TIMEOUT)) pegasus->stats.tx_aborted_errors++; if (d[0] & LATE_COL) pegasus->stats.tx_window_errors++; } /* d[5].LINK_STATUS lies on some adapters. * d[0].NO_CARRIER kicks in only with failed TX. * ... so monitoring with MII may be safest. */ /* bytes 3-4 == rx_lostpkt, reg 2E/2F */ pegasus->stats.rx_missed_errors += ((d[3] & 0x7f) << 8) | d[4]; } res = usb_submit_urb(urb, GFP_ATOMIC); if (res == -ENODEV) netif_device_detach(pegasus->net); if (res) netif_err(pegasus, timer, net, "can't resubmit interrupt urb, %d\n", res); } static void pegasus_tx_timeout(struct net_device *net) { pegasus_t *pegasus = netdev_priv(net); netif_warn(pegasus, timer, net, "tx timeout\n"); usb_unlink_urb(pegasus->tx_urb); pegasus->stats.tx_errors++; } static netdev_tx_t pegasus_start_xmit(struct sk_buff *skb, struct net_device *net) { pegasus_t *pegasus = netdev_priv(net); int count = ((skb->len + 2) & 0x3f) ? skb->len + 2 : skb->len + 3; int res; __u16 l16 = skb->len; netif_stop_queue(net); ((__le16 *) pegasus->tx_buff)[0] = cpu_to_le16(l16); skb_copy_from_linear_data(skb, pegasus->tx_buff + 2, skb->len); usb_fill_bulk_urb(pegasus->tx_urb, pegasus->usb, usb_sndbulkpipe(pegasus->usb, 2), pegasus->tx_buff, count, write_bulk_callback, pegasus); if ((res = usb_submit_urb(pegasus->tx_urb, GFP_ATOMIC))) { netif_warn(pegasus, tx_err, net, "fail tx, %d\n", res); switch (res) { case -EPIPE: /* stall, or disconnect from TT */ /* cleanup should already have been scheduled */ break; case -ENODEV: /* disconnect() upcoming */ case -EPERM: netif_device_detach(pegasus->net); break; default: pegasus->stats.tx_errors++; netif_start_queue(net); } } else { pegasus->stats.tx_packets++; pegasus->stats.tx_bytes += skb->len; } dev_kfree_skb(skb); return NETDEV_TX_OK; } static struct net_device_stats *pegasus_netdev_stats(struct net_device *dev) { return &((pegasus_t *) netdev_priv(dev))->stats; } static inline void disable_net_traffic(pegasus_t *pegasus) { __le16 tmp = cpu_to_le16(0); set_registers(pegasus, EthCtrl0, sizeof(tmp), &tmp); } static inline void get_interrupt_interval(pegasus_t *pegasus) { u16 data; u8 interval; read_eprom_word(pegasus, 4, &data); interval = data >> 8; if (pegasus->usb->speed != USB_SPEED_HIGH) { if (interval < 0x80) { netif_info(pegasus, timer, pegasus->net, "intr interval changed from %ums to %ums\n", interval, 0x80); interval = 0x80; data = (data & 0x00FF) | ((u16)interval << 8); #ifdef PEGASUS_WRITE_EEPROM write_eprom_word(pegasus, 4, data); #endif } } pegasus->intr_interval = interval; } static void set_carrier(struct net_device *net) { pegasus_t *pegasus = netdev_priv(net); u16 tmp; if (read_mii_word(pegasus, pegasus->phy, MII_BMSR, &tmp)) return; if (tmp & BMSR_LSTATUS) netif_carrier_on(net); else netif_carrier_off(net); } static void free_all_urbs(pegasus_t *pegasus) { usb_free_urb(pegasus->intr_urb); usb_free_urb(pegasus->tx_urb); usb_free_urb(pegasus->rx_urb); } static void unlink_all_urbs(pegasus_t *pegasus) { usb_kill_urb(pegasus->intr_urb); usb_kill_urb(pegasus->tx_urb); usb_kill_urb(pegasus->rx_urb); } static int alloc_urbs(pegasus_t *pegasus) { int res = -ENOMEM; pegasus->rx_urb = usb_alloc_urb(0, GFP_KERNEL); if (!pegasus->rx_urb) { return res; } pegasus->tx_urb = usb_alloc_urb(0, GFP_KERNEL); if (!pegasus->tx_urb) { usb_free_urb(pegasus->rx_urb); return res; } pegasus->intr_urb = usb_alloc_urb(0, GFP_KERNEL); if (!pegasus->intr_urb) { usb_free_urb(pegasus->tx_urb); usb_free_urb(pegasus->rx_urb); return res; } return 0; } static int pegasus_open(struct net_device *net) { pegasus_t *pegasus = netdev_priv(net); int res=-ENOMEM; if (pegasus->rx_skb == NULL) pegasus->rx_skb = __netdev_alloc_skb_ip_align(pegasus->net, PEGASUS_MTU, GFP_KERNEL); if (!pegasus->rx_skb) goto exit; res = set_registers(pegasus, EthID, 6, net->dev_addr); usb_fill_bulk_urb(pegasus->rx_urb, pegasus->usb, usb_rcvbulkpipe(pegasus->usb, 1), pegasus->rx_skb->data, PEGASUS_MTU, read_bulk_callback, pegasus); if ((res = usb_submit_urb(pegasus->rx_urb, GFP_KERNEL))) { if (res == -ENODEV) netif_device_detach(pegasus->net); netif_dbg(pegasus, ifup, net, "failed rx_urb, %d\n", res); goto exit; } usb_fill_int_urb(pegasus->intr_urb, pegasus->usb, usb_rcvintpipe(pegasus->usb, 3), pegasus->intr_buff, sizeof(pegasus->intr_buff), intr_callback, pegasus, pegasus->intr_interval); if ((res = usb_submit_urb(pegasus->intr_urb, GFP_KERNEL))) { if (res == -ENODEV) netif_device_detach(pegasus->net); netif_dbg(pegasus, ifup, net, "failed intr_urb, %d\n", res); usb_kill_urb(pegasus->rx_urb); goto exit; } res = enable_net_traffic(net, pegasus->usb); if (res < 0) { netif_dbg(pegasus, ifup, net, "can't enable_net_traffic() - %d\n", res); res = -EIO; usb_kill_urb(pegasus->rx_urb); usb_kill_urb(pegasus->intr_urb); goto exit; } set_carrier(net); netif_start_queue(net); netif_dbg(pegasus, ifup, net, "open\n"); res = 0; exit: return res; } static int pegasus_close(struct net_device *net) { pegasus_t *pegasus = netdev_priv(net); netif_stop_queue(net); if (!(pegasus->flags & PEGASUS_UNPLUG)) disable_net_traffic(pegasus); tasklet_kill(&pegasus->rx_tl); unlink_all_urbs(pegasus); return 0; } static void pegasus_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info) { pegasus_t *pegasus = netdev_priv(dev); strlcpy(info->driver, driver_name, sizeof(info->driver)); strlcpy(info->version, DRIVER_VERSION, sizeof(info->version)); usb_make_path(pegasus->usb, info->bus_info, sizeof(info->bus_info)); } /* also handles three patterns of some kind in hardware */ #define WOL_SUPPORTED (WAKE_MAGIC|WAKE_PHY) static void pegasus_get_wol(struct net_device *dev, struct ethtool_wolinfo *wol) { pegasus_t *pegasus = netdev_priv(dev); wol->supported = WAKE_MAGIC | WAKE_PHY; wol->wolopts = pegasus->wolopts; } static int pegasus_set_wol(struct net_device *dev, struct ethtool_wolinfo *wol) { pegasus_t *pegasus = netdev_priv(dev); u8 reg78 = 0x04; int ret; if (wol->wolopts & ~WOL_SUPPORTED) return -EINVAL; if (wol->wolopts & WAKE_MAGIC) reg78 |= 0x80; if (wol->wolopts & WAKE_PHY) reg78 |= 0x40; /* FIXME this 0x10 bit still needs to get set in the chip... */ if (wol->wolopts) pegasus->eth_regs[0] |= 0x10; else pegasus->eth_regs[0] &= ~0x10; pegasus->wolopts = wol->wolopts; ret = set_register(pegasus, WakeupControl, reg78); if (!ret) ret = device_set_wakeup_enable(&pegasus->usb->dev, wol->wolopts); return ret; } static inline void pegasus_reset_wol(struct net_device *dev) { struct ethtool_wolinfo wol; memset(&wol, 0, sizeof wol); (void) pegasus_set_wol(dev, &wol); } static int pegasus_get_settings(struct net_device *dev, struct ethtool_cmd *ecmd) { pegasus_t *pegasus; pegasus = netdev_priv(dev); mii_ethtool_gset(&pegasus->mii, ecmd); return 0; } static int pegasus_set_settings(struct net_device *dev, struct ethtool_cmd *ecmd) { pegasus_t *pegasus = netdev_priv(dev); return mii_ethtool_sset(&pegasus->mii, ecmd); } static int pegasus_nway_reset(struct net_device *dev) { pegasus_t *pegasus = netdev_priv(dev); return mii_nway_restart(&pegasus->mii); } static u32 pegasus_get_link(struct net_device *dev) { pegasus_t *pegasus = netdev_priv(dev); return mii_link_ok(&pegasus->mii); } static u32 pegasus_get_msglevel(struct net_device *dev) { pegasus_t *pegasus = netdev_priv(dev); return pegasus->msg_enable; } static void pegasus_set_msglevel(struct net_device *dev, u32 v) { pegasus_t *pegasus = netdev_priv(dev); pegasus->msg_enable = v; } static const struct ethtool_ops ops = { .get_drvinfo = pegasus_get_drvinfo, .get_settings = pegasus_get_settings, .set_settings = pegasus_set_settings, .nway_reset = pegasus_nway_reset, .get_link = pegasus_get_link, .get_msglevel = pegasus_get_msglevel, .set_msglevel = pegasus_set_msglevel, .get_wol = pegasus_get_wol, .set_wol = pegasus_set_wol, }; static int pegasus_ioctl(struct net_device *net, struct ifreq *rq, int cmd) { __u16 *data = (__u16 *) &rq->ifr_ifru; pegasus_t *pegasus = netdev_priv(net); int res; switch (cmd) { case SIOCDEVPRIVATE: data[0] = pegasus->phy; case SIOCDEVPRIVATE + 1: read_mii_word(pegasus, data[0], data[1] & 0x1f, &data[3]); res = 0; break; case SIOCDEVPRIVATE + 2: if (!capable(CAP_NET_ADMIN)) return -EPERM; write_mii_word(pegasus, pegasus->phy, data[1] & 0x1f, &data[2]); res = 0; break; default: res = -EOPNOTSUPP; } return res; } static void pegasus_set_multicast(struct net_device *net) { pegasus_t *pegasus = netdev_priv(net); if (net->flags & IFF_PROMISC) { pegasus->eth_regs[EthCtrl2] |= RX_PROMISCUOUS; netif_info(pegasus, link, net, "Promiscuous mode enabled\n"); } else if (!netdev_mc_empty(net) || (net->flags & IFF_ALLMULTI)) { pegasus->eth_regs[EthCtrl0] |= RX_MULTICAST; pegasus->eth_regs[EthCtrl2] &= ~RX_PROMISCUOUS; netif_dbg(pegasus, link, net, "set allmulti\n"); } else { pegasus->eth_regs[EthCtrl0] &= ~RX_MULTICAST; pegasus->eth_regs[EthCtrl2] &= ~RX_PROMISCUOUS; } update_eth_regs_async(pegasus); } static __u8 mii_phy_probe(pegasus_t *pegasus) { int i; __u16 tmp; for (i = 0; i < 32; i++) { read_mii_word(pegasus, i, MII_BMSR, &tmp); if (tmp == 0 || tmp == 0xffff || (tmp & BMSR_MEDIA) == 0) continue; else return i; } return 0xff; } static inline void setup_pegasus_II(pegasus_t *pegasus) { __u8 data = 0xa5; set_register(pegasus, Reg1d, 0); set_register(pegasus, Reg7b, 1); mdelay(100); if ((pegasus->features & HAS_HOME_PNA) && mii_mode) set_register(pegasus, Reg7b, 0); else set_register(pegasus, Reg7b, 2); set_register(pegasus, 0x83, data); get_registers(pegasus, 0x83, 1, &data); if (data == 0xa5) pegasus->chip = 0x8513; else pegasus->chip = 0; set_register(pegasus, 0x80, 0xc0); set_register(pegasus, 0x83, 0xff); set_register(pegasus, 0x84, 0x01); if (pegasus->features & HAS_HOME_PNA && mii_mode) set_register(pegasus, Reg81, 6); else set_register(pegasus, Reg81, 2); } static int pegasus_count; static struct workqueue_struct *pegasus_workqueue; #define CARRIER_CHECK_DELAY (2 * HZ) static void check_carrier(struct work_struct *work) { pegasus_t *pegasus = container_of(work, pegasus_t, carrier_check.work); set_carrier(pegasus->net); if (!(pegasus->flags & PEGASUS_UNPLUG)) { queue_delayed_work(pegasus_workqueue, &pegasus->carrier_check, CARRIER_CHECK_DELAY); } } static int pegasus_blacklisted(struct usb_device *udev) { struct usb_device_descriptor *udd = &udev->descriptor; /* Special quirk to keep the driver from handling the Belkin Bluetooth * dongle which happens to have the same ID. */ if ((udd->idVendor == cpu_to_le16(VENDOR_BELKIN)) && (udd->idProduct == cpu_to_le16(0x0121)) && (udd->bDeviceClass == USB_CLASS_WIRELESS_CONTROLLER) && (udd->bDeviceProtocol == 1)) return 1; return 0; } /* we rely on probe() and remove() being serialized so we * don't need extra locking on pegasus_count. */ static void pegasus_dec_workqueue(void) { pegasus_count--; if (pegasus_count == 0) { destroy_workqueue(pegasus_workqueue); pegasus_workqueue = NULL; } } static int pegasus_probe(struct usb_interface *intf, const struct usb_device_id *id) { struct usb_device *dev = interface_to_usbdev(intf); struct net_device *net; pegasus_t *pegasus; int dev_index = id - pegasus_ids; int res = -ENOMEM; if (pegasus_blacklisted(dev)) return -ENODEV; if (pegasus_count == 0) { pegasus_workqueue = alloc_workqueue("pegasus", WQ_MEM_RECLAIM, 0); if (!pegasus_workqueue) return -ENOMEM; } pegasus_count++; net = alloc_etherdev(sizeof(struct pegasus)); if (!net) goto out; pegasus = netdev_priv(net); pegasus->dev_index = dev_index; res = alloc_urbs(pegasus); if (res < 0) { dev_err(&intf->dev, "can't allocate %s\n", "urbs"); goto out1; } tasklet_init(&pegasus->rx_tl, rx_fixup, (unsigned long) pegasus); INIT_DELAYED_WORK(&pegasus->carrier_check, check_carrier); pegasus->intf = intf; pegasus->usb = dev; pegasus->net = net; net->watchdog_timeo = PEGASUS_TX_TIMEOUT; net->netdev_ops = &pegasus_netdev_ops; net->ethtool_ops = &ops; pegasus->mii.dev = net; pegasus->mii.mdio_read = mdio_read; pegasus->mii.mdio_write = mdio_write; pegasus->mii.phy_id_mask = 0x1f; pegasus->mii.reg_num_mask = 0x1f; pegasus->msg_enable = netif_msg_init(msg_level, NETIF_MSG_DRV | NETIF_MSG_PROBE | NETIF_MSG_LINK); pegasus->features = usb_dev_id[dev_index].private; get_interrupt_interval(pegasus); if (reset_mac(pegasus)) { dev_err(&intf->dev, "can't reset MAC\n"); res = -EIO; goto out2; } set_ethernet_addr(pegasus); if (pegasus->features & PEGASUS_II) { dev_info(&intf->dev, "setup Pegasus II specific registers\n"); setup_pegasus_II(pegasus); } pegasus->phy = mii_phy_probe(pegasus); if (pegasus->phy == 0xff) { dev_warn(&intf->dev, "can't locate MII phy, using default\n"); pegasus->phy = 1; } pegasus->mii.phy_id = pegasus->phy; usb_set_intfdata(intf, pegasus); SET_NETDEV_DEV(net, &intf->dev); pegasus_reset_wol(net); res = register_netdev(net); if (res) goto out3; queue_delayed_work(pegasus_workqueue, &pegasus->carrier_check, CARRIER_CHECK_DELAY); dev_info(&intf->dev, "%s, %s, %pM\n", net->name, usb_dev_id[dev_index].name, net->dev_addr); return 0; out3: usb_set_intfdata(intf, NULL); out2: free_all_urbs(pegasus); out1: free_netdev(net); out: pegasus_dec_workqueue(); return res; } static void pegasus_disconnect(struct usb_interface *intf) { struct pegasus *pegasus = usb_get_intfdata(intf); usb_set_intfdata(intf, NULL); if (!pegasus) { dev_dbg(&intf->dev, "unregistering non-bound device?\n"); return; } pegasus->flags |= PEGASUS_UNPLUG; cancel_delayed_work(&pegasus->carrier_check); unregister_netdev(pegasus->net); unlink_all_urbs(pegasus); free_all_urbs(pegasus); if (pegasus->rx_skb != NULL) { dev_kfree_skb(pegasus->rx_skb); pegasus->rx_skb = NULL; } free_netdev(pegasus->net); pegasus_dec_workqueue(); } static int pegasus_suspend(struct usb_interface *intf, pm_message_t message) { struct pegasus *pegasus = usb_get_intfdata(intf); netif_device_detach(pegasus->net); cancel_delayed_work(&pegasus->carrier_check); if (netif_running(pegasus->net)) { usb_kill_urb(pegasus->rx_urb); usb_kill_urb(pegasus->intr_urb); } return 0; } static int pegasus_resume(struct usb_interface *intf) { struct pegasus *pegasus = usb_get_intfdata(intf); netif_device_attach(pegasus->net); if (netif_running(pegasus->net)) { pegasus->rx_urb->status = 0; pegasus->rx_urb->actual_length = 0; read_bulk_callback(pegasus->rx_urb); pegasus->intr_urb->status = 0; pegasus->intr_urb->actual_length = 0; intr_callback(pegasus->intr_urb); } queue_delayed_work(pegasus_workqueue, &pegasus->carrier_check, CARRIER_CHECK_DELAY); return 0; } static const struct net_device_ops pegasus_netdev_ops = { .ndo_open = pegasus_open, .ndo_stop = pegasus_close, .ndo_do_ioctl = pegasus_ioctl, .ndo_start_xmit = pegasus_start_xmit, .ndo_set_rx_mode = pegasus_set_multicast, .ndo_get_stats = pegasus_netdev_stats, .ndo_tx_timeout = pegasus_tx_timeout, .ndo_set_mac_address = eth_mac_addr, .ndo_validate_addr = eth_validate_addr, }; static struct usb_driver pegasus_driver = { .name = driver_name, .probe = pegasus_probe, .disconnect = pegasus_disconnect, .id_table = pegasus_ids, .suspend = pegasus_suspend, .resume = pegasus_resume, .disable_hub_initiated_lpm = 1, }; static void __init parse_id(char *id) { unsigned int vendor_id = 0, device_id = 0, flags = 0, i = 0; char *token, *name = NULL; if ((token = strsep(&id, ":")) != NULL) name = token; /* name now points to a null terminated string*/ if ((token = strsep(&id, ":")) != NULL) vendor_id = simple_strtoul(token, NULL, 16); if ((token = strsep(&id, ":")) != NULL) device_id = simple_strtoul(token, NULL, 16); flags = simple_strtoul(id, NULL, 16); pr_info("%s: new device %s, vendor ID 0x%04x, device ID 0x%04x, flags: 0x%x\n", driver_name, name, vendor_id, device_id, flags); if (vendor_id > 0x10000 || vendor_id == 0) return; if (device_id > 0x10000 || device_id == 0) return; for (i = 0; usb_dev_id[i].name; i++); usb_dev_id[i].name = name; usb_dev_id[i].vendor = vendor_id; usb_dev_id[i].device = device_id; usb_dev_id[i].private = flags; pegasus_ids[i].match_flags = USB_DEVICE_ID_MATCH_DEVICE; pegasus_ids[i].idVendor = vendor_id; pegasus_ids[i].idProduct = device_id; } static int __init pegasus_init(void) { pr_info("%s: %s, " DRIVER_DESC "\n", driver_name, DRIVER_VERSION); if (devid) parse_id(devid); return usb_register(&pegasus_driver); } static void __exit pegasus_exit(void) { usb_deregister(&pegasus_driver); } module_init(pegasus_init); module_exit(pegasus_exit);
./CrossVul/dataset_final_sorted/CWE-119/c/good_3317_0
crossvul-cpp_data_bad_798_0
/* * GPAC - Multimedia Framework C SDK * * Authors: Jean Le Feuvre * Copyright (c) Telecom ParisTech 2000-2012 * All rights reserved * * This file is part of GPAC / common tools sub-project * * GPAC is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * GPAC is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * */ #include <gpac/tools.h> #include <gpac/network.h> #if defined(_WIN32_WCE) #include <winbase.h> #include <winsock.h> #include <tlhelp32.h> //#include <direct.h> #if !defined(__GNUC__) #pragma comment(lib, "toolhelp") #endif #elif defined(WIN32) #include <time.h> #include <sys/timeb.h> #include <io.h> #include <windows.h> #include <tlhelp32.h> #include <direct.h> #if !defined(__GNUC__) #pragma comment(lib, "winmm") #endif #else #include <time.h> #include <sys/stat.h> #include <sys/time.h> #include <dirent.h> #include <unistd.h> #include <sys/times.h> #include <sys/resource.h> #ifndef __BEOS__ #include <errno.h> #endif #define SLEEP_ABS_SELECT 1 static u32 sys_start_time = 0; static u64 sys_start_time_hr = 0; #endif #ifndef _WIN32_WCE #include <locale.h> #endif #ifndef WIN32 GF_EXPORT u32 gf_sys_clock() { struct timeval now; gettimeofday(&now, NULL); return (u32) ( ( (now.tv_sec)*1000 + (now.tv_usec) / 1000) - sys_start_time ); } GF_EXPORT u64 gf_sys_clock_high_res() { struct timeval now; gettimeofday(&now, NULL); return (now.tv_sec)*1000000 + (now.tv_usec) - sys_start_time_hr; } #endif GF_EXPORT void gf_sleep(u32 ms) { #ifdef WIN32 Sleep(ms); #else s32 sel_err; struct timeval tv; #ifndef SLEEP_ABS_SELECT u32 prev, now, elapsed; #endif #ifdef SLEEP_ABS_SELECT tv.tv_sec = ms/1000; tv.tv_usec = (ms%1000)*1000; #else prev = gf_sys_clock(); #endif do { errno = 0; #ifndef SLEEP_ABS_SELECT now = gf_sys_clock(); elapsed = (now - prev); if ( elapsed >= ms ) { break; } prev = now; ms -= elapsed; tv.tv_sec = ms/1000; tv.tv_usec = (ms%1000)*1000; #endif sel_err = select(0, NULL, NULL, NULL, &tv); } while ( sel_err && (errno == EINTR) ); #endif } #ifndef gettimeofday #ifdef _WIN32_WCE #include <time.h> //#include <wce_time.h> /* * Author of first version (timeval.h): by Wu Yongwei * Author of Windows CE version: Mateusz Loskot (mateusz@loskot.net) * * All code here is considered in the public domain though we do wish our names * could be retained if anyone uses them. */ /* * Constants used internally by time functions. */ #ifndef _TM_DEFINED struct tm { int tm_sec; /* seconds after the minute - [0,59] */ int tm_min; /* minutes after the hour - [0,59] */ int tm_hour; /* hours since midnight - [0,23] */ int tm_mday; /* day of the month - [1,31] */ int tm_mon; /* months since January - [0,11] */ int tm_year; /* years since 1900 */ int tm_wday; /* days since Sunday - [0,6] */ int tm_yday; /* days since January 1 - [0,365] */ int tm_isdst; /* daylight savings time flag */ }; #define _TM_DEFINED #endif /* _TM_DEFINED */ #ifndef _TIMEZONE_DEFINED struct timezone { int tz_minuteswest; /* minutes W of Greenwich */ int tz_dsttime; /* type of dst correction */ }; #define _TIMEZONE_DEFINED #endif /* _TIMEZONE_DEFINED */ #if defined(_MSC_VER) || defined(__BORLANDC__) #define EPOCHFILETIME (116444736000000000i64) #else #define EPOCHFILETIME (116444736000000000LL) #endif int gettimeofday(struct timeval *tp, struct timezone *tzp) { SYSTEMTIME st; FILETIME ft; LARGE_INTEGER li; TIME_ZONE_INFORMATION tzi; __int64 t; static int tzflag; if (NULL != tp) { GetSystemTime(&st); SystemTimeToFileTime(&st, &ft); li.LowPart = ft.dwLowDateTime; li.HighPart = ft.dwHighDateTime; t = li.QuadPart; /* In 100-nanosecond intervals */ t -= EPOCHFILETIME; /* Offset to the Epoch time */ t /= 10; /* In microseconds */ tp->tv_sec = (long)(t / 1000000); tp->tv_usec = (long)(t % 1000000); } if (NULL != tzp) { GetTimeZoneInformation(&tzi); tzp->tz_minuteswest = tzi.Bias; if (tzi.StandardDate.wMonth != 0) { tzp->tz_minuteswest += tzi.StandardBias * 60; } if (tzi.DaylightDate.wMonth != 0) { tzp->tz_dsttime = 1; } else { tzp->tz_dsttime = 0; } } return 0; } #if _GPAC_UNUSED /* time between jan 1, 1601 and jan 1, 1970 in units of 100 nanoseconds FILETIME in Win32 is from jan 1, 1601 */ s32 __gettimeofday(struct timeval *tp, void *tz) { FILETIME ft; SYSTEMTIME st; s32 val; GetSystemTime(&st); SystemTimeToFileTime(&st, &ft); val = (s32) ((*(LONGLONG *) &ft - TIMESPEC_TO_FILETIME_OFFSET) / 10000000); tp->tv_sec = (u32) val; val = (s32 ) ((*(LONGLONG *) &ft - TIMESPEC_TO_FILETIME_OFFSET - ((LONGLONG) val * (LONGLONG) 10000000)) * 100); tp->tv_usec = val; return 0; } #endif #elif defined(WIN32) static s32 gettimeofday(struct timeval *tp, void *tz) { struct _timeb timebuffer; _ftime( &timebuffer ); tp->tv_sec = (long) (timebuffer.time); tp->tv_usec = timebuffer.millitm * 1000; return 0; } #endif #endif #ifdef _WIN32_WCE void CE_Assert(u32 valid, char *file, u32 line) { if (!valid) { char szBuf[2048]; u16 wcBuf[2048]; sprintf(szBuf, "File %s : line %d", file, line); CE_CharToWide(szBuf, wcBuf); MessageBox(NULL, wcBuf, _T("GPAC Assertion Failure"), MB_OK); exit(EXIT_FAILURE); } } void CE_WideToChar(unsigned short *w_str, char *str) { WideCharToMultiByte(CP_ACP, 0, w_str, -1, str, GF_MAX_PATH, NULL, NULL); } void CE_CharToWide(char *str, unsigned short *w_str) { MultiByteToWideChar(CP_ACP, 0, str, -1, w_str, GF_MAX_PATH); } #endif GF_EXPORT void gf_rand_init(Bool Reset) { if (Reset) { srand(1); } else { #if defined(_WIN32_WCE) srand( (u32) GetTickCount() ); #else srand( (u32) time(NULL) ); #endif } } GF_EXPORT u32 gf_rand() { return rand(); } #ifndef _WIN32_WCE #include <sys/stat.h> #endif GF_EXPORT void gf_utc_time_since_1970(u32 *sec, u32 *msec) { #if defined (WIN32) && !defined(_WIN32_WCE) struct _timeb tb; _ftime( &tb ); *sec = (u32) tb.time; *msec = tb.millitm; #else struct timeval tv; gettimeofday(&tv, NULL); *sec = (u32) tv.tv_sec; *msec = tv.tv_usec/1000; #endif } GF_EXPORT void gf_get_user_name(char *buf, u32 buf_size) { strcpy(buf, "mpeg4-user"); #if 0 s32 len; char *t; strcpy(buf, ""); len = 1024; GetUserName(buf, &len); if (!len) { t = getenv("USER"); if (t) strcpy(buf, t); } #endif #if 0 struct passwd *pw; pw = getpwuid(getuid()); strcpy(buf, ""); if (pw && pw->pw_name) strcpy(name, pw->pw_name); #endif } #ifndef WIN32 GF_EXPORT char * my_str_upr(char *str) { u32 i; for (i=0; i<strlen(str); i++) { str[i] = toupper(str[i]); } return str; } GF_EXPORT char * my_str_lwr(char *str) { u32 i; for (i=0; i<strlen(str); i++) { str[i] = tolower(str[i]); } return str; } #endif /*seems OK under mingw also*/ #ifdef WIN32 #ifdef _WIN32_WCE Bool gf_prompt_has_input() { return 0; } char gf_prompt_get_char() { return 0; } GF_EXPORT void gf_prompt_set_echo_off(Bool echo_off) { return; } #else #include <conio.h> #include <windows.h> Bool gf_prompt_has_input() { return kbhit(); } char gf_prompt_get_char() { return getchar(); } GF_EXPORT void gf_prompt_set_echo_off(Bool echo_off) { DWORD flags; HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE); BOOL ret = GetConsoleMode(hStdin, &flags); if (!ret) { DWORD err = GetLastError(); GF_LOG(GF_LOG_ERROR, GF_LOG_CONSOLE, ("[Console] GetConsoleMode() return with the following error code: %d\n", err)); } if (echo_off) flags &= ~ENABLE_ECHO_INPUT; else flags |= ENABLE_ECHO_INPUT; SetConsoleMode(hStdin, flags); } #endif #else /*linux kbhit/getchar- borrowed on debian mailing lists, (author Mike Brownlow)*/ #include <termios.h> static struct termios t_orig, t_new; static s32 ch_peek = -1; static void init_keyboard() { tcgetattr(0, &t_orig); t_new = t_orig; t_new.c_lflag &= ~ICANON; t_new.c_lflag &= ~ECHO; t_new.c_lflag &= ~ISIG; t_new.c_cc[VMIN] = 1; t_new.c_cc[VTIME] = 0; tcsetattr(0, TCSANOW, &t_new); } static void close_keyboard(Bool new_line) { tcsetattr(0,TCSANOW, &t_orig); if (new_line) fprintf(stderr, "\n"); } GF_EXPORT void gf_prompt_set_echo_off(Bool echo_off) { init_keyboard(); if (echo_off) t_orig.c_lflag &= ~ECHO; else t_orig.c_lflag |= ECHO; close_keyboard(0); } GF_EXPORT Bool gf_prompt_has_input() { u8 ch; s32 nread; pid_t fg = tcgetpgrp(STDIN_FILENO); //we are not foreground nor piped (used for IDEs), can't read stdin if ((fg!=-1) && (fg != getpgrp())) { return 0; } init_keyboard(); if (ch_peek != -1) return 1; t_new.c_cc[VMIN]=0; tcsetattr(0, TCSANOW, &t_new); nread = (s32) read(0, &ch, 1); t_new.c_cc[VMIN]=1; tcsetattr(0, TCSANOW, &t_new); if(nread == 1) { ch_peek = ch; return 1; } close_keyboard(0); return 0; } GF_EXPORT char gf_prompt_get_char() { char ch; if (ch_peek != -1) { ch = ch_peek; ch_peek = -1; close_keyboard(1); return ch; } if (0==read(0,&ch,1)) ch = 0; close_keyboard(1); return ch; } #endif static u32 sys_init = 0; static u32 last_update_time = 0; static u64 last_process_k_u_time = 0; GF_SystemRTInfo the_rti; #if defined(_WIN32_WCE) static LARGE_INTEGER frequency , init_counter; static u64 last_total_k_u_time = 0; static u32 mem_usage_at_startup = 0; #ifndef GetCurrentPermissions DWORD GetCurrentPermissions(); #endif #ifndef SetProcPermissions void SetProcPermissions(DWORD ); #endif #elif defined(WIN32) static LARGE_INTEGER frequency , init_counter; static u64 last_proc_idle_time = 0; static u64 last_proc_k_u_time = 0; static HINSTANCE psapi_hinst = NULL; typedef BOOL(WINAPI* NTGetSystemTimes)(VOID *,VOID *,VOID *); NTGetSystemTimes MyGetSystemTimes = NULL; typedef BOOL(WINAPI* NTGetProcessMemoryInfo)(HANDLE,VOID *,DWORD); NTGetProcessMemoryInfo MyGetProcessMemoryInfo = NULL; typedef int(WINAPI* NTQuerySystemInfo)(ULONG,PVOID,ULONG,PULONG); NTQuerySystemInfo MyQuerySystemInfo = NULL; #ifndef PROCESS_MEMORY_COUNTERS typedef struct _PROCESS_MEMORY_COUNTERS { DWORD cb; DWORD PageFaultCount; SIZE_T PeakWorkingSetSize; SIZE_T WorkingSetSize; SIZE_T QuotaPeakPagedPoolUsage; SIZE_T QuotaPagedPoolUsage; SIZE_T QuotaPeakNonPagedPoolUsage; SIZE_T QuotaNonPagedPoolUsage; SIZE_T PagefileUsage; SIZE_T PeakPagefileUsage; } PROCESS_MEMORY_COUNTERS; #endif #ifndef SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION typedef struct _SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION { LARGE_INTEGER IdleTime; LARGE_INTEGER KernelTime; LARGE_INTEGER UserTime; LARGE_INTEGER Reserved1[2]; ULONG Reserved2; } SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION; #endif #else static u64 last_cpu_u_k_time = 0; static u64 last_cpu_idle_time = 0; static u64 mem_at_startup = 0; #endif #ifdef WIN32 static u32 (*OS_GetSysClock)(); u32 gf_sys_clock() { return OS_GetSysClock(); } static u64 (*OS_GetSysClockHR)(); u64 gf_sys_clock_high_res() { return OS_GetSysClockHR(); } #endif #ifdef WIN32 static u32 OS_GetSysClockHIGHRES() { LARGE_INTEGER now; QueryPerformanceCounter(&now); now.QuadPart -= init_counter.QuadPart; return (u32) ((now.QuadPart * 1000) / frequency.QuadPart); } static u64 OS_GetSysClockHIGHRES_FULL() { LARGE_INTEGER now; QueryPerformanceCounter(&now); now.QuadPart -= init_counter.QuadPart; return (u64) ((now.QuadPart * 1000000) / frequency.QuadPart); } static u32 OS_GetSysClockNORMAL() { #ifdef _WIN32_WCE return GetTickCount(); #else return timeGetTime(); #endif } static u64 OS_GetSysClockNORMAL_FULL() { u64 res = OS_GetSysClockNORMAL(); return res*1000; } #endif /* WIN32 */ #if defined(__sh__) /* Avoid exception for denormalized floating point values */ static int sh4_get_fpscr() { int ret; asm volatile ("sts fpscr,%0" : "=r" (ret)); return ret; } static void sh4_put_fpscr(int nv) { asm volatile ("lds %0,fpscr" : : "r" (nv)); } #define SH4_FPSCR_FR 0x00200000 #define SH4_FPSCR_SZ 0x00100000 #define SH4_FPSCR_PR 0x00080000 #define SH4_FPSCR_DN 0x00040000 #define SH4_FPSCR_RN 0x00000003 #define SH4_FPSCR_RN_N 0 #define SH4_FPSCR_RN_Z 1 extern int __fpscr_values[2]; void sh4_change_fpscr(int off, int on) { int b = sh4_get_fpscr(); off = ~off; off |= 0x00180000; on &= ~ 0x00180000; b &= off; b |= on; sh4_put_fpscr(b); __fpscr_values[0] &= off; __fpscr_values[0] |= on; __fpscr_values[1] &= off; __fpscr_values[1] |= on; } #endif #ifdef GPAC_MEMORY_TRACKING void gf_mem_enable_tracker(Bool enable_backtrace); #endif static u64 memory_at_gpac_startup = 0; static u32 gpac_argc = 0; const char **gpac_argv = NULL; GF_EXPORT void gf_sys_set_args(s32 argc, const char **argv) { //for OSX we allow overwrite of argc/argv due to different behavior between console-mode apps and GUI #if !defined(__DARWIN__) && !defined(__APPLE__) if (!gpac_argc && (argc>=0) ) #endif { gpac_argc = (u32) argc; gpac_argv = argv; } } GF_EXPORT u32 gf_sys_get_argc() { return gpac_argc; } GF_EXPORT const char *gf_sys_get_arg(u32 arg) { if (!gpac_argc || !gpac_argv) return NULL; if (arg>=gpac_argc) return NULL; return gpac_argv[arg]; } GF_EXPORT void gf_sys_init(GF_MemTrackerType mem_tracker_type) { if (!sys_init) { #if defined (WIN32) #if defined(_WIN32_WCE) MEMORYSTATUS ms; #else SYSTEM_INFO sysinfo; #endif #endif if (mem_tracker_type!=GF_MemTrackerNone) { #ifdef GPAC_MEMORY_TRACKING gf_mem_enable_tracker( (mem_tracker_type==GF_MemTrackerBackTrace) ? GF_TRUE : GF_FALSE); #endif } #ifndef GPAC_DISABLE_LOG /*by default log subsystem is initialized to error on all tools, and info on console to debug scripts*/ gf_log_set_tool_level(GF_LOG_ALL, GF_LOG_ERROR); gf_log_set_tool_level(GF_LOG_CONSOLE, GF_LOG_INFO); #endif #if defined(__sh__) /* Round all denormalized floatting point number to 0.0 */ sh4_change_fpscr(0,SH4_FPSCR_DN) ; #endif #if defined(WIN32) frequency.QuadPart = 0; /*clock setup*/ if (QueryPerformanceFrequency(&frequency)) { QueryPerformanceCounter(&init_counter); OS_GetSysClock = OS_GetSysClockHIGHRES; OS_GetSysClockHR = OS_GetSysClockHIGHRES_FULL; GF_LOG(GF_LOG_INFO, GF_LOG_CORE, ("[core] using WIN32 performance timer\n")); } else { OS_GetSysClock = OS_GetSysClockNORMAL; OS_GetSysClockHR = OS_GetSysClockNORMAL_FULL; GF_LOG(GF_LOG_INFO, GF_LOG_CORE, ("[core] using WIN32 regular timer\n")); } #ifndef _WIN32_WCE timeBeginPeriod(1); #endif GF_LOG(GF_LOG_INFO, GF_LOG_CORE, ("[core] checking for run-time info tools")); #if defined(_WIN32_WCE) last_total_k_u_time = last_process_k_u_time = 0; last_update_time = 0; memset(&the_rti, 0, sizeof(GF_SystemRTInfo)); the_rti.pid = GetCurrentProcessId(); the_rti.nb_cores = 1; GlobalMemoryStatus(&ms); mem_usage_at_startup = ms.dwAvailPhys; #else /*cpu usage tools are buried in win32 dlls...*/ MyGetSystemTimes = (NTGetSystemTimes) GetProcAddress(GetModuleHandle("kernel32.dll"), "GetSystemTimes"); if (!MyGetSystemTimes) { MyQuerySystemInfo = (NTQuerySystemInfo) GetProcAddress(GetModuleHandle("ntdll.dll"), "NtQuerySystemInformation"); if (MyQuerySystemInfo) { GF_LOG(GF_LOG_INFO, GF_LOG_CORE, (" - CPU: QuerySystemInformation")); } } else { GF_LOG(GF_LOG_INFO, GF_LOG_CORE, (" - CPU: GetSystemsTimes")); } psapi_hinst = LoadLibrary("psapi.dll"); MyGetProcessMemoryInfo = (NTGetProcessMemoryInfo) GetProcAddress(psapi_hinst, "GetProcessMemoryInfo"); if (MyGetProcessMemoryInfo) { GF_LOG(GF_LOG_INFO, GF_LOG_CORE, (" - memory: GetProcessMemoryInfo")); } last_process_k_u_time = last_proc_idle_time = last_proc_k_u_time = 0; last_update_time = 0; memset(&the_rti, 0, sizeof(GF_SystemRTInfo)); the_rti.pid = GetCurrentProcessId(); GetSystemInfo( &sysinfo ); the_rti.nb_cores = sysinfo.dwNumberOfProcessors; #endif GF_LOG(GF_LOG_INFO, GF_LOG_CORE, ("\n")); #else /*linux threads and OSX...*/ last_process_k_u_time = 0; last_cpu_u_k_time = last_cpu_idle_time = 0; last_update_time = 0; memset(&the_rti, 0, sizeof(GF_SystemRTInfo)); the_rti.pid = getpid(); the_rti.nb_cores = (u32) sysconf( _SC_NPROCESSORS_ONLN ); sys_start_time = gf_sys_clock(); sys_start_time_hr = gf_sys_clock_high_res(); #endif GF_LOG(GF_LOG_INFO, GF_LOG_CORE, ("[core] process id %d\n", the_rti.pid)); #ifndef _WIN32_WCE setlocale( LC_NUMERIC, "C" ); #endif } sys_init += 1; /*init RTI stats*/ if (!memory_at_gpac_startup) { GF_SystemRTInfo rti; if (gf_sys_get_rti(500, &rti, GF_RTI_SYSTEM_MEMORY_ONLY)) { memory_at_gpac_startup = rti.physical_memory_avail; GF_LOG(GF_LOG_INFO, GF_LOG_CORE, ("[core] System init OK - process id %d - %d MB physical RAM - %d cores\n", rti.pid, (u32) (rti.physical_memory/1024/1024), rti.nb_cores)); } else { memory_at_gpac_startup = 0; } } } GF_EXPORT void gf_sys_close() { if (sys_init > 0) { sys_init --; if (sys_init) return; /*prevent any call*/ last_update_time = 0xFFFFFFFF; #if defined(WIN32) && !defined(_WIN32_WCE) timeEndPeriod(1); MyGetSystemTimes = NULL; MyGetProcessMemoryInfo = NULL; MyQuerySystemInfo = NULL; if (psapi_hinst) FreeLibrary(psapi_hinst); psapi_hinst = NULL; #endif } } #ifdef GPAC_MEMORY_TRACKING extern size_t gpac_allocated_memory; extern size_t gpac_nb_alloc_blocs; #endif /*CPU and Memory Usage*/ #ifdef WIN32 Bool gf_sys_get_rti_os(u32 refresh_time_ms, GF_SystemRTInfo *rti, u32 flags) { #if defined(_WIN32_WCE) THREADENTRY32 tentry; u64 total_cpu_time, process_cpu_time; DWORD orig_perm; #endif MEMORYSTATUS ms; u64 creation, exit, kernel, user, process_k_u_time, proc_idle_time, proc_k_u_time; u32 entry_time; HANDLE hSnapShot; assert(sys_init); if (!rti) return GF_FALSE; proc_idle_time = proc_k_u_time = process_k_u_time = 0; entry_time = gf_sys_clock(); if (last_update_time && (entry_time - last_update_time < refresh_time_ms)) { memcpy(rti, &the_rti, sizeof(GF_SystemRTInfo)); return GF_FALSE; } if (flags & GF_RTI_SYSTEM_MEMORY_ONLY) { memset(rti, 0, sizeof(GF_SystemRTInfo)); rti->sampling_instant = last_update_time; GlobalMemoryStatus(&ms); rti->physical_memory = ms.dwTotalPhys; rti->physical_memory_avail = ms.dwAvailPhys; #ifdef GPAC_MEMORY_TRACKING rti->gpac_memory = (u64) gpac_allocated_memory; #endif return GF_TRUE; } #if defined (_WIN32_WCE) total_cpu_time = process_cpu_time = 0; /*get a snapshot of all running threads*/ orig_perm = GetCurrentPermissions(); SetProcPermissions(0xFFFFFFFF); hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); if (hSnapShot) { tentry.dwSize = sizeof(THREADENTRY32); the_rti.thread_count = 0; /*note we always act as if GF_RTI_ALL_PROCESSES_TIMES flag is set, since there is no other way to enumerate threads from a process, and GetProcessTimes doesn't exist on CE*/ if (Thread32First(hSnapShot, &tentry)) { do { /*get thread times*/ if (GetThreadTimes( (HANDLE) tentry.th32ThreadID, (FILETIME *) &creation, (FILETIME *) &exit, (FILETIME *) &kernel, (FILETIME *) &user)) { total_cpu_time += user + kernel; if (tentry.th32OwnerProcessID==the_rti.pid) { process_cpu_time += user + kernel; the_rti.thread_count ++; } } } while (Thread32Next(hSnapShot, &tentry)); } CloseToolhelp32Snapshot(hSnapShot); } if (flags & GF_RTI_PROCESS_MEMORY) { HEAPLIST32 hlentry; HEAPENTRY32 hentry; the_rti.process_memory = 0; hlentry.dwSize = sizeof(HEAPLIST32); hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPHEAPLIST, the_rti.pid); if (hSnapShot && Heap32ListFirst(hSnapShot, &hlentry)) { do { hentry.dwSize = sizeof(hentry); if (Heap32First(hSnapShot, &hentry, hlentry.th32ProcessID, hlentry.th32HeapID)) { do { the_rti.process_memory += hentry.dwBlockSize; } while (Heap32Next(hSnapShot, &hentry)); } } while (Heap32ListNext(hSnapShot, &hlentry)); } CloseToolhelp32Snapshot(hSnapShot); } SetProcPermissions(orig_perm); total_cpu_time /= 10; process_cpu_time /= 10; #else /*XP-SP1 and Win2003 servers only have GetSystemTimes support. This will give a better estimation of CPU usage since we can take into account the idle time*/ if (MyGetSystemTimes) { u64 u_time; MyGetSystemTimes(&proc_idle_time, &proc_k_u_time, &u_time); proc_k_u_time += u_time; proc_idle_time /= 10; proc_k_u_time /= 10; } /*same rq for NtQuerySystemInformation*/ else if (MyQuerySystemInfo) { DWORD ret; SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION info; MyQuerySystemInfo(0x8 /*SystemProcessorPerformanceInformation*/, &info, sizeof(info), &ret); if (ret && (ret<=sizeof(info))) { proc_idle_time = info.IdleTime.QuadPart / 10; proc_k_u_time = (info.KernelTime.QuadPart + info.UserTime.QuadPart) / 10; } } /*no special API available, ONLY FETCH TIMES if requested (may eat up some time)*/ else if (flags & GF_RTI_ALL_PROCESSES_TIMES) { PROCESSENTRY32 pentry; /*get a snapshot of all running threads*/ hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (!hSnapShot) return GF_FALSE; pentry.dwSize = sizeof(PROCESSENTRY32); if (Process32First(hSnapShot, &pentry)) { do { HANDLE procH = NULL; if (pentry.th32ProcessID) procH = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pentry.th32ProcessID); if (procH && GetProcessTimes(procH, (FILETIME *) &creation, (FILETIME *) &exit, (FILETIME *) &kernel, (FILETIME *) &user) ) { user += kernel; proc_k_u_time += user; if (pentry.th32ProcessID==the_rti.pid) { process_k_u_time = user; //nb_threads = pentry.cntThreads; } } if (procH) CloseHandle(procH); } while (Process32Next(hSnapShot, &pentry)); } CloseHandle(hSnapShot); proc_k_u_time /= 10; } if (!process_k_u_time) { HANDLE procH = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, the_rti.pid); if (procH && GetProcessTimes(procH, (FILETIME *) &creation, (FILETIME *) &exit, (FILETIME *) &kernel, (FILETIME *) &user) ) { process_k_u_time = user + kernel; } if (procH) CloseHandle(procH); if (!process_k_u_time) return GF_FALSE; } process_k_u_time /= 10; /*this won't cost a lot*/ if (MyGetProcessMemoryInfo) { PROCESS_MEMORY_COUNTERS pmc; HANDLE procH = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, the_rti.pid); MyGetProcessMemoryInfo(procH, &pmc, sizeof (pmc)); the_rti.process_memory = pmc.WorkingSetSize; if (procH) CloseHandle(procH); } /*THIS IS VERY HEAVY (eats up mem and time) - only perform if requested*/ else if (flags & GF_RTI_PROCESS_MEMORY) { HEAPLIST32 hlentry; HEAPENTRY32 hentry; the_rti.process_memory = 0; hlentry.dwSize = sizeof(HEAPLIST32); hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPHEAPLIST, the_rti.pid); if (hSnapShot && Heap32ListFirst(hSnapShot, &hlentry)) { do { hentry.dwSize = sizeof(hentry); if (Heap32First(&hentry, hlentry.th32ProcessID, hlentry.th32HeapID)) { do { the_rti.process_memory += hentry.dwBlockSize; } while (Heap32Next(&hentry)); } } while (Heap32ListNext(hSnapShot, &hlentry)); } CloseHandle(hSnapShot); } #endif the_rti.sampling_instant = last_update_time; if (last_update_time) { the_rti.sampling_period_duration = entry_time - last_update_time; the_rti.process_cpu_time_diff = (u32) ((process_k_u_time - last_process_k_u_time)/1000); #if defined(_WIN32_WCE) the_rti.total_cpu_time_diff = (u32) ((total_cpu_time - last_total_k_u_time)/1000); /*we're not that accurate....*/ if (the_rti.total_cpu_time_diff > the_rti.sampling_period_duration) the_rti.sampling_period_duration = the_rti.total_cpu_time_diff; /*rough values*/ the_rti.cpu_idle_time = the_rti.sampling_period_duration - the_rti.total_cpu_time_diff; if (!the_rti.sampling_period_duration) the_rti.sampling_period_duration=1; the_rti.total_cpu_usage = (u32) (100 * the_rti.total_cpu_time_diff / the_rti.sampling_period_duration); if (the_rti.total_cpu_time_diff + the_rti.cpu_idle_time==0) the_rti.total_cpu_time_diff ++; the_rti.process_cpu_usage = (u32) (100*the_rti.process_cpu_time_diff / (the_rti.total_cpu_time_diff + the_rti.cpu_idle_time) ); #else /*oops, we have no choice but to assume 100% cpu usage during this period*/ if (!proc_k_u_time) { the_rti.total_cpu_time_diff = the_rti.sampling_period_duration; proc_k_u_time = last_proc_k_u_time + the_rti.sampling_period_duration; the_rti.cpu_idle_time = 0; the_rti.total_cpu_usage = 100; if (the_rti.sampling_period_duration) the_rti.process_cpu_usage = (u32) (100*the_rti.process_cpu_time_diff / the_rti.sampling_period_duration); } else { u64 samp_sys_time, idle; the_rti.total_cpu_time_diff = (u32) ((proc_k_u_time - last_proc_k_u_time)/1000); /*we're not that accurate....*/ if (the_rti.total_cpu_time_diff > the_rti.sampling_period_duration) { the_rti.sampling_period_duration = the_rti.total_cpu_time_diff; } if (!proc_idle_time) proc_idle_time = last_proc_idle_time + (the_rti.sampling_period_duration - the_rti.total_cpu_time_diff); samp_sys_time = proc_k_u_time - last_proc_k_u_time; idle = proc_idle_time - last_proc_idle_time; the_rti.cpu_idle_time = (u32) (idle/1000); if (samp_sys_time) { the_rti.total_cpu_usage = (u32) ( (samp_sys_time - idle) / (samp_sys_time / 100) ); the_rti.process_cpu_usage = (u32) (100*the_rti.process_cpu_time_diff / (samp_sys_time/1000)); } } #endif } last_update_time = entry_time; last_process_k_u_time = process_k_u_time; GlobalMemoryStatus(&ms); the_rti.physical_memory = ms.dwTotalPhys; #ifdef GPAC_MEMORY_TRACKING the_rti.gpac_memory = (u64) gpac_allocated_memory; #endif the_rti.physical_memory_avail = ms.dwAvailPhys; #if defined(_WIN32_WCE) last_total_k_u_time = total_cpu_time; if (!the_rti.process_memory) the_rti.process_memory = mem_usage_at_startup - ms.dwAvailPhys; #else last_proc_idle_time = proc_idle_time; last_proc_k_u_time = proc_k_u_time; #endif if (!the_rti.gpac_memory) the_rti.gpac_memory = the_rti.process_memory; memcpy(rti, &the_rti, sizeof(GF_SystemRTInfo)); return GF_TRUE; } #elif defined(GPAC_CONFIG_DARWIN) && !defined(GPAC_IPHONE) #include <sys/types.h> #include <sys/sysctl.h> #include <sys/vmmeter.h> #include <mach/mach_init.h> #include <mach/mach_host.h> #include <mach/mach_port.h> #include <mach/mach_traps.h> #include <mach/task_info.h> #include <mach/thread_info.h> #include <mach/thread_act.h> #include <mach/vm_region.h> #include <mach/vm_map.h> #include <mach/task.h> #if __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ >= 1060 #include <mach/shared_region.h> #else #include <mach/shared_memory_server.h> #endif #include <mach/mach_error.h> static u64 total_physical_memory = 0; Bool gf_sys_get_rti_os(u32 refresh_time_ms, GF_SystemRTInfo *rti, u32 flags) { size_t length; u32 entry_time, i, percent; int mib[6]; u64 result; int pagesize; u64 process_u_k_time; double utime, stime; vm_statistics_data_t vmstat; task_t task; kern_return_t error; thread_array_t thread_table; unsigned table_size; thread_basic_info_t thi; thread_basic_info_data_t thi_data; struct task_basic_info ti; mach_msg_type_number_t count = HOST_VM_INFO_COUNT, size = sizeof(ti); entry_time = gf_sys_clock(); if (last_update_time && (entry_time - last_update_time < refresh_time_ms)) { memcpy(rti, &the_rti, sizeof(GF_SystemRTInfo)); return 0; } mib[0] = CTL_HW; mib[1] = HW_PAGESIZE; length = sizeof(pagesize); if (sysctl(mib, 2, &pagesize, &length, NULL, 0) < 0) { return 0; } if (host_statistics(mach_host_self(), HOST_VM_INFO, (host_info_t)&vmstat, &count) != KERN_SUCCESS) { return 0; } the_rti.physical_memory = (vmstat.wire_count + vmstat.active_count + vmstat.inactive_count + vmstat.free_count)* pagesize; the_rti.physical_memory_avail = vmstat.free_count * pagesize; if (!total_physical_memory) { mib[0] = CTL_HW; mib[1] = HW_MEMSIZE; length = sizeof(u64); if (sysctl(mib, 2, &result, &length, NULL, 0) >= 0) { total_physical_memory = result; } } the_rti.physical_memory = total_physical_memory; error = task_for_pid(mach_task_self(), the_rti.pid, &task); if (error) { GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[RTI] Cannot get process task for PID %d: error %d\n", the_rti.pid, error)); return 0; } error = task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)&ti, &size); if (error) { GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[RTI] Cannot get process task info (PID %d): error %d\n", the_rti.pid, error)); return 0; } percent = 0; utime = ti.user_time.seconds + ti.user_time.microseconds * 1e-6; stime = ti.system_time.seconds + ti.system_time.microseconds * 1e-6; error = task_threads(task, &thread_table, &table_size); if (error != KERN_SUCCESS) { GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[RTI] Cannot get threads task for PID %d: error %d\n", the_rti.pid, error)); return 0; } thi = &thi_data; for (i = 0; i != table_size; ++i) { count = THREAD_BASIC_INFO_COUNT; error = thread_info(thread_table[i], THREAD_BASIC_INFO, (thread_info_t)thi, &count); if (error != KERN_SUCCESS) { mach_error("[RTI] Unexpected thread_info() call return", error); GF_LOG(GF_LOG_WARNING, GF_LOG_CORE, ("[RTI] Unexpected thread info for PID %d\n", the_rti.pid)); break; } if ((thi->flags & TH_FLAGS_IDLE) == 0) { utime += thi->user_time.seconds + thi->user_time.microseconds * 1e-6; stime += thi->system_time.seconds + thi->system_time.microseconds * 1e-6; percent += (u32) (100 * (double)thi->cpu_usage / TH_USAGE_SCALE); } } vm_deallocate(mach_task_self(), (vm_offset_t)thread_table, table_size * sizeof(thread_array_t)); mach_port_deallocate(mach_task_self(), task); process_u_k_time = utime + stime; the_rti.sampling_instant = last_update_time; if (last_update_time) { the_rti.sampling_period_duration = (entry_time - last_update_time); the_rti.process_cpu_time_diff = (process_u_k_time - last_process_k_u_time) * 10; the_rti.total_cpu_time_diff = the_rti.sampling_period_duration; /*TODO*/ the_rti.cpu_idle_time = 0; the_rti.total_cpu_usage = 0; if (!the_rti.process_cpu_time_diff) the_rti.process_cpu_time_diff = the_rti.total_cpu_time_diff; the_rti.process_cpu_usage = percent; } else { mem_at_startup = the_rti.physical_memory_avail; } the_rti.process_memory = mem_at_startup - the_rti.physical_memory_avail; #ifdef GPAC_MEMORY_TRACKING the_rti.gpac_memory = gpac_allocated_memory; #endif last_process_k_u_time = process_u_k_time; last_cpu_idle_time = 0; last_update_time = entry_time; memcpy(rti, &the_rti, sizeof(GF_SystemRTInfo)); return 1; } //linux #else Bool gf_sys_get_rti_os(u32 refresh_time_ms, GF_SystemRTInfo *rti, u32 flags) { u32 entry_time; u64 process_u_k_time; u32 u_k_time, idle_time; #if 0 char szProc[100]; #endif char line[2048]; FILE *f; assert(sys_init); entry_time = gf_sys_clock(); if (last_update_time && (entry_time - last_update_time < refresh_time_ms)) { memcpy(rti, &the_rti, sizeof(GF_SystemRTInfo)); return 0; } u_k_time = idle_time = 0; f = gf_fopen("/proc/stat", "r"); if (f) { u32 k_time, nice_time, u_time; if (fgets(line, 128, f) != NULL) { if (sscanf(line, "cpu %u %u %u %u\n", &u_time, &k_time, &nice_time, &idle_time) == 4) { u_k_time = u_time + k_time + nice_time; } } gf_fclose(f); } process_u_k_time = 0; the_rti.process_memory = 0; /*FIXME? under LinuxThreads this will only fetch stats for the calling thread, we would have to enumerate /proc to get the complete CPU usage of all therads of the process...*/ #if 0 sprintf(szProc, "/proc/%d/stat", the_rti.pid); f = gf_fopen(szProc, "r"); if (f) { fflush(f); if (fgets(line, 2048, f) != NULL) { char state; char *start; long cutime, cstime, priority, nice, itrealvalue, rss; int exit_signal, processor; unsigned long flags, minflt, cminflt, majflt, cmajflt, utime, stime,starttime, vsize, rlim, startcode, endcode, startstack, kstkesp, kstkeip, signal, blocked, sigignore, sigcatch, wchan, nswap, cnswap, rem; int ppid, pgrp ,session, tty_nr, tty_pgrp, res; start = strchr(line, ')'); if (start) start += 2; else { start = strchr(line, ' '); start++; } res = sscanf(start,"%c %d %d %d %d %d %lu %lu %lu %lu \ %lu %lu %lu %ld %ld %ld %ld %ld %ld %lu \ %lu %ld %lu %lu %lu %lu %lu %lu %lu %lu \ %lu %lu %lu %lu %lu %d %d", &state, &ppid, &pgrp, &session, &tty_nr, &tty_pgrp, &flags, &minflt, &cminflt, &majflt, &cmajflt, &utime, &stime, &cutime, &cstime, &priority, &nice, &itrealvalue, &rem, &starttime, &vsize, &rss, &rlim, &startcode, &endcode, &startstack, &kstkesp, &kstkeip, &signal, &blocked, &sigignore, &sigcatch, &wchan, &nswap, &cnswap, &exit_signal, &processor); if (res) process_u_k_time = (u64) (cutime + cstime); else { GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[RTI] PROC %s parse error\n", szProc)); } } else { GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[RTI] error reading pid/stat\n\n", szProc)); } gf_fclose(f); } else { GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[RTI] cannot open %s\n", szProc)); } sprintf(szProc, "/proc/%d/status", the_rti.pid); f = gf_fopen(szProc, "r"); if (f) { while (fgets(line, 1024, f) != NULL) { if (!strnicmp(line, "VmSize:", 7)) { sscanf(line, "VmSize: %"LLD" kB", &the_rti.process_memory); the_rti.process_memory *= 1024; } } gf_fclose(f); } else { GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[RTI] cannot open %s\n", szProc)); } #endif #ifndef GPAC_IPHONE the_rti.physical_memory = the_rti.physical_memory_avail = 0; f = gf_fopen("/proc/meminfo", "r"); if (f) { while (fgets(line, 1024, f) != NULL) { if (!strnicmp(line, "MemTotal:", 9)) { sscanf(line, "MemTotal: "LLU" kB", &the_rti.physical_memory); the_rti.physical_memory *= 1024; } else if (!strnicmp(line, "MemFree:", 8)) { sscanf(line, "MemFree: "LLU" kB", &the_rti.physical_memory_avail); the_rti.physical_memory_avail *= 1024; break; } } gf_fclose(f); } else { GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[RTI] cannot open /proc/meminfo\n")); } #endif the_rti.sampling_instant = last_update_time; if (last_update_time) { the_rti.sampling_period_duration = (entry_time - last_update_time); the_rti.process_cpu_time_diff = (u32) (process_u_k_time - last_process_k_u_time) * 10; /*oops, we have no choice but to assume 100% cpu usage during this period*/ if (!u_k_time) { the_rti.total_cpu_time_diff = the_rti.sampling_period_duration; u_k_time = (u32) (last_cpu_u_k_time + the_rti.sampling_period_duration); the_rti.cpu_idle_time = 0; the_rti.total_cpu_usage = 100; if (!the_rti.process_cpu_time_diff) the_rti.process_cpu_time_diff = the_rti.total_cpu_time_diff; the_rti.process_cpu_usage = (u32) ( 100 * the_rti.process_cpu_time_diff / the_rti.sampling_period_duration); } else { u64 samp_sys_time; /*move to ms (/proc/stat gives times in 100 ms unit*/ the_rti.total_cpu_time_diff = (u32) (u_k_time - last_cpu_u_k_time)*10; /*we're not that accurate....*/ if (the_rti.total_cpu_time_diff > the_rti.sampling_period_duration) the_rti.sampling_period_duration = the_rti.total_cpu_time_diff; if (!idle_time) idle_time = (the_rti.sampling_period_duration - the_rti.total_cpu_time_diff)/10; samp_sys_time = u_k_time - last_cpu_u_k_time; the_rti.cpu_idle_time = (u32) (idle_time - last_cpu_idle_time); the_rti.total_cpu_usage = (u32) ( 100 * samp_sys_time / (the_rti.cpu_idle_time + samp_sys_time ) ); /*move to ms (/proc/stat gives times in 100 ms unit*/ the_rti.cpu_idle_time *= 10; if (!the_rti.process_cpu_time_diff) the_rti.process_cpu_time_diff = the_rti.total_cpu_time_diff; the_rti.process_cpu_usage = (u32) ( 100 * the_rti.process_cpu_time_diff / (the_rti.cpu_idle_time + 10*samp_sys_time ) ); } } else { mem_at_startup = the_rti.physical_memory_avail; } the_rti.process_memory = mem_at_startup - the_rti.physical_memory_avail; #ifdef GPAC_MEMORY_TRACKING the_rti.gpac_memory = gpac_allocated_memory; #endif last_process_k_u_time = process_u_k_time; last_cpu_idle_time = idle_time; last_cpu_u_k_time = u_k_time; last_update_time = entry_time; memcpy(rti, &the_rti, sizeof(GF_SystemRTInfo)); return 1; } #endif GF_EXPORT Bool gf_sys_get_rti(u32 refresh_time_ms, GF_SystemRTInfo *rti, u32 flags) { Bool res = gf_sys_get_rti_os(refresh_time_ms, rti, flags); if (res) { if (!rti->process_memory) rti->process_memory = memory_at_gpac_startup - rti->physical_memory_avail; if (!rti->gpac_memory) rti->gpac_memory = memory_at_gpac_startup - rti->physical_memory_avail; } return res; } GF_EXPORT char * gf_get_default_cache_directory() { char szPath[GF_MAX_PATH]; char* root_tmp; size_t len; #ifdef _WIN32_WCE strcpy(szPath, "\\windows\\temp" ); #elif defined(WIN32) GetTempPath(GF_MAX_PATH, szPath); #else strcpy(szPath, "/tmp"); #endif root_tmp = gf_strdup(szPath); len = strlen(szPath); if (szPath[len-1] != GF_PATH_SEPARATOR) { szPath[len] = GF_PATH_SEPARATOR; szPath[len+1] = 0; } strcat(szPath, "gpac_cache"); if ( !gf_dir_exists(szPath) && gf_mkdir(szPath)!=GF_OK ) { return root_tmp; } gf_free(root_tmp); return gf_strdup(szPath); } GF_EXPORT Bool gf_sys_get_battery_state(Bool *onBattery, u32 *onCharge, u32*level, u32 *batteryLifeTime, u32 *batteryFullLifeTime) { #if defined(_WIN32_WCE) SYSTEM_POWER_STATUS_EX sps; GetSystemPowerStatusEx(&sps, 0); if (onBattery) *onBattery = sps.ACLineStatus ? 0 : 1; if (onCharge) *onCharge = (sps.BatteryFlag & BATTERY_FLAG_CHARGING) ? 1 : 0; if (level) *level = sps.BatteryLifePercent; if (batteryLifeTime) *batteryLifeTime = sps.BatteryLifeTime; if (batteryFullLifeTime) *batteryFullLifeTime = sps.BatteryFullLifeTime; #elif defined(WIN32) SYSTEM_POWER_STATUS sps; GetSystemPowerStatus(&sps); if (onBattery) *onBattery = sps.ACLineStatus ? GF_FALSE : GF_TRUE; if (onCharge) *onCharge = (sps.BatteryFlag & BATTERY_FLAG_CHARGING) ? 1 : 0; if (level) *level = sps.BatteryLifePercent; if (batteryLifeTime) *batteryLifeTime = sps.BatteryLifeTime; if (batteryFullLifeTime) *batteryFullLifeTime = sps.BatteryFullLifeTime; #endif return GF_TRUE; } struct GF_GlobalLock { const char * resourceName; }; #ifndef WIN32 #define CPF_CLOEXEC 1 #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> struct _GF_GlobalLock_opaque { char * resourceName; char * pidFile; int fd; }; GF_GlobalLock * gf_create_PID_file( const char * resourceName ) { const char * prefix = "/gpac_lock_"; const char * dir = gf_get_default_cache_directory(); char * pidfile; int flags; int status; pidfile = gf_malloc(strlen(dir)+strlen(prefix)+strlen(resourceName)+1); strcpy(pidfile, dir); strcat(pidfile, prefix); /* Use only valid names for file */ { const char *res; char * pid = &(pidfile[strlen(pidfile)]); for (res = resourceName; *res ; res++) { if (*res >= 'A' && *res <= 'z') *pid = * res; else *pid = '_'; pid++; } *pid = '\0'; } int fd = open(pidfile, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); if (fd == -1) goto exit; /* Get the flags */ flags = fcntl(fd, F_GETFD); if (flags == -1) { goto exit; } /* Set FD_CLOEXEC, so exclusive lock will be removed on exit, so even if GPAC crashes, * lock will be allowed for next instance */ flags |= FD_CLOEXEC; /* Now, update the flags */ if (fcntl(fd, F_SETFD, flags) == -1) { goto exit; } /* Now, we try to lock the file */ { struct flock fl; fl.l_type = F_WRLCK; fl.l_whence = SEEK_SET; fl.l_start = fl.l_len = 0; status = fcntl(fd, F_SETLK, &fl); } if (status == -1) { goto exit; } if (ftruncate(fd, 0) == -1) { goto exit; } /* Write the PID */ { int sz = 100; char * buf = gf_malloc( sz ); sz = snprintf(buf, sz, "%ld\n", (long) getpid()); if (write(fd, buf, sz) != sz) { gf_free(buf); goto exit; } } sync(); { GF_GlobalLock * lock = gf_malloc( sizeof(GF_GlobalLock)); lock->resourceName = gf_strdup(resourceName); lock->pidFile = pidfile; lock->fd = fd; return lock; } exit: if (fd >= 0) close(fd); return NULL; } #else /* WIN32 */ struct _GF_GlobalLock_opaque { char * resourceName; HANDLE hMutex; /*a named mutex is a system-mode object on windows*/ }; #endif GF_EXPORT GF_GlobalLock * gf_global_resource_lock(const char * resourceName) { #ifdef WIN32 #ifdef _WIN32_WCE unsigned short sWResourceName[MAX_PATH]; #endif DWORD lastErr; GF_GlobalLock *lock = gf_malloc(sizeof(GF_GlobalLock)); lock->resourceName = gf_strdup(resourceName); /*first ensure mutex is created*/ #ifdef _WIN32_WCE CE_CharToWide((char *)resourceName, sWResourceName); lock->hMutex = CreateMutex(NULL, TRUE, sWResourceName); #else lock->hMutex = CreateMutex(NULL, TRUE, resourceName); #endif lastErr = GetLastError(); if (lastErr && lastErr == ERROR_ALREADY_EXISTS) return NULL; if (!lock->hMutex) { GF_LOG(GF_LOG_ERROR, GF_LOG_MUTEX, ("[Mutex] Couldn't create mutex for global lock: %d\n", lastErr)); return NULL; } /*then lock it*/ switch (WaitForSingleObject(lock->hMutex, INFINITE)) { case WAIT_ABANDONED: case WAIT_TIMEOUT: assert(0); /*serious error: someone has modified the object elsewhere*/ GF_LOG(GF_LOG_ERROR, GF_LOG_MUTEX, ("[Mutex] Couldn't get the global lock\n")); gf_global_resource_unlock(lock); return NULL; } return lock; #else /* WIN32 */ return gf_create_PID_file(resourceName); #endif /* WIN32 */ } /*! * Unlock a previouly locked resource * \param lock The resource to unlock * \return GF_OK if evertything went fine */ GF_EXPORT GF_Err gf_global_resource_unlock(GF_GlobalLock * lock) { if (!lock) return GF_BAD_PARAM; #ifndef WIN32 assert( lock->pidFile); close(lock->fd); if (unlink(lock->pidFile)) perror("Failed to unlink lock file"); gf_free(lock->pidFile); lock->pidFile = NULL; lock->fd = -1; #else /* WIN32 */ { /*MSDN: "The mutex object is destroyed when its last handle has been closed."*/ BOOL ret = ReleaseMutex(lock->hMutex); if (!ret) { DWORD err = GetLastError(); GF_LOG(GF_LOG_ERROR, GF_LOG_MUTEX, ("[Mutex] Couldn't release mutex for global lock: %d\n", err)); } ret = CloseHandle(lock->hMutex); if (!ret) { DWORD err = GetLastError(); GF_LOG(GF_LOG_ERROR, GF_LOG_MUTEX, ("[Mutex] Couldn't destroy mutex for global lock: %d\n", err)); } } #endif if (lock->resourceName) gf_free(lock->resourceName); lock->resourceName = NULL; gf_free(lock); return GF_OK; } #ifdef GPAC_ANDROID fm_callback_func fm_cbk = NULL; static void *fm_cbk_obj = NULL; void gf_fm_request_set_callback(void *cbk_obj, fm_callback_func cbk_func) { fm_cbk = cbk_func; fm_cbk_obj = cbk_obj; } void gf_fm_request_call(u32 type, u32 param, int *value) { if (fm_cbk) fm_cbk(fm_cbk_obj, type, param, value); } #endif //GPAC_ANDROID GF_EXPORT s32 gf_gettimeofday(struct timeval *tp, void *tz) { return gettimeofday(tp, tz); } static u32 ntp_shift = GF_NTP_SEC_1900_TO_1970; GF_EXPORT void gf_net_set_ntp_shift(s32 shift) { ntp_shift = GF_NTP_SEC_1900_TO_1970 + shift; } /* NTP tools */ GF_EXPORT void gf_net_get_ntp(u32 *sec, u32 *frac) { u64 frac_part; struct timeval now; gettimeofday(&now, NULL); if (sec) { *sec = (u32) (now.tv_sec) + ntp_shift; } if (frac) { frac_part = now.tv_usec * 0xFFFFFFFFULL; frac_part /= 1000000; *frac = (u32) ( frac_part ); } } GF_EXPORT u64 gf_net_get_ntp_ts() { u64 res; u32 sec, frac; gf_net_get_ntp(&sec, &frac); res = sec; res<<= 32; res |= frac; return res; } GF_EXPORT s32 gf_net_get_ntp_diff_ms(u64 ntp) { u32 remote_s, remote_f, local_s, local_f; s64 local, remote; remote_s = (ntp >> 32); remote_f = (u32) (ntp & 0xFFFFFFFFULL); gf_net_get_ntp(&local_s, &local_f); local = local_s; local *= 1000; local += ((u64) local_f)*1000 / 0xFFFFFFFFULL; remote = remote_s; remote *= 1000; remote += ((u64) remote_f)*1000 / 0xFFFFFFFFULL; return (s32) (local - remote); } GF_EXPORT s32 gf_net_get_timezone() { #if defined(_WIN32_WCE) return 0; #else //this has been commented due to some reports of broken implementation on some systems ... // s32 val = timezone; // return val; /*FIXME - avoid errors at midnight when estimating timezone this does not work !!*/ s32 t_timezone; struct tm t_gmt, t_local; time_t t_time; t_time = time(NULL); t_gmt = *gmtime(&t_time); t_local = *localtime(&t_time); t_timezone = (t_gmt.tm_hour - t_local.tm_hour) * 3600 + (t_gmt.tm_min - t_local.tm_min) * 60; return t_timezone; #endif } //no mkgmtime on mingw..., use our own #if (defined(WIN32) && defined(__GNUC__)) static Bool leap_year(u32 year) { year += 1900; return (year % 4) == 0 && ((year % 100) != 0 || (year % 400) == 0) ? GF_TRUE : GF_FALSE; } static time_t gf_mktime_utc(struct tm *tm) { static const u32 days_per_month[2][12] = { {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} }; time_t time=0; int i; for (i=70; i<tm->tm_year; i++) { time += leap_year(i) ? 366 : 365; } for (i=0; i<tm->tm_mon; ++i) { time += days_per_month[leap_year(tm->tm_year)][i]; } time += tm->tm_mday - 1; time *= 24; time += tm->tm_hour; time *= 60; time += tm->tm_min; time *= 60; time += tm->tm_sec; return time; } #elif defined(WIN32) static time_t gf_mktime_utc(struct tm *tm) { return _mkgmtime(tm); } #elif defined(GPAC_ANDROID) #include <time64.h> #if defined(__LP64__) static time_t gf_mktime_utc(struct tm *tm) { return timegm64(tm); } #else static time_t gf_mktime_utc(struct tm *tm) { static const time_t kTimeMax = ~(1L << (sizeof(time_t) * CHAR_BIT - 1)); static const time_t kTimeMin = (1L << (sizeof(time_t) * CHAR_BIT - 1)); time64_t result = timegm64(tm); if (result < kTimeMin || result > kTimeMax) return -1; return result; } #endif #else static time_t gf_mktime_utc(struct tm *tm) { return timegm(tm); } #endif GF_EXPORT u64 gf_net_parse_date(const char *val) { u64 current_time; char szDay[50], szMonth[50]; u32 year, month, day, h, m, s, ms; s32 oh, om; Float secs; Bool neg_time_zone = GF_FALSE; #ifdef _WIN32_WCE SYSTEMTIME syst; FILETIME filet; #else struct tm t; memset(&t, 0, sizeof(struct tm)); #endif szDay[0] = szMonth[0] = 0; year = month = day = h = m = s = 0; oh = om = 0; secs = 0; if (sscanf(val, "%d-%d-%dT%d:%d:%gZ", &year, &month, &day, &h, &m, &secs) == 6) { } else if (sscanf(val, "%d-%d-%dT%d:%d:%g-%d:%d", &year, &month, &day, &h, &m, &secs, &oh, &om) == 8) { neg_time_zone = GF_TRUE; } else if (sscanf(val, "%d-%d-%dT%d:%d:%g+%d:%d", &year, &month, &day, &h, &m, &secs, &oh, &om) == 8) { } else if (sscanf(val, "%3s, %d %3s %d %d:%d:%d", szDay, &day, szMonth, &year, &h, &m, &s)==7) { secs = (Float) s; } else if (sscanf(val, "%9s, %d-%3s-%d %02d:%02d:%02d GMT", szDay, &day, szMonth, &year, &h, &m, &s)==7) { secs = (Float) s; } else if (sscanf(val, "%3s %3s %d %02d:%02d:%02d %d", szDay, szMonth, &day, &year, &h, &m, &s)==7) { secs = (Float) s; } else { GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[Core] Cannot parse date string %s\n", val)); return 0; } if (month) { month -= 1; } else { if (!strcmp(szMonth, "Jan")) month = 0; else if (!strcmp(szMonth, "Feb")) month = 1; else if (!strcmp(szMonth, "Mar")) month = 2; else if (!strcmp(szMonth, "Apr")) month = 3; else if (!strcmp(szMonth, "May")) month = 4; else if (!strcmp(szMonth, "Jun")) month = 5; else if (!strcmp(szMonth, "Jul")) month = 6; else if (!strcmp(szMonth, "Aug")) month = 7; else if (!strcmp(szMonth, "Sep")) month = 8; else if (!strcmp(szMonth, "Oct")) month = 9; else if (!strcmp(szMonth, "Nov")) month = 10; else if (!strcmp(szMonth, "Dec")) month = 11; } #ifdef _WIN32_WCE memset(&syst, 0, sizeof(SYSTEMTIME)); syst.wYear = year; syst.wMonth = month + 1; syst.wDay = day; syst.wHour = h; syst.wMinute = m; syst.wSecond = (u32) secs; SystemTimeToFileTime(&syst, &filet); current_time = (u64) ((*(LONGLONG *) &filet - TIMESPEC_TO_FILETIME_OFFSET) / 10000000); #else t.tm_year = year>1000 ? year-1900 : year; t.tm_mday = day; t.tm_hour = h; t.tm_min = m; t.tm_sec = (u32) secs; t.tm_mon = month; if (strlen(szDay) ) { if (!strcmp(szDay, "Mon") || !strcmp(szDay, "Monday")) t.tm_wday = 0; else if (!strcmp(szDay, "Tue") || !strcmp(szDay, "Tuesday")) t.tm_wday = 1; else if (!strcmp(szDay, "Wed") || !strcmp(szDay, "Wednesday")) t.tm_wday = 2; else if (!strcmp(szDay, "Thu") || !strcmp(szDay, "Thursday")) t.tm_wday = 3; else if (!strcmp(szDay, "Fri") || !strcmp(szDay, "Friday")) t.tm_wday = 4; else if (!strcmp(szDay, "Sat") || !strcmp(szDay, "Saturday")) t.tm_wday = 5; else if (!strcmp(szDay, "Sun") || !strcmp(szDay, "Sunday")) t.tm_wday = 6; } current_time = gf_mktime_utc(&t); if ((s64) current_time == -1) { //use 1 ms return 1; } if (current_time == 0) { //use 1 ms return 1; } #endif if (om || oh) { s32 diff = (60*oh + om)*60; if (neg_time_zone) diff = -diff; current_time = current_time + diff; } current_time *= 1000; ms = (u32) ( (secs - (u32) secs) * 1000); return current_time + ms; } GF_EXPORT u64 gf_net_get_utc() { u64 current_time; Double msec; u32 sec, frac; gf_net_get_ntp(&sec, &frac); current_time = sec - GF_NTP_SEC_1900_TO_1970; current_time *= 1000; msec = frac*1000.0; msec /= 0xFFFFFFFF; current_time += (u64) msec; return current_time; } GF_EXPORT GF_Err gf_bin128_parse(const char *string, bin128 value) { u32 len; u32 i=0; if (!strnicmp(string, "0x", 2)) string += 2; len = (u32) strlen(string); if (len >= 32) { u32 j; for (j=0; j<len; j+=2) { u32 v; char szV[5]; while (string[j] && !isalnum(string[j])) j++; if (!string[j]) break; sprintf(szV, "%c%c", string[j], string[j+1]); sscanf(szV, "%x", &v); value[i] = v; i++; } } if (i != 16) { GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[CORE] 128bit blob is not 16-bytes long: %s\n", string)); return GF_BAD_PARAM; } return GF_OK; }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_798_0
crossvul-cpp_data_good_1494_0
/* crypto/x509/x509_vfy.c */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * 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 copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL 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. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ #include <stdio.h> #include <time.h> #include <errno.h> #include "internal/cryptlib.h" #include <openssl/crypto.h> #include <openssl/lhash.h> #include <openssl/buffer.h> #include <openssl/evp.h> #include <openssl/asn1.h> #include <openssl/x509.h> #include <openssl/x509v3.h> #include <openssl/objects.h> #include "x509_lcl.h" /* CRL score values */ /* No unhandled critical extensions */ #define CRL_SCORE_NOCRITICAL 0x100 /* certificate is within CRL scope */ #define CRL_SCORE_SCOPE 0x080 /* CRL times valid */ #define CRL_SCORE_TIME 0x040 /* Issuer name matches certificate */ #define CRL_SCORE_ISSUER_NAME 0x020 /* If this score or above CRL is probably valid */ #define CRL_SCORE_VALID (CRL_SCORE_NOCRITICAL|CRL_SCORE_TIME|CRL_SCORE_SCOPE) /* CRL issuer is certificate issuer */ #define CRL_SCORE_ISSUER_CERT 0x018 /* CRL issuer is on certificate path */ #define CRL_SCORE_SAME_PATH 0x008 /* CRL issuer matches CRL AKID */ #define CRL_SCORE_AKID 0x004 /* Have a delta CRL with valid times */ #define CRL_SCORE_TIME_DELTA 0x002 static int null_callback(int ok, X509_STORE_CTX *e); static int check_issued(X509_STORE_CTX *ctx, X509 *x, X509 *issuer); static X509 *find_issuer(X509_STORE_CTX *ctx, STACK_OF(X509) *sk, X509 *x); static int check_chain_extensions(X509_STORE_CTX *ctx); static int check_name_constraints(X509_STORE_CTX *ctx); static int check_id(X509_STORE_CTX *ctx); static int check_trust(X509_STORE_CTX *ctx); static int check_revocation(X509_STORE_CTX *ctx); static int check_cert(X509_STORE_CTX *ctx); static int check_policy(X509_STORE_CTX *ctx); static int get_issuer_sk(X509 **issuer, X509_STORE_CTX *ctx, X509 *x); static int get_crl_score(X509_STORE_CTX *ctx, X509 **pissuer, unsigned int *preasons, X509_CRL *crl, X509 *x); static int get_crl_delta(X509_STORE_CTX *ctx, X509_CRL **pcrl, X509_CRL **pdcrl, X509 *x); static void get_delta_sk(X509_STORE_CTX *ctx, X509_CRL **dcrl, int *pcrl_score, X509_CRL *base, STACK_OF(X509_CRL) *crls); static void crl_akid_check(X509_STORE_CTX *ctx, X509_CRL *crl, X509 **pissuer, int *pcrl_score); static int crl_crldp_check(X509 *x, X509_CRL *crl, int crl_score, unsigned int *preasons); static int check_crl_path(X509_STORE_CTX *ctx, X509 *x); static int check_crl_chain(X509_STORE_CTX *ctx, STACK_OF(X509) *cert_path, STACK_OF(X509) *crl_path); static int internal_verify(X509_STORE_CTX *ctx); const char X509_version[] = "X.509" OPENSSL_VERSION_PTEXT; static int null_callback(int ok, X509_STORE_CTX *e) { return ok; } /* Return 1 is a certificate is self signed */ static int cert_self_signed(X509 *x) { X509_check_purpose(x, -1, 0); if (x->ex_flags & EXFLAG_SS) return 1; else return 0; } /* Given a certificate try and find an exact match in the store */ static X509 *lookup_cert_match(X509_STORE_CTX *ctx, X509 *x) { STACK_OF(X509) *certs; X509 *xtmp = NULL; int i; /* Lookup all certs with matching subject name */ certs = ctx->lookup_certs(ctx, X509_get_subject_name(x)); if (certs == NULL) return NULL; /* Look for exact match */ for (i = 0; i < sk_X509_num(certs); i++) { xtmp = sk_X509_value(certs, i); if (!X509_cmp(xtmp, x)) break; } if (i < sk_X509_num(certs)) CRYPTO_add(&xtmp->references, 1, CRYPTO_LOCK_X509); else xtmp = NULL; sk_X509_pop_free(certs, X509_free); return xtmp; } int X509_verify_cert(X509_STORE_CTX *ctx) { X509 *x, *xtmp, *xtmp2, *chain_ss = NULL; int bad_chain = 0; X509_VERIFY_PARAM *param = ctx->param; int depth, i, ok = 0; int num, j, retry; int (*cb) (int xok, X509_STORE_CTX *xctx); STACK_OF(X509) *sktmp = NULL; if (ctx->cert == NULL) { X509err(X509_F_X509_VERIFY_CERT, X509_R_NO_CERT_SET_FOR_US_TO_VERIFY); return -1; } cb = ctx->verify_cb; /* * first we make sure the chain we are going to build is present and that * the first entry is in place */ if (ctx->chain == NULL) { if (((ctx->chain = sk_X509_new_null()) == NULL) || (!sk_X509_push(ctx->chain, ctx->cert))) { X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE); goto end; } CRYPTO_add(&ctx->cert->references, 1, CRYPTO_LOCK_X509); ctx->last_untrusted = 1; } /* We use a temporary STACK so we can chop and hack at it */ if (ctx->untrusted != NULL && (sktmp = sk_X509_dup(ctx->untrusted)) == NULL) { X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE); goto end; } num = sk_X509_num(ctx->chain); x = sk_X509_value(ctx->chain, num - 1); depth = param->depth; for (;;) { /* If we have enough, we break */ if (depth < num) break; /* FIXME: If this happens, we should take * note of it and, if appropriate, use the * X509_V_ERR_CERT_CHAIN_TOO_LONG error code * later. */ /* If we are self signed, we break */ if (cert_self_signed(x)) break; /* * If asked see if we can find issuer in trusted store first */ if (ctx->param->flags & X509_V_FLAG_TRUSTED_FIRST) { ok = ctx->get_issuer(&xtmp, ctx, x); if (ok < 0) return ok; /* * If successful for now free up cert so it will be picked up * again later. */ if (ok > 0) { X509_free(xtmp); break; } } /* If we were passed a cert chain, use it first */ if (ctx->untrusted != NULL) { xtmp = find_issuer(ctx, sktmp, x); if (xtmp != NULL) { if (!sk_X509_push(ctx->chain, xtmp)) { X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE); goto end; } CRYPTO_add(&xtmp->references, 1, CRYPTO_LOCK_X509); (void)sk_X509_delete_ptr(sktmp, xtmp); ctx->last_untrusted++; x = xtmp; num++; /* * reparse the full chain for the next one */ continue; } } break; } /* Remember how many untrusted certs we have */ j = num; /* * at this point, chain should contain a list of untrusted certificates. * We now need to add at least one trusted one, if possible, otherwise we * complain. */ do { /* * Examine last certificate in chain and see if it is self signed. */ i = sk_X509_num(ctx->chain); x = sk_X509_value(ctx->chain, i - 1); if (cert_self_signed(x)) { /* we have a self signed certificate */ if (sk_X509_num(ctx->chain) == 1) { /* * We have a single self signed certificate: see if we can * find it in the store. We must have an exact match to avoid * possible impersonation. */ ok = ctx->get_issuer(&xtmp, ctx, x); if ((ok <= 0) || X509_cmp(x, xtmp)) { ctx->error = X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT; ctx->current_cert = x; ctx->error_depth = i - 1; if (ok == 1) X509_free(xtmp); bad_chain = 1; ok = cb(0, ctx); if (!ok) goto end; } else { /* * We have a match: replace certificate with store * version so we get any trust settings. */ X509_free(x); x = xtmp; (void)sk_X509_set(ctx->chain, i - 1, x); ctx->last_untrusted = 0; } } else { /* * extract and save self signed certificate for later use */ chain_ss = sk_X509_pop(ctx->chain); ctx->last_untrusted--; num--; j--; x = sk_X509_value(ctx->chain, num - 1); } } /* We now lookup certs from the certificate store */ for (;;) { /* If we have enough, we break */ if (depth < num) break; /* If we are self signed, we break */ if (cert_self_signed(x)) break; ok = ctx->get_issuer(&xtmp, ctx, x); if (ok < 0) return ok; if (ok == 0) break; x = xtmp; if (!sk_X509_push(ctx->chain, x)) { X509_free(xtmp); X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE); return 0; } num++; } /* we now have our chain, lets check it... */ i = check_trust(ctx); /* If explicitly rejected error */ if (i == X509_TRUST_REJECTED) goto end; /* * If it's not explicitly trusted then check if there is an alternative * chain that could be used. We only do this if we haven't already * checked via TRUSTED_FIRST and the user hasn't switched off alternate * chain checking */ retry = 0; if (i != X509_TRUST_TRUSTED && !(ctx->param->flags & X509_V_FLAG_TRUSTED_FIRST) && !(ctx->param->flags & X509_V_FLAG_NO_ALT_CHAINS)) { while (j-- > 1) { STACK_OF(X509) *chtmp = ctx->chain; xtmp2 = sk_X509_value(ctx->chain, j - 1); /* * Temporarily set chain to NULL so we don't discount * duplicates: the same certificate could be an untrusted * CA found in the trusted store. */ ctx->chain = NULL; ok = ctx->get_issuer(&xtmp, ctx, xtmp2); ctx->chain = chtmp; if (ok < 0) goto end; /* Check if we found an alternate chain */ if (ok > 0) { /* * Free up the found cert we'll add it again later */ X509_free(xtmp); /* * Dump all the certs above this point - we've found an * alternate chain */ while (num > j) { xtmp = sk_X509_pop(ctx->chain); X509_free(xtmp); num--; ctx->last_untrusted--; } retry = 1; break; } } } } while (retry); /* * If not explicitly trusted then indicate error unless it's a single * self signed certificate in which case we've indicated an error already * and set bad_chain == 1 */ if (i != X509_TRUST_TRUSTED && !bad_chain) { if ((chain_ss == NULL) || !ctx->check_issued(ctx, x, chain_ss)) { if (ctx->last_untrusted >= num) ctx->error = X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY; else ctx->error = X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT; ctx->current_cert = x; } else { sk_X509_push(ctx->chain, chain_ss); num++; ctx->last_untrusted = num; ctx->current_cert = chain_ss; ctx->error = X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN; chain_ss = NULL; } ctx->error_depth = num - 1; bad_chain = 1; ok = cb(0, ctx); if (!ok) goto end; } /* We have the chain complete: now we need to check its purpose */ ok = check_chain_extensions(ctx); if (!ok) goto end; /* Check name constraints */ ok = check_name_constraints(ctx); if (!ok) goto end; ok = check_id(ctx); if (!ok) goto end; /* We may as well copy down any DSA parameters that are required */ X509_get_pubkey_parameters(NULL, ctx->chain); /* * Check revocation status: we do this after copying parameters because * they may be needed for CRL signature verification. */ ok = ctx->check_revocation(ctx); if (!ok) goto end; i = X509_chain_check_suiteb(&ctx->error_depth, NULL, ctx->chain, ctx->param->flags); if (i != X509_V_OK) { ctx->error = i; ctx->current_cert = sk_X509_value(ctx->chain, ctx->error_depth); ok = cb(0, ctx); if (!ok) goto end; } /* At this point, we have a chain and need to verify it */ if (ctx->verify != NULL) ok = ctx->verify(ctx); else ok = internal_verify(ctx); if (!ok) goto end; /* RFC 3779 path validation, now that CRL check has been done */ ok = v3_asid_validate_path(ctx); if (!ok) goto end; ok = v3_addr_validate_path(ctx); if (!ok) goto end; /* If we get this far evaluate policies */ if (!bad_chain && (ctx->param->flags & X509_V_FLAG_POLICY_CHECK)) ok = ctx->check_policy(ctx); if (ok) goto done; end: X509_get_pubkey_parameters(NULL, ctx->chain); done: sk_X509_free(sktmp); X509_free(chain_ss); return ok; } /* * Given a STACK_OF(X509) find the issuer of cert (if any) */ static X509 *find_issuer(X509_STORE_CTX *ctx, STACK_OF(X509) *sk, X509 *x) { int i; X509 *issuer, *rv = NULL;; for (i = 0; i < sk_X509_num(sk); i++) { issuer = sk_X509_value(sk, i); if (ctx->check_issued(ctx, x, issuer)) { rv = issuer; if (x509_check_cert_time(ctx, rv, 1)) break; } } return rv; } /* Given a possible certificate and issuer check them */ static int check_issued(X509_STORE_CTX *ctx, X509 *x, X509 *issuer) { int ret; if (x == issuer) return cert_self_signed(x); ret = X509_check_issued(issuer, x); if (ret == X509_V_OK) { int i; X509 *ch; /* Special case: single self signed certificate */ if (cert_self_signed(x) && sk_X509_num(ctx->chain) == 1) return 1; for (i = 0; i < sk_X509_num(ctx->chain); i++) { ch = sk_X509_value(ctx->chain, i); if (ch == issuer || !X509_cmp(ch, issuer)) { ret = X509_V_ERR_PATH_LOOP; break; } } } if (ret == X509_V_OK) return 1; /* If we haven't asked for issuer errors don't set ctx */ if (!(ctx->param->flags & X509_V_FLAG_CB_ISSUER_CHECK)) return 0; ctx->error = ret; ctx->current_cert = x; ctx->current_issuer = issuer; return ctx->verify_cb(0, ctx); } /* Alternative lookup method: look from a STACK stored in other_ctx */ static int get_issuer_sk(X509 **issuer, X509_STORE_CTX *ctx, X509 *x) { *issuer = find_issuer(ctx, ctx->other_ctx, x); if (*issuer) { CRYPTO_add(&(*issuer)->references, 1, CRYPTO_LOCK_X509); return 1; } else return 0; } /* * Check a certificate chains extensions for consistency with the supplied * purpose */ static int check_chain_extensions(X509_STORE_CTX *ctx) { int i, ok = 0, must_be_ca, plen = 0; X509 *x; int (*cb) (int xok, X509_STORE_CTX *xctx); int proxy_path_length = 0; int purpose; int allow_proxy_certs; cb = ctx->verify_cb; /*- * must_be_ca can have 1 of 3 values: * -1: we accept both CA and non-CA certificates, to allow direct * use of self-signed certificates (which are marked as CA). * 0: we only accept non-CA certificates. This is currently not * used, but the possibility is present for future extensions. * 1: we only accept CA certificates. This is currently used for * all certificates in the chain except the leaf certificate. */ must_be_ca = -1; /* CRL path validation */ if (ctx->parent) { allow_proxy_certs = 0; purpose = X509_PURPOSE_CRL_SIGN; } else { allow_proxy_certs = ! !(ctx->param->flags & X509_V_FLAG_ALLOW_PROXY_CERTS); /* * A hack to keep people who don't want to modify their software * happy */ if (getenv("OPENSSL_ALLOW_PROXY_CERTS")) allow_proxy_certs = 1; purpose = ctx->param->purpose; } /* Check all untrusted certificates */ for (i = 0; i < ctx->last_untrusted; i++) { int ret; x = sk_X509_value(ctx->chain, i); if (!(ctx->param->flags & X509_V_FLAG_IGNORE_CRITICAL) && (x->ex_flags & EXFLAG_CRITICAL)) { ctx->error = X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION; ctx->error_depth = i; ctx->current_cert = x; ok = cb(0, ctx); if (!ok) goto end; } if (!allow_proxy_certs && (x->ex_flags & EXFLAG_PROXY)) { ctx->error = X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED; ctx->error_depth = i; ctx->current_cert = x; ok = cb(0, ctx); if (!ok) goto end; } ret = X509_check_ca(x); switch (must_be_ca) { case -1: if ((ctx->param->flags & X509_V_FLAG_X509_STRICT) && (ret != 1) && (ret != 0)) { ret = 0; ctx->error = X509_V_ERR_INVALID_CA; } else ret = 1; break; case 0: if (ret != 0) { ret = 0; ctx->error = X509_V_ERR_INVALID_NON_CA; } else ret = 1; break; default: if ((ret == 0) || ((ctx->param->flags & X509_V_FLAG_X509_STRICT) && (ret != 1))) { ret = 0; ctx->error = X509_V_ERR_INVALID_CA; } else ret = 1; break; } if (ret == 0) { ctx->error_depth = i; ctx->current_cert = x; ok = cb(0, ctx); if (!ok) goto end; } if (ctx->param->purpose > 0) { ret = X509_check_purpose(x, purpose, must_be_ca > 0); if ((ret == 0) || ((ctx->param->flags & X509_V_FLAG_X509_STRICT) && (ret != 1))) { ctx->error = X509_V_ERR_INVALID_PURPOSE; ctx->error_depth = i; ctx->current_cert = x; ok = cb(0, ctx); if (!ok) goto end; } } /* Check pathlen if not self issued */ if ((i > 1) && !(x->ex_flags & EXFLAG_SI) && (x->ex_pathlen != -1) && (plen > (x->ex_pathlen + proxy_path_length + 1))) { ctx->error = X509_V_ERR_PATH_LENGTH_EXCEEDED; ctx->error_depth = i; ctx->current_cert = x; ok = cb(0, ctx); if (!ok) goto end; } /* Increment path length if not self issued */ if (!(x->ex_flags & EXFLAG_SI)) plen++; /* * If this certificate is a proxy certificate, the next certificate * must be another proxy certificate or a EE certificate. If not, * the next certificate must be a CA certificate. */ if (x->ex_flags & EXFLAG_PROXY) { if (x->ex_pcpathlen != -1 && i > x->ex_pcpathlen) { ctx->error = X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED; ctx->error_depth = i; ctx->current_cert = x; ok = cb(0, ctx); if (!ok) goto end; } proxy_path_length++; must_be_ca = 0; } else must_be_ca = 1; } ok = 1; end: return ok; } static int check_name_constraints(X509_STORE_CTX *ctx) { X509 *x; int i, j, rv; /* Check name constraints for all certificates */ for (i = sk_X509_num(ctx->chain) - 1; i >= 0; i--) { x = sk_X509_value(ctx->chain, i); /* Ignore self issued certs unless last in chain */ if (i && (x->ex_flags & EXFLAG_SI)) continue; /* * Check against constraints for all certificates higher in chain * including trust anchor. Trust anchor not strictly speaking needed * but if it includes constraints it is to be assumed it expects them * to be obeyed. */ for (j = sk_X509_num(ctx->chain) - 1; j > i; j--) { NAME_CONSTRAINTS *nc = sk_X509_value(ctx->chain, j)->nc; if (nc) { rv = NAME_CONSTRAINTS_check(x, nc); if (rv != X509_V_OK) { ctx->error = rv; ctx->error_depth = i; ctx->current_cert = x; if (!ctx->verify_cb(0, ctx)) return 0; } } } } return 1; } static int check_id_error(X509_STORE_CTX *ctx, int errcode) { ctx->error = errcode; ctx->current_cert = ctx->cert; ctx->error_depth = 0; return ctx->verify_cb(0, ctx); } static int check_hosts(X509 *x, X509_VERIFY_PARAM_ID *id) { int i; int n = sk_OPENSSL_STRING_num(id->hosts); char *name; for (i = 0; i < n; ++i) { name = sk_OPENSSL_STRING_value(id->hosts, i); if (X509_check_host(x, name, 0, id->hostflags, &id->peername) > 0) return 1; } return n == 0; } static int check_id(X509_STORE_CTX *ctx) { X509_VERIFY_PARAM *vpm = ctx->param; X509_VERIFY_PARAM_ID *id = vpm->id; X509 *x = ctx->cert; if (id->hosts && check_hosts(x, id) <= 0) { if (!check_id_error(ctx, X509_V_ERR_HOSTNAME_MISMATCH)) return 0; } if (id->email && X509_check_email(x, id->email, id->emaillen, 0) <= 0) { if (!check_id_error(ctx, X509_V_ERR_EMAIL_MISMATCH)) return 0; } if (id->ip && X509_check_ip(x, id->ip, id->iplen, 0) <= 0) { if (!check_id_error(ctx, X509_V_ERR_IP_ADDRESS_MISMATCH)) return 0; } return 1; } static int check_trust(X509_STORE_CTX *ctx) { int i, ok; X509 *x = NULL; int (*cb) (int xok, X509_STORE_CTX *xctx); cb = ctx->verify_cb; /* Check all trusted certificates in chain */ for (i = ctx->last_untrusted; i < sk_X509_num(ctx->chain); i++) { x = sk_X509_value(ctx->chain, i); ok = X509_check_trust(x, ctx->param->trust, 0); /* If explicitly trusted return trusted */ if (ok == X509_TRUST_TRUSTED) return X509_TRUST_TRUSTED; /* * If explicitly rejected notify callback and reject if not * overridden. */ if (ok == X509_TRUST_REJECTED) { ctx->error_depth = i; ctx->current_cert = x; ctx->error = X509_V_ERR_CERT_REJECTED; ok = cb(0, ctx); if (!ok) return X509_TRUST_REJECTED; } } /* * If we accept partial chains and have at least one trusted certificate * return success. */ if (ctx->param->flags & X509_V_FLAG_PARTIAL_CHAIN) { X509 *mx; if (ctx->last_untrusted < sk_X509_num(ctx->chain)) return X509_TRUST_TRUSTED; x = sk_X509_value(ctx->chain, 0); mx = lookup_cert_match(ctx, x); if (mx) { (void)sk_X509_set(ctx->chain, 0, mx); X509_free(x); ctx->last_untrusted = 0; return X509_TRUST_TRUSTED; } } /* * If no trusted certs in chain at all return untrusted and allow * standard (no issuer cert) etc errors to be indicated. */ return X509_TRUST_UNTRUSTED; } static int check_revocation(X509_STORE_CTX *ctx) { int i = 0, last = 0, ok = 0; if (!(ctx->param->flags & X509_V_FLAG_CRL_CHECK)) return 1; if (ctx->param->flags & X509_V_FLAG_CRL_CHECK_ALL) last = sk_X509_num(ctx->chain) - 1; else { /* If checking CRL paths this isn't the EE certificate */ if (ctx->parent) return 1; last = 0; } for (i = 0; i <= last; i++) { ctx->error_depth = i; ok = check_cert(ctx); if (!ok) return ok; } return 1; } static int check_cert(X509_STORE_CTX *ctx) { X509_CRL *crl = NULL, *dcrl = NULL; X509 *x = NULL; int ok = 0, cnum = 0; unsigned int last_reasons = 0; cnum = ctx->error_depth; x = sk_X509_value(ctx->chain, cnum); ctx->current_cert = x; ctx->current_issuer = NULL; ctx->current_crl_score = 0; ctx->current_reasons = 0; while (ctx->current_reasons != CRLDP_ALL_REASONS) { last_reasons = ctx->current_reasons; /* Try to retrieve relevant CRL */ if (ctx->get_crl) ok = ctx->get_crl(ctx, &crl, x); else ok = get_crl_delta(ctx, &crl, &dcrl, x); /* * If error looking up CRL, nothing we can do except notify callback */ if (!ok) { ctx->error = X509_V_ERR_UNABLE_TO_GET_CRL; ok = ctx->verify_cb(0, ctx); goto err; } ctx->current_crl = crl; ok = ctx->check_crl(ctx, crl); if (!ok) goto err; if (dcrl) { ok = ctx->check_crl(ctx, dcrl); if (!ok) goto err; ok = ctx->cert_crl(ctx, dcrl, x); if (!ok) goto err; } else ok = 1; /* Don't look in full CRL if delta reason is removefromCRL */ if (ok != 2) { ok = ctx->cert_crl(ctx, crl, x); if (!ok) goto err; } X509_CRL_free(crl); X509_CRL_free(dcrl); crl = NULL; dcrl = NULL; /* * If reasons not updated we wont get anywhere by another iteration, * so exit loop. */ if (last_reasons == ctx->current_reasons) { ctx->error = X509_V_ERR_UNABLE_TO_GET_CRL; ok = ctx->verify_cb(0, ctx); goto err; } } err: X509_CRL_free(crl); X509_CRL_free(dcrl); ctx->current_crl = NULL; return ok; } /* Check CRL times against values in X509_STORE_CTX */ static int check_crl_time(X509_STORE_CTX *ctx, X509_CRL *crl, int notify) { time_t *ptime; int i; if (notify) ctx->current_crl = crl; if (ctx->param->flags & X509_V_FLAG_USE_CHECK_TIME) ptime = &ctx->param->check_time; else ptime = NULL; i = X509_cmp_time(X509_CRL_get_lastUpdate(crl), ptime); if (i == 0) { if (!notify) return 0; ctx->error = X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD; if (!ctx->verify_cb(0, ctx)) return 0; } if (i > 0) { if (!notify) return 0; ctx->error = X509_V_ERR_CRL_NOT_YET_VALID; if (!ctx->verify_cb(0, ctx)) return 0; } if (X509_CRL_get_nextUpdate(crl)) { i = X509_cmp_time(X509_CRL_get_nextUpdate(crl), ptime); if (i == 0) { if (!notify) return 0; ctx->error = X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD; if (!ctx->verify_cb(0, ctx)) return 0; } /* Ignore expiry of base CRL is delta is valid */ if ((i < 0) && !(ctx->current_crl_score & CRL_SCORE_TIME_DELTA)) { if (!notify) return 0; ctx->error = X509_V_ERR_CRL_HAS_EXPIRED; if (!ctx->verify_cb(0, ctx)) return 0; } } if (notify) ctx->current_crl = NULL; return 1; } static int get_crl_sk(X509_STORE_CTX *ctx, X509_CRL **pcrl, X509_CRL **pdcrl, X509 **pissuer, int *pscore, unsigned int *preasons, STACK_OF(X509_CRL) *crls) { int i, crl_score, best_score = *pscore; unsigned int reasons, best_reasons = 0; X509 *x = ctx->current_cert; X509_CRL *crl, *best_crl = NULL; X509 *crl_issuer = NULL, *best_crl_issuer = NULL; for (i = 0; i < sk_X509_CRL_num(crls); i++) { crl = sk_X509_CRL_value(crls, i); reasons = *preasons; crl_score = get_crl_score(ctx, &crl_issuer, &reasons, crl, x); if (crl_score > best_score) { best_crl = crl; best_crl_issuer = crl_issuer; best_score = crl_score; best_reasons = reasons; } } if (best_crl) { X509_CRL_free(*pcrl); *pcrl = best_crl; *pissuer = best_crl_issuer; *pscore = best_score; *preasons = best_reasons; CRYPTO_add(&best_crl->references, 1, CRYPTO_LOCK_X509_CRL); X509_CRL_free(*pdcrl); *pdcrl = NULL; get_delta_sk(ctx, pdcrl, pscore, best_crl, crls); } if (best_score >= CRL_SCORE_VALID) return 1; return 0; } /* * Compare two CRL extensions for delta checking purposes. They should be * both present or both absent. If both present all fields must be identical. */ static int crl_extension_match(X509_CRL *a, X509_CRL *b, int nid) { ASN1_OCTET_STRING *exta, *extb; int i; i = X509_CRL_get_ext_by_NID(a, nid, -1); if (i >= 0) { /* Can't have multiple occurrences */ if (X509_CRL_get_ext_by_NID(a, nid, i) != -1) return 0; exta = X509_EXTENSION_get_data(X509_CRL_get_ext(a, i)); } else exta = NULL; i = X509_CRL_get_ext_by_NID(b, nid, -1); if (i >= 0) { if (X509_CRL_get_ext_by_NID(b, nid, i) != -1) return 0; extb = X509_EXTENSION_get_data(X509_CRL_get_ext(b, i)); } else extb = NULL; if (!exta && !extb) return 1; if (!exta || !extb) return 0; if (ASN1_OCTET_STRING_cmp(exta, extb)) return 0; return 1; } /* See if a base and delta are compatible */ static int check_delta_base(X509_CRL *delta, X509_CRL *base) { /* Delta CRL must be a delta */ if (!delta->base_crl_number) return 0; /* Base must have a CRL number */ if (!base->crl_number) return 0; /* Issuer names must match */ if (X509_NAME_cmp(X509_CRL_get_issuer(base), X509_CRL_get_issuer(delta))) return 0; /* AKID and IDP must match */ if (!crl_extension_match(delta, base, NID_authority_key_identifier)) return 0; if (!crl_extension_match(delta, base, NID_issuing_distribution_point)) return 0; /* Delta CRL base number must not exceed Full CRL number. */ if (ASN1_INTEGER_cmp(delta->base_crl_number, base->crl_number) > 0) return 0; /* Delta CRL number must exceed full CRL number */ if (ASN1_INTEGER_cmp(delta->crl_number, base->crl_number) > 0) return 1; return 0; } /* * For a given base CRL find a delta... maybe extend to delta scoring or * retrieve a chain of deltas... */ static void get_delta_sk(X509_STORE_CTX *ctx, X509_CRL **dcrl, int *pscore, X509_CRL *base, STACK_OF(X509_CRL) *crls) { X509_CRL *delta; int i; if (!(ctx->param->flags & X509_V_FLAG_USE_DELTAS)) return; if (!((ctx->current_cert->ex_flags | base->flags) & EXFLAG_FRESHEST)) return; for (i = 0; i < sk_X509_CRL_num(crls); i++) { delta = sk_X509_CRL_value(crls, i); if (check_delta_base(delta, base)) { if (check_crl_time(ctx, delta, 0)) *pscore |= CRL_SCORE_TIME_DELTA; CRYPTO_add(&delta->references, 1, CRYPTO_LOCK_X509_CRL); *dcrl = delta; return; } } *dcrl = NULL; } /* * For a given CRL return how suitable it is for the supplied certificate * 'x'. The return value is a mask of several criteria. If the issuer is not * the certificate issuer this is returned in *pissuer. The reasons mask is * also used to determine if the CRL is suitable: if no new reasons the CRL * is rejected, otherwise reasons is updated. */ static int get_crl_score(X509_STORE_CTX *ctx, X509 **pissuer, unsigned int *preasons, X509_CRL *crl, X509 *x) { int crl_score = 0; unsigned int tmp_reasons = *preasons, crl_reasons; /* First see if we can reject CRL straight away */ /* Invalid IDP cannot be processed */ if (crl->idp_flags & IDP_INVALID) return 0; /* Reason codes or indirect CRLs need extended CRL support */ if (!(ctx->param->flags & X509_V_FLAG_EXTENDED_CRL_SUPPORT)) { if (crl->idp_flags & (IDP_INDIRECT | IDP_REASONS)) return 0; } else if (crl->idp_flags & IDP_REASONS) { /* If no new reasons reject */ if (!(crl->idp_reasons & ~tmp_reasons)) return 0; } /* Don't process deltas at this stage */ else if (crl->base_crl_number) return 0; /* If issuer name doesn't match certificate need indirect CRL */ if (X509_NAME_cmp(X509_get_issuer_name(x), X509_CRL_get_issuer(crl))) { if (!(crl->idp_flags & IDP_INDIRECT)) return 0; } else crl_score |= CRL_SCORE_ISSUER_NAME; if (!(crl->flags & EXFLAG_CRITICAL)) crl_score |= CRL_SCORE_NOCRITICAL; /* Check expiry */ if (check_crl_time(ctx, crl, 0)) crl_score |= CRL_SCORE_TIME; /* Check authority key ID and locate certificate issuer */ crl_akid_check(ctx, crl, pissuer, &crl_score); /* If we can't locate certificate issuer at this point forget it */ if (!(crl_score & CRL_SCORE_AKID)) return 0; /* Check cert for matching CRL distribution points */ if (crl_crldp_check(x, crl, crl_score, &crl_reasons)) { /* If no new reasons reject */ if (!(crl_reasons & ~tmp_reasons)) return 0; tmp_reasons |= crl_reasons; crl_score |= CRL_SCORE_SCOPE; } *preasons = tmp_reasons; return crl_score; } static void crl_akid_check(X509_STORE_CTX *ctx, X509_CRL *crl, X509 **pissuer, int *pcrl_score) { X509 *crl_issuer = NULL; X509_NAME *cnm = X509_CRL_get_issuer(crl); int cidx = ctx->error_depth; int i; if (cidx != sk_X509_num(ctx->chain) - 1) cidx++; crl_issuer = sk_X509_value(ctx->chain, cidx); if (X509_check_akid(crl_issuer, crl->akid) == X509_V_OK) { if (*pcrl_score & CRL_SCORE_ISSUER_NAME) { *pcrl_score |= CRL_SCORE_AKID | CRL_SCORE_ISSUER_CERT; *pissuer = crl_issuer; return; } } for (cidx++; cidx < sk_X509_num(ctx->chain); cidx++) { crl_issuer = sk_X509_value(ctx->chain, cidx); if (X509_NAME_cmp(X509_get_subject_name(crl_issuer), cnm)) continue; if (X509_check_akid(crl_issuer, crl->akid) == X509_V_OK) { *pcrl_score |= CRL_SCORE_AKID | CRL_SCORE_SAME_PATH; *pissuer = crl_issuer; return; } } /* Anything else needs extended CRL support */ if (!(ctx->param->flags & X509_V_FLAG_EXTENDED_CRL_SUPPORT)) return; /* * Otherwise the CRL issuer is not on the path. Look for it in the set of * untrusted certificates. */ for (i = 0; i < sk_X509_num(ctx->untrusted); i++) { crl_issuer = sk_X509_value(ctx->untrusted, i); if (X509_NAME_cmp(X509_get_subject_name(crl_issuer), cnm)) continue; if (X509_check_akid(crl_issuer, crl->akid) == X509_V_OK) { *pissuer = crl_issuer; *pcrl_score |= CRL_SCORE_AKID; return; } } } /* * Check the path of a CRL issuer certificate. This creates a new * X509_STORE_CTX and populates it with most of the parameters from the * parent. This could be optimised somewhat since a lot of path checking will * be duplicated by the parent, but this will rarely be used in practice. */ static int check_crl_path(X509_STORE_CTX *ctx, X509 *x) { X509_STORE_CTX crl_ctx; int ret; /* Don't allow recursive CRL path validation */ if (ctx->parent) return 0; if (!X509_STORE_CTX_init(&crl_ctx, ctx->ctx, x, ctx->untrusted)) return -1; crl_ctx.crls = ctx->crls; /* Copy verify params across */ X509_STORE_CTX_set0_param(&crl_ctx, ctx->param); crl_ctx.parent = ctx; crl_ctx.verify_cb = ctx->verify_cb; /* Verify CRL issuer */ ret = X509_verify_cert(&crl_ctx); if (ret <= 0) goto err; /* Check chain is acceptable */ ret = check_crl_chain(ctx, ctx->chain, crl_ctx.chain); err: X509_STORE_CTX_cleanup(&crl_ctx); return ret; } /* * RFC3280 says nothing about the relationship between CRL path and * certificate path, which could lead to situations where a certificate could * be revoked or validated by a CA not authorised to do so. RFC5280 is more * strict and states that the two paths must end in the same trust anchor, * though some discussions remain... until this is resolved we use the * RFC5280 version */ static int check_crl_chain(X509_STORE_CTX *ctx, STACK_OF(X509) *cert_path, STACK_OF(X509) *crl_path) { X509 *cert_ta, *crl_ta; cert_ta = sk_X509_value(cert_path, sk_X509_num(cert_path) - 1); crl_ta = sk_X509_value(crl_path, sk_X509_num(crl_path) - 1); if (!X509_cmp(cert_ta, crl_ta)) return 1; return 0; } /*- * Check for match between two dist point names: three separate cases. * 1. Both are relative names and compare X509_NAME types. * 2. One full, one relative. Compare X509_NAME to GENERAL_NAMES. * 3. Both are full names and compare two GENERAL_NAMES. * 4. One is NULL: automatic match. */ static int idp_check_dp(DIST_POINT_NAME *a, DIST_POINT_NAME *b) { X509_NAME *nm = NULL; GENERAL_NAMES *gens = NULL; GENERAL_NAME *gena, *genb; int i, j; if (!a || !b) return 1; if (a->type == 1) { if (!a->dpname) return 0; /* Case 1: two X509_NAME */ if (b->type == 1) { if (!b->dpname) return 0; if (!X509_NAME_cmp(a->dpname, b->dpname)) return 1; else return 0; } /* Case 2: set name and GENERAL_NAMES appropriately */ nm = a->dpname; gens = b->name.fullname; } else if (b->type == 1) { if (!b->dpname) return 0; /* Case 2: set name and GENERAL_NAMES appropriately */ gens = a->name.fullname; nm = b->dpname; } /* Handle case 2 with one GENERAL_NAMES and one X509_NAME */ if (nm) { for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) { gena = sk_GENERAL_NAME_value(gens, i); if (gena->type != GEN_DIRNAME) continue; if (!X509_NAME_cmp(nm, gena->d.directoryName)) return 1; } return 0; } /* Else case 3: two GENERAL_NAMES */ for (i = 0; i < sk_GENERAL_NAME_num(a->name.fullname); i++) { gena = sk_GENERAL_NAME_value(a->name.fullname, i); for (j = 0; j < sk_GENERAL_NAME_num(b->name.fullname); j++) { genb = sk_GENERAL_NAME_value(b->name.fullname, j); if (!GENERAL_NAME_cmp(gena, genb)) return 1; } } return 0; } static int crldp_check_crlissuer(DIST_POINT *dp, X509_CRL *crl, int crl_score) { int i; X509_NAME *nm = X509_CRL_get_issuer(crl); /* If no CRLissuer return is successful iff don't need a match */ if (!dp->CRLissuer) return ! !(crl_score & CRL_SCORE_ISSUER_NAME); for (i = 0; i < sk_GENERAL_NAME_num(dp->CRLissuer); i++) { GENERAL_NAME *gen = sk_GENERAL_NAME_value(dp->CRLissuer, i); if (gen->type != GEN_DIRNAME) continue; if (!X509_NAME_cmp(gen->d.directoryName, nm)) return 1; } return 0; } /* Check CRLDP and IDP */ static int crl_crldp_check(X509 *x, X509_CRL *crl, int crl_score, unsigned int *preasons) { int i; if (crl->idp_flags & IDP_ONLYATTR) return 0; if (x->ex_flags & EXFLAG_CA) { if (crl->idp_flags & IDP_ONLYUSER) return 0; } else { if (crl->idp_flags & IDP_ONLYCA) return 0; } *preasons = crl->idp_reasons; for (i = 0; i < sk_DIST_POINT_num(x->crldp); i++) { DIST_POINT *dp = sk_DIST_POINT_value(x->crldp, i); if (crldp_check_crlissuer(dp, crl, crl_score)) { if (!crl->idp || idp_check_dp(dp->distpoint, crl->idp->distpoint)) { *preasons &= dp->dp_reasons; return 1; } } } if ((!crl->idp || !crl->idp->distpoint) && (crl_score & CRL_SCORE_ISSUER_NAME)) return 1; return 0; } /* * Retrieve CRL corresponding to current certificate. If deltas enabled try * to find a delta CRL too */ static int get_crl_delta(X509_STORE_CTX *ctx, X509_CRL **pcrl, X509_CRL **pdcrl, X509 *x) { int ok; X509 *issuer = NULL; int crl_score = 0; unsigned int reasons; X509_CRL *crl = NULL, *dcrl = NULL; STACK_OF(X509_CRL) *skcrl; X509_NAME *nm = X509_get_issuer_name(x); reasons = ctx->current_reasons; ok = get_crl_sk(ctx, &crl, &dcrl, &issuer, &crl_score, &reasons, ctx->crls); if (ok) goto done; /* Lookup CRLs from store */ skcrl = ctx->lookup_crls(ctx, nm); /* If no CRLs found and a near match from get_crl_sk use that */ if (!skcrl && crl) goto done; get_crl_sk(ctx, &crl, &dcrl, &issuer, &crl_score, &reasons, skcrl); sk_X509_CRL_pop_free(skcrl, X509_CRL_free); done: /* If we got any kind of CRL use it and return success */ if (crl) { ctx->current_issuer = issuer; ctx->current_crl_score = crl_score; ctx->current_reasons = reasons; *pcrl = crl; *pdcrl = dcrl; return 1; } return 0; } /* Check CRL validity */ static int check_crl(X509_STORE_CTX *ctx, X509_CRL *crl) { X509 *issuer = NULL; EVP_PKEY *ikey = NULL; int ok = 0, chnum, cnum; cnum = ctx->error_depth; chnum = sk_X509_num(ctx->chain) - 1; /* if we have an alternative CRL issuer cert use that */ if (ctx->current_issuer) issuer = ctx->current_issuer; /* * Else find CRL issuer: if not last certificate then issuer is next * certificate in chain. */ else if (cnum < chnum) issuer = sk_X509_value(ctx->chain, cnum + 1); else { issuer = sk_X509_value(ctx->chain, chnum); /* If not self signed, can't check signature */ if (!ctx->check_issued(ctx, issuer, issuer)) { ctx->error = X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER; ok = ctx->verify_cb(0, ctx); if (!ok) goto err; } } if (issuer) { /* * Skip most tests for deltas because they have already been done */ if (!crl->base_crl_number) { /* Check for cRLSign bit if keyUsage present */ if ((issuer->ex_flags & EXFLAG_KUSAGE) && !(issuer->ex_kusage & KU_CRL_SIGN)) { ctx->error = X509_V_ERR_KEYUSAGE_NO_CRL_SIGN; ok = ctx->verify_cb(0, ctx); if (!ok) goto err; } if (!(ctx->current_crl_score & CRL_SCORE_SCOPE)) { ctx->error = X509_V_ERR_DIFFERENT_CRL_SCOPE; ok = ctx->verify_cb(0, ctx); if (!ok) goto err; } if (!(ctx->current_crl_score & CRL_SCORE_SAME_PATH)) { if (check_crl_path(ctx, ctx->current_issuer) <= 0) { ctx->error = X509_V_ERR_CRL_PATH_VALIDATION_ERROR; ok = ctx->verify_cb(0, ctx); if (!ok) goto err; } } if (crl->idp_flags & IDP_INVALID) { ctx->error = X509_V_ERR_INVALID_EXTENSION; ok = ctx->verify_cb(0, ctx); if (!ok) goto err; } } if (!(ctx->current_crl_score & CRL_SCORE_TIME)) { ok = check_crl_time(ctx, crl, 1); if (!ok) goto err; } /* Attempt to get issuer certificate public key */ ikey = X509_get_pubkey(issuer); if (!ikey) { ctx->error = X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY; ok = ctx->verify_cb(0, ctx); if (!ok) goto err; } else { int rv; rv = X509_CRL_check_suiteb(crl, ikey, ctx->param->flags); if (rv != X509_V_OK) { ctx->error = rv; ok = ctx->verify_cb(0, ctx); if (!ok) goto err; } /* Verify CRL signature */ if (X509_CRL_verify(crl, ikey) <= 0) { ctx->error = X509_V_ERR_CRL_SIGNATURE_FAILURE; ok = ctx->verify_cb(0, ctx); if (!ok) goto err; } } } ok = 1; err: EVP_PKEY_free(ikey); return ok; } /* Check certificate against CRL */ static int cert_crl(X509_STORE_CTX *ctx, X509_CRL *crl, X509 *x) { int ok; X509_REVOKED *rev; /* * The rules changed for this... previously if a CRL contained unhandled * critical extensions it could still be used to indicate a certificate * was revoked. This has since been changed since critical extension can * change the meaning of CRL entries. */ if (!(ctx->param->flags & X509_V_FLAG_IGNORE_CRITICAL) && (crl->flags & EXFLAG_CRITICAL)) { ctx->error = X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION; ok = ctx->verify_cb(0, ctx); if (!ok) return 0; } /* * Look for serial number of certificate in CRL If found make sure reason * is not removeFromCRL. */ if (X509_CRL_get0_by_cert(crl, &rev, x)) { if (rev->reason == CRL_REASON_REMOVE_FROM_CRL) return 2; ctx->error = X509_V_ERR_CERT_REVOKED; ok = ctx->verify_cb(0, ctx); if (!ok) return 0; } return 1; } static int check_policy(X509_STORE_CTX *ctx) { int ret; if (ctx->parent) return 1; ret = X509_policy_check(&ctx->tree, &ctx->explicit_policy, ctx->chain, ctx->param->policies, ctx->param->flags); if (ret == 0) { X509err(X509_F_CHECK_POLICY, ERR_R_MALLOC_FAILURE); return 0; } /* Invalid or inconsistent extensions */ if (ret == -1) { /* * Locate certificates with bad extensions and notify callback. */ X509 *x; int i; for (i = 1; i < sk_X509_num(ctx->chain); i++) { x = sk_X509_value(ctx->chain, i); if (!(x->ex_flags & EXFLAG_INVALID_POLICY)) continue; ctx->current_cert = x; ctx->error = X509_V_ERR_INVALID_POLICY_EXTENSION; if (!ctx->verify_cb(0, ctx)) return 0; } return 1; } if (ret == -2) { ctx->current_cert = NULL; ctx->error = X509_V_ERR_NO_EXPLICIT_POLICY; return ctx->verify_cb(0, ctx); } if (ctx->param->flags & X509_V_FLAG_NOTIFY_POLICY) { ctx->current_cert = NULL; ctx->error = X509_V_OK; if (!ctx->verify_cb(2, ctx)) return 0; } return 1; } int x509_check_cert_time(X509_STORE_CTX *ctx, X509 *x, int quiet) { time_t *ptime; int i; if (ctx->param->flags & X509_V_FLAG_USE_CHECK_TIME) ptime = &ctx->param->check_time; else ptime = NULL; i = X509_cmp_time(X509_get_notBefore(x), ptime); if (i == 0) { if (quiet) return 0; ctx->error = X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD; ctx->current_cert = x; if (!ctx->verify_cb(0, ctx)) return 0; } if (i > 0) { if (quiet) return 0; ctx->error = X509_V_ERR_CERT_NOT_YET_VALID; ctx->current_cert = x; if (!ctx->verify_cb(0, ctx)) return 0; } i = X509_cmp_time(X509_get_notAfter(x), ptime); if (i == 0) { if (quiet) return 0; ctx->error = X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD; ctx->current_cert = x; if (!ctx->verify_cb(0, ctx)) return 0; } if (i < 0) { if (quiet) return 0; ctx->error = X509_V_ERR_CERT_HAS_EXPIRED; ctx->current_cert = x; if (!ctx->verify_cb(0, ctx)) return 0; } return 1; } static int internal_verify(X509_STORE_CTX *ctx) { int ok = 0, n; X509 *xs, *xi; EVP_PKEY *pkey = NULL; int (*cb) (int xok, X509_STORE_CTX *xctx); cb = ctx->verify_cb; n = sk_X509_num(ctx->chain); ctx->error_depth = n - 1; n--; xi = sk_X509_value(ctx->chain, n); if (ctx->check_issued(ctx, xi, xi)) xs = xi; else { if (ctx->param->flags & X509_V_FLAG_PARTIAL_CHAIN) { xs = xi; goto check_cert; } if (n <= 0) { ctx->error = X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE; ctx->current_cert = xi; ok = cb(0, ctx); goto end; } else { n--; ctx->error_depth = n; xs = sk_X509_value(ctx->chain, n); } } /* ctx->error=0; not needed */ while (n >= 0) { ctx->error_depth = n; /* * Skip signature check for self signed certificates unless * explicitly asked for. It doesn't add any security and just wastes * time. */ if (!xs->valid && (xs != xi || (ctx->param->flags & X509_V_FLAG_CHECK_SS_SIGNATURE))) { if ((pkey = X509_get_pubkey(xi)) == NULL) { ctx->error = X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY; ctx->current_cert = xi; ok = (*cb) (0, ctx); if (!ok) goto end; } else if (X509_verify(xs, pkey) <= 0) { ctx->error = X509_V_ERR_CERT_SIGNATURE_FAILURE; ctx->current_cert = xs; ok = (*cb) (0, ctx); if (!ok) { EVP_PKEY_free(pkey); goto end; } } EVP_PKEY_free(pkey); pkey = NULL; } xs->valid = 1; check_cert: ok = x509_check_cert_time(ctx, xs, 0); if (!ok) goto end; /* The last error (if any) is still in the error value */ ctx->current_issuer = xi; ctx->current_cert = xs; ok = (*cb) (1, ctx); if (!ok) goto end; n--; if (n >= 0) { xi = xs; xs = sk_X509_value(ctx->chain, n); } } ok = 1; end: return ok; } int X509_cmp_current_time(const ASN1_TIME *ctm) { return X509_cmp_time(ctm, NULL); } int X509_cmp_time(const ASN1_TIME *ctm, time_t *cmp_time) { char *str; ASN1_TIME atm; long offset; char buff1[24], buff2[24], *p; int i, j, remaining; p = buff1; remaining = ctm->length; str = (char *)ctm->data; /* * Note that the following (historical) code allows much more slack in the * time format than RFC5280. In RFC5280, the representation is fixed: * UTCTime: YYMMDDHHMMSSZ * GeneralizedTime: YYYYMMDDHHMMSSZ */ if (ctm->type == V_ASN1_UTCTIME) { /* YYMMDDHHMM[SS]Z or YYMMDDHHMM[SS](+-)hhmm */ int min_length = sizeof("YYMMDDHHMMZ") - 1; int max_length = sizeof("YYMMDDHHMMSS+hhmm") - 1; if (remaining < min_length || remaining > max_length) return 0; memcpy(p, str, 10); p += 10; str += 10; remaining -= 10; } else { /* YYYYMMDDHHMM[SS[.fff]]Z or YYYYMMDDHHMM[SS[.f[f[f]]]](+-)hhmm */ int min_length = sizeof("YYYYMMDDHHMMZ") - 1; int max_length = sizeof("YYYYMMDDHHMMSS.fff+hhmm") - 1; if (remaining < min_length || remaining > max_length) return 0; memcpy(p, str, 12); p += 12; str += 12; remaining -= 12; } if ((*str == 'Z') || (*str == '-') || (*str == '+')) { *(p++) = '0'; *(p++) = '0'; } else { /* SS (seconds) */ if (remaining < 2) return 0; *(p++) = *(str++); *(p++) = *(str++); remaining -= 2; /* * Skip any (up to three) fractional seconds... * TODO(emilia): in RFC5280, fractional seconds are forbidden. * Can we just kill them altogether? */ if (remaining && *str == '.') { str++; remaining--; for (i = 0; i < 3 && remaining; i++, str++, remaining--) { if (*str < '0' || *str > '9') break; } } } *(p++) = 'Z'; *(p++) = '\0'; /* We now need either a terminating 'Z' or an offset. */ if (!remaining) return 0; if (*str == 'Z') { if (remaining != 1) return 0; offset = 0; } else { /* (+-)HHMM */ if ((*str != '+') && (*str != '-')) return 0; /* Historical behaviour: the (+-)hhmm offset is forbidden in RFC5280. */ if (remaining != 5) return 0; if (str[1] < '0' || str[1] > '9' || str[2] < '0' || str[2] > '9' || str[3] < '0' || str[3] > '9' || str[4] < '0' || str[4] > '9') return 0; offset = ((str[1] - '0') * 10 + (str[2] - '0')) * 60; offset += (str[3] - '0') * 10 + (str[4] - '0'); if (*str == '-') offset = -offset; } atm.type = ctm->type; atm.flags = 0; atm.length = sizeof(buff2); atm.data = (unsigned char *)buff2; if (X509_time_adj(&atm, offset * 60, cmp_time) == NULL) return 0; if (ctm->type == V_ASN1_UTCTIME) { i = (buff1[0] - '0') * 10 + (buff1[1] - '0'); if (i < 50) i += 100; /* cf. RFC 2459 */ j = (buff2[0] - '0') * 10 + (buff2[1] - '0'); if (j < 50) j += 100; if (i < j) return -1; if (i > j) return 1; } i = strcmp(buff1, buff2); if (i == 0) /* wait a second then return younger :-) */ return -1; else return i; } ASN1_TIME *X509_gmtime_adj(ASN1_TIME *s, long adj) { return X509_time_adj(s, adj, NULL); } ASN1_TIME *X509_time_adj(ASN1_TIME *s, long offset_sec, time_t *in_tm) { return X509_time_adj_ex(s, 0, offset_sec, in_tm); } ASN1_TIME *X509_time_adj_ex(ASN1_TIME *s, int offset_day, long offset_sec, time_t *in_tm) { time_t t; if (in_tm) t = *in_tm; else time(&t); if (s && !(s->flags & ASN1_STRING_FLAG_MSTRING)) { if (s->type == V_ASN1_UTCTIME) return ASN1_UTCTIME_adj(s, t, offset_day, offset_sec); if (s->type == V_ASN1_GENERALIZEDTIME) return ASN1_GENERALIZEDTIME_adj(s, t, offset_day, offset_sec); } return ASN1_TIME_adj(s, t, offset_day, offset_sec); } int X509_get_pubkey_parameters(EVP_PKEY *pkey, STACK_OF(X509) *chain) { EVP_PKEY *ktmp = NULL, *ktmp2; int i, j; if ((pkey != NULL) && !EVP_PKEY_missing_parameters(pkey)) return 1; for (i = 0; i < sk_X509_num(chain); i++) { ktmp = X509_get_pubkey(sk_X509_value(chain, i)); if (ktmp == NULL) { X509err(X509_F_X509_GET_PUBKEY_PARAMETERS, X509_R_UNABLE_TO_GET_CERTS_PUBLIC_KEY); return 0; } if (!EVP_PKEY_missing_parameters(ktmp)) break; EVP_PKEY_free(ktmp); ktmp = NULL; } if (ktmp == NULL) { X509err(X509_F_X509_GET_PUBKEY_PARAMETERS, X509_R_UNABLE_TO_FIND_PARAMETERS_IN_CHAIN); return 0; } /* first, populate the other certs */ for (j = i - 1; j >= 0; j--) { ktmp2 = X509_get_pubkey(sk_X509_value(chain, j)); EVP_PKEY_copy_parameters(ktmp2, ktmp); EVP_PKEY_free(ktmp2); } if (pkey != NULL) EVP_PKEY_copy_parameters(pkey, ktmp); EVP_PKEY_free(ktmp); return 1; } /* Make a delta CRL as the diff between two full CRLs */ X509_CRL *X509_CRL_diff(X509_CRL *base, X509_CRL *newer, EVP_PKEY *skey, const EVP_MD *md, unsigned int flags) { X509_CRL *crl = NULL; int i; STACK_OF(X509_REVOKED) *revs = NULL; /* CRLs can't be delta already */ if (base->base_crl_number || newer->base_crl_number) { X509err(X509_F_X509_CRL_DIFF, X509_R_CRL_ALREADY_DELTA); return NULL; } /* Base and new CRL must have a CRL number */ if (!base->crl_number || !newer->crl_number) { X509err(X509_F_X509_CRL_DIFF, X509_R_NO_CRL_NUMBER); return NULL; } /* Issuer names must match */ if (X509_NAME_cmp(X509_CRL_get_issuer(base), X509_CRL_get_issuer(newer))) { X509err(X509_F_X509_CRL_DIFF, X509_R_ISSUER_MISMATCH); return NULL; } /* AKID and IDP must match */ if (!crl_extension_match(base, newer, NID_authority_key_identifier)) { X509err(X509_F_X509_CRL_DIFF, X509_R_AKID_MISMATCH); return NULL; } if (!crl_extension_match(base, newer, NID_issuing_distribution_point)) { X509err(X509_F_X509_CRL_DIFF, X509_R_IDP_MISMATCH); return NULL; } /* Newer CRL number must exceed full CRL number */ if (ASN1_INTEGER_cmp(newer->crl_number, base->crl_number) <= 0) { X509err(X509_F_X509_CRL_DIFF, X509_R_NEWER_CRL_NOT_NEWER); return NULL; } /* CRLs must verify */ if (skey && (X509_CRL_verify(base, skey) <= 0 || X509_CRL_verify(newer, skey) <= 0)) { X509err(X509_F_X509_CRL_DIFF, X509_R_CRL_VERIFY_FAILURE); return NULL; } /* Create new CRL */ crl = X509_CRL_new(); if (!crl || !X509_CRL_set_version(crl, 1)) goto memerr; /* Set issuer name */ if (!X509_CRL_set_issuer_name(crl, X509_CRL_get_issuer(newer))) goto memerr; if (!X509_CRL_set_lastUpdate(crl, X509_CRL_get_lastUpdate(newer))) goto memerr; if (!X509_CRL_set_nextUpdate(crl, X509_CRL_get_nextUpdate(newer))) goto memerr; /* Set base CRL number: must be critical */ if (!X509_CRL_add1_ext_i2d(crl, NID_delta_crl, base->crl_number, 1, 0)) goto memerr; /* * Copy extensions across from newest CRL to delta: this will set CRL * number to correct value too. */ for (i = 0; i < X509_CRL_get_ext_count(newer); i++) { X509_EXTENSION *ext; ext = X509_CRL_get_ext(newer, i); if (!X509_CRL_add_ext(crl, ext, -1)) goto memerr; } /* Go through revoked entries, copying as needed */ revs = X509_CRL_get_REVOKED(newer); for (i = 0; i < sk_X509_REVOKED_num(revs); i++) { X509_REVOKED *rvn, *rvtmp; rvn = sk_X509_REVOKED_value(revs, i); /* * Add only if not also in base. TODO: need something cleverer here * for some more complex CRLs covering multiple CAs. */ if (!X509_CRL_get0_by_serial(base, &rvtmp, rvn->serialNumber)) { rvtmp = X509_REVOKED_dup(rvn); if (!rvtmp) goto memerr; if (!X509_CRL_add0_revoked(crl, rvtmp)) { X509_REVOKED_free(rvtmp); goto memerr; } } } /* TODO: optionally prune deleted entries */ if (skey && md && !X509_CRL_sign(crl, skey, md)) goto memerr; return crl; memerr: X509err(X509_F_X509_CRL_DIFF, ERR_R_MALLOC_FAILURE); X509_CRL_free(crl); return NULL; } int X509_STORE_CTX_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func, CRYPTO_EX_dup *dup_func, CRYPTO_EX_free *free_func) { /* * This function is (usually) called only once, by * SSL_get_ex_data_X509_STORE_CTX_idx (ssl/ssl_cert.c). */ return CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_X509_STORE_CTX, argl, argp, new_func, dup_func, free_func); } int X509_STORE_CTX_set_ex_data(X509_STORE_CTX *ctx, int idx, void *data) { return CRYPTO_set_ex_data(&ctx->ex_data, idx, data); } void *X509_STORE_CTX_get_ex_data(X509_STORE_CTX *ctx, int idx) { return CRYPTO_get_ex_data(&ctx->ex_data, idx); } int X509_STORE_CTX_get_error(X509_STORE_CTX *ctx) { return ctx->error; } void X509_STORE_CTX_set_error(X509_STORE_CTX *ctx, int err) { ctx->error = err; } int X509_STORE_CTX_get_error_depth(X509_STORE_CTX *ctx) { return ctx->error_depth; } X509 *X509_STORE_CTX_get_current_cert(X509_STORE_CTX *ctx) { return ctx->current_cert; } STACK_OF(X509) *X509_STORE_CTX_get_chain(X509_STORE_CTX *ctx) { return ctx->chain; } STACK_OF(X509) *X509_STORE_CTX_get1_chain(X509_STORE_CTX *ctx) { if (!ctx->chain) return NULL; return X509_chain_up_ref(ctx->chain); } X509 *X509_STORE_CTX_get0_current_issuer(X509_STORE_CTX *ctx) { return ctx->current_issuer; } X509_CRL *X509_STORE_CTX_get0_current_crl(X509_STORE_CTX *ctx) { return ctx->current_crl; } X509_STORE_CTX *X509_STORE_CTX_get0_parent_ctx(X509_STORE_CTX *ctx) { return ctx->parent; } void X509_STORE_CTX_set_cert(X509_STORE_CTX *ctx, X509 *x) { ctx->cert = x; } void X509_STORE_CTX_set_chain(X509_STORE_CTX *ctx, STACK_OF(X509) *sk) { ctx->untrusted = sk; } void X509_STORE_CTX_set0_crls(X509_STORE_CTX *ctx, STACK_OF(X509_CRL) *sk) { ctx->crls = sk; } int X509_STORE_CTX_set_purpose(X509_STORE_CTX *ctx, int purpose) { return X509_STORE_CTX_purpose_inherit(ctx, 0, purpose, 0); } int X509_STORE_CTX_set_trust(X509_STORE_CTX *ctx, int trust) { return X509_STORE_CTX_purpose_inherit(ctx, 0, 0, trust); } /* * This function is used to set the X509_STORE_CTX purpose and trust values. * This is intended to be used when another structure has its own trust and * purpose values which (if set) will be inherited by the ctx. If they aren't * set then we will usually have a default purpose in mind which should then * be used to set the trust value. An example of this is SSL use: an SSL * structure will have its own purpose and trust settings which the * application can set: if they aren't set then we use the default of SSL * client/server. */ int X509_STORE_CTX_purpose_inherit(X509_STORE_CTX *ctx, int def_purpose, int purpose, int trust) { int idx; /* If purpose not set use default */ if (!purpose) purpose = def_purpose; /* If we have a purpose then check it is valid */ if (purpose) { X509_PURPOSE *ptmp; idx = X509_PURPOSE_get_by_id(purpose); if (idx == -1) { X509err(X509_F_X509_STORE_CTX_PURPOSE_INHERIT, X509_R_UNKNOWN_PURPOSE_ID); return 0; } ptmp = X509_PURPOSE_get0(idx); if (ptmp->trust == X509_TRUST_DEFAULT) { idx = X509_PURPOSE_get_by_id(def_purpose); if (idx == -1) { X509err(X509_F_X509_STORE_CTX_PURPOSE_INHERIT, X509_R_UNKNOWN_PURPOSE_ID); return 0; } ptmp = X509_PURPOSE_get0(idx); } /* If trust not set then get from purpose default */ if (!trust) trust = ptmp->trust; } if (trust) { idx = X509_TRUST_get_by_id(trust); if (idx == -1) { X509err(X509_F_X509_STORE_CTX_PURPOSE_INHERIT, X509_R_UNKNOWN_TRUST_ID); return 0; } } if (purpose && !ctx->param->purpose) ctx->param->purpose = purpose; if (trust && !ctx->param->trust) ctx->param->trust = trust; return 1; } X509_STORE_CTX *X509_STORE_CTX_new(void) { X509_STORE_CTX *ctx = OPENSSL_malloc(sizeof(*ctx)); if (!ctx) { X509err(X509_F_X509_STORE_CTX_NEW, ERR_R_MALLOC_FAILURE); return NULL; } memset(ctx, 0, sizeof(*ctx)); return ctx; } void X509_STORE_CTX_free(X509_STORE_CTX *ctx) { if (!ctx) return; X509_STORE_CTX_cleanup(ctx); OPENSSL_free(ctx); } int X509_STORE_CTX_init(X509_STORE_CTX *ctx, X509_STORE *store, X509 *x509, STACK_OF(X509) *chain) { int ret = 1; ctx->ctx = store; ctx->current_method = 0; ctx->cert = x509; ctx->untrusted = chain; ctx->crls = NULL; ctx->last_untrusted = 0; ctx->other_ctx = NULL; ctx->valid = 0; ctx->chain = NULL; ctx->error = 0; ctx->explicit_policy = 0; ctx->error_depth = 0; ctx->current_cert = NULL; ctx->current_issuer = NULL; ctx->current_crl = NULL; ctx->current_crl_score = 0; ctx->current_reasons = 0; ctx->tree = NULL; ctx->parent = NULL; ctx->param = X509_VERIFY_PARAM_new(); if (!ctx->param) { X509err(X509_F_X509_STORE_CTX_INIT, ERR_R_MALLOC_FAILURE); return 0; } /* * Inherit callbacks and flags from X509_STORE if not set use defaults. */ if (store) ret = X509_VERIFY_PARAM_inherit(ctx->param, store->param); else ctx->param->inh_flags |= X509_VP_FLAG_DEFAULT | X509_VP_FLAG_ONCE; if (store) { ctx->verify_cb = store->verify_cb; ctx->cleanup = store->cleanup; } else ctx->cleanup = 0; if (ret) ret = X509_VERIFY_PARAM_inherit(ctx->param, X509_VERIFY_PARAM_lookup("default")); if (ret == 0) { X509err(X509_F_X509_STORE_CTX_INIT, ERR_R_MALLOC_FAILURE); return 0; } if (store && store->check_issued) ctx->check_issued = store->check_issued; else ctx->check_issued = check_issued; if (store && store->get_issuer) ctx->get_issuer = store->get_issuer; else ctx->get_issuer = X509_STORE_CTX_get1_issuer; if (store && store->verify_cb) ctx->verify_cb = store->verify_cb; else ctx->verify_cb = null_callback; if (store && store->verify) ctx->verify = store->verify; else ctx->verify = internal_verify; if (store && store->check_revocation) ctx->check_revocation = store->check_revocation; else ctx->check_revocation = check_revocation; if (store && store->get_crl) ctx->get_crl = store->get_crl; else ctx->get_crl = NULL; if (store && store->check_crl) ctx->check_crl = store->check_crl; else ctx->check_crl = check_crl; if (store && store->cert_crl) ctx->cert_crl = store->cert_crl; else ctx->cert_crl = cert_crl; if (store && store->lookup_certs) ctx->lookup_certs = store->lookup_certs; else ctx->lookup_certs = X509_STORE_get1_certs; if (store && store->lookup_crls) ctx->lookup_crls = store->lookup_crls; else ctx->lookup_crls = X509_STORE_get1_crls; ctx->check_policy = check_policy; /* * Since X509_STORE_CTX_cleanup does a proper "free" on the ex_data, we * put a corresponding "new" here. */ if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_X509_STORE_CTX, ctx, &(ctx->ex_data))) { OPENSSL_free(ctx); X509err(X509_F_X509_STORE_CTX_INIT, ERR_R_MALLOC_FAILURE); return 0; } return 1; } /* * Set alternative lookup method: just a STACK of trusted certificates. This * avoids X509_STORE nastiness where it isn't needed. */ void X509_STORE_CTX_trusted_stack(X509_STORE_CTX *ctx, STACK_OF(X509) *sk) { ctx->other_ctx = sk; ctx->get_issuer = get_issuer_sk; } void X509_STORE_CTX_cleanup(X509_STORE_CTX *ctx) { if (ctx->cleanup) ctx->cleanup(ctx); if (ctx->param != NULL) { if (ctx->parent == NULL) X509_VERIFY_PARAM_free(ctx->param); ctx->param = NULL; } X509_policy_tree_free(ctx->tree); ctx->tree = NULL; sk_X509_pop_free(ctx->chain, X509_free); ctx->chain = NULL; CRYPTO_free_ex_data(CRYPTO_EX_INDEX_X509_STORE_CTX, ctx, &(ctx->ex_data)); memset(&ctx->ex_data, 0, sizeof(ctx->ex_data)); } void X509_STORE_CTX_set_depth(X509_STORE_CTX *ctx, int depth) { X509_VERIFY_PARAM_set_depth(ctx->param, depth); } void X509_STORE_CTX_set_flags(X509_STORE_CTX *ctx, unsigned long flags) { X509_VERIFY_PARAM_set_flags(ctx->param, flags); } void X509_STORE_CTX_set_time(X509_STORE_CTX *ctx, unsigned long flags, time_t t) { X509_VERIFY_PARAM_set_time(ctx->param, t); } void X509_STORE_CTX_set_verify_cb(X509_STORE_CTX *ctx, int (*verify_cb) (int, X509_STORE_CTX *)) { ctx->verify_cb = verify_cb; } X509_POLICY_TREE *X509_STORE_CTX_get0_policy_tree(X509_STORE_CTX *ctx) { return ctx->tree; } int X509_STORE_CTX_get_explicit_policy(X509_STORE_CTX *ctx) { return ctx->explicit_policy; } int X509_STORE_CTX_set_default(X509_STORE_CTX *ctx, const char *name) { const X509_VERIFY_PARAM *param; param = X509_VERIFY_PARAM_lookup(name); if (!param) return 0; return X509_VERIFY_PARAM_inherit(ctx->param, param); } X509_VERIFY_PARAM *X509_STORE_CTX_get0_param(X509_STORE_CTX *ctx) { return ctx->param; } void X509_STORE_CTX_set0_param(X509_STORE_CTX *ctx, X509_VERIFY_PARAM *param) { X509_VERIFY_PARAM_free(ctx->param); ctx->param = param; }
./CrossVul/dataset_final_sorted/CWE-119/c/good_1494_0
crossvul-cpp_data_bad_342_10
/* * util.c: utility functions used by OpenSC command line tools. * * Copyright (C) 2011 OpenSC Project developers * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "config.h" #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #ifndef _WIN32 #include <termios.h> #else #include <conio.h> #endif #include <ctype.h> #include "util.h" #include "ui/notify.h" int is_string_valid_atr(const char *atr_str) { unsigned char atr[SC_MAX_ATR_SIZE]; size_t atr_len = sizeof(atr); if (sc_hex_to_bin(atr_str, atr, &atr_len)) return 0; if (atr_len < 2) return 0; if (atr[0] != 0x3B && atr[0] != 0x3F) return 0; return 1; } int util_connect_card_ex(sc_context_t *ctx, sc_card_t **cardp, const char *reader_id, int do_wait, int do_lock, int verbose) { struct sc_reader *reader = NULL, *found = NULL; struct sc_card *card = NULL; int r; sc_notify_init(); if (do_wait) { unsigned int event; if (sc_ctx_get_reader_count(ctx) == 0) { fprintf(stderr, "Waiting for a reader to be attached...\n"); r = sc_wait_for_event(ctx, SC_EVENT_READER_ATTACHED, &found, &event, -1, NULL); if (r < 0) { fprintf(stderr, "Error while waiting for a reader: %s\n", sc_strerror(r)); return 3; } r = sc_ctx_detect_readers(ctx); if (r < 0) { fprintf(stderr, "Error while refreshing readers: %s\n", sc_strerror(r)); return 3; } } fprintf(stderr, "Waiting for a card to be inserted...\n"); r = sc_wait_for_event(ctx, SC_EVENT_CARD_INSERTED, &found, &event, -1, NULL); if (r < 0) { fprintf(stderr, "Error while waiting for a card: %s\n", sc_strerror(r)); return 3; } reader = found; } else if (sc_ctx_get_reader_count(ctx) == 0) { fprintf(stderr, "No smart card readers found.\n"); return 1; } else { if (!reader_id) { unsigned int i; /* Automatically try to skip to a reader with a card if reader not specified */ for (i = 0; i < sc_ctx_get_reader_count(ctx); i++) { reader = sc_ctx_get_reader(ctx, i); if (sc_detect_card_presence(reader) & SC_READER_CARD_PRESENT) { fprintf(stderr, "Using reader with a card: %s\n", reader->name); goto autofound; } } /* If no reader had a card, default to the first reader */ reader = sc_ctx_get_reader(ctx, 0); } else { /* If the reader identifier looks like an ATR, try to find the reader with that card */ if (is_string_valid_atr(reader_id)) { unsigned char atr_buf[SC_MAX_ATR_SIZE]; size_t atr_buf_len = sizeof(atr_buf); unsigned int i; sc_hex_to_bin(reader_id, atr_buf, &atr_buf_len); /* Loop readers, looking for a card with ATR */ for (i = 0; i < sc_ctx_get_reader_count(ctx); i++) { struct sc_reader *rdr = sc_ctx_get_reader(ctx, i); if (!(sc_detect_card_presence(rdr) & SC_READER_CARD_PRESENT)) continue; else if (rdr->atr.len != atr_buf_len) continue; else if (memcmp(rdr->atr.value, atr_buf, rdr->atr.len)) continue; fprintf(stderr, "Matched ATR in reader: %s\n", rdr->name); reader = rdr; goto autofound; } } else { char *endptr = NULL; unsigned int num; errno = 0; num = strtol(reader_id, &endptr, 0); if (!errno && endptr && *endptr == '\0') reader = sc_ctx_get_reader(ctx, num); else reader = sc_ctx_get_reader_by_name(ctx, reader_id); } } autofound: if (!reader) { fprintf(stderr, "Reader \"%s\" not found (%d reader(s) detected)\n", reader_id, sc_ctx_get_reader_count(ctx)); return 1; } if (sc_detect_card_presence(reader) <= 0) { fprintf(stderr, "Card not present.\n"); return 3; } } if (verbose) printf("Connecting to card in reader %s...\n", reader->name); r = sc_connect_card(reader, &card); if (r < 0) { fprintf(stderr, "Failed to connect to card: %s\n", sc_strerror(r)); return 1; } if (verbose) printf("Using card driver %s.\n", card->driver->name); if (do_lock) { r = sc_lock(card); if (r < 0) { fprintf(stderr, "Failed to lock card: %s\n", sc_strerror(r)); sc_disconnect_card(card); return 1; } } *cardp = card; return 0; } int util_connect_card(sc_context_t *ctx, sc_card_t **cardp, const char *reader_id, int do_wait, int verbose) { return util_connect_card_ex(ctx, cardp, reader_id, do_wait, 1, verbose); } void util_print_binary(FILE *f, const u8 *buf, int count) { int i; for (i = 0; i < count; i++) { unsigned char c = buf[i]; const char *format; if (!isprint(c)) format = "\\x%02X"; else format = "%c"; fprintf(f, format, c); } (void) fflush(f); } void util_hex_dump(FILE *f, const u8 *in, int len, const char *sep) { int i; for (i = 0; i < len; i++) { if (sep != NULL && i) fprintf(f, "%s", sep); fprintf(f, "%02X", in[i]); } } void util_hex_dump_asc(FILE *f, const u8 *in, size_t count, int addr) { int lines = 0; while (count) { char ascbuf[17]; size_t i; if (addr >= 0) { fprintf(f, "%08X: ", addr); addr += 16; } for (i = 0; i < count && i < 16; i++) { fprintf(f, "%02X ", *in); if (isprint(*in)) ascbuf[i] = *in; else ascbuf[i] = '.'; in++; } count -= i; ascbuf[i] = 0; for (; i < 16 && lines; i++) fprintf(f, " "); fprintf(f, "%s\n", ascbuf); lines++; } } NORETURN void util_print_usage_and_die(const char *app_name, const struct option options[], const char *option_help[], const char *args) { int i; int header_shown = 0; if (args) printf("Usage: %s [OPTIONS] %s\n", app_name, args); else printf("Usage: %s [OPTIONS]\n", app_name); for (i = 0; options[i].name; i++) { char buf[40]; const char *arg_str; /* Skip "hidden" options */ if (option_help[i] == NULL) continue; if (!header_shown++) printf("Options:\n"); switch (options[i].has_arg) { case 1: arg_str = " <arg>"; break; case 2: arg_str = " [arg]"; break; default: arg_str = ""; break; } if (isascii(options[i].val) && isprint(options[i].val) && !isspace(options[i].val)) sprintf(buf, "-%c, --%s%s", options[i].val, options[i].name, arg_str); else sprintf(buf, " --%s%s", options[i].name, arg_str); /* print the line - wrap if necessary */ if (strlen(buf) > 28) { printf(" %s\n", buf); buf[0] = '\0'; } printf(" %-28s %s\n", buf, option_help[i]); } exit(2); } const char * util_acl_to_str(const sc_acl_entry_t *e) { static char line[80], buf[20]; unsigned int acl; if (e == NULL) return "N/A"; line[0] = 0; while (e != NULL) { acl = e->method; switch (acl) { case SC_AC_UNKNOWN: return "N/A"; case SC_AC_NEVER: return "NEVR"; case SC_AC_NONE: return "NONE"; case SC_AC_CHV: strcpy(buf, "CHV"); if (e->key_ref != SC_AC_KEY_REF_NONE) sprintf(buf + 3, "%d", e->key_ref); break; case SC_AC_TERM: strcpy(buf, "TERM"); break; case SC_AC_PRO: strcpy(buf, "PROT"); break; case SC_AC_AUT: strcpy(buf, "AUTH"); if (e->key_ref != SC_AC_KEY_REF_NONE) sprintf(buf + 4, "%d", e->key_ref); break; case SC_AC_SEN: strcpy(buf, "Sec.Env. "); if (e->key_ref != SC_AC_KEY_REF_NONE) sprintf(buf + 3, "#%d", e->key_ref); break; case SC_AC_SCB: strcpy(buf, "Sec.ControlByte "); if (e->key_ref != SC_AC_KEY_REF_NONE) sprintf(buf + 3, "Ox%X", e->key_ref); break; case SC_AC_IDA: strcpy(buf, "PKCS#15 AuthID "); if (e->key_ref != SC_AC_KEY_REF_NONE) sprintf(buf + 3, "#%d", e->key_ref); break; default: strcpy(buf, "????"); break; } strcat(line, buf); strcat(line, " "); e = e->next; } line[strlen(line)-1] = 0; /* get rid of trailing space */ return line; } NORETURN void util_fatal(const char *fmt, ...) { va_list ap; va_start(ap, fmt); fprintf(stderr, "error: "); vfprintf(stderr, fmt, ap); fprintf(stderr, "\nAborting.\n"); va_end(ap); sc_notify_close(); exit(1); } void util_error(const char *fmt, ...) { va_list ap; va_start(ap, fmt); fprintf(stderr, "error: "); vfprintf(stderr, fmt, ap); fprintf(stderr, "\n"); va_end(ap); } void util_warn(const char *fmt, ...) { va_list ap; va_start(ap, fmt); fprintf(stderr, "warning: "); vfprintf(stderr, fmt, ap); fprintf(stderr, "\n"); va_end(ap); } int util_getpass (char **lineptr, size_t *len, FILE *stream) { #define MAX_PASS_SIZE 128 char *buf; size_t i; int ch = 0; #ifndef _WIN32 struct termios old, new; fflush(stdout); if (tcgetattr (fileno (stdout), &old) != 0) return -1; new = old; new.c_lflag &= ~ECHO; if (tcsetattr (fileno (stdout), TCSAFLUSH, &new) != 0) return -1; #endif buf = calloc(1, MAX_PASS_SIZE); if (!buf) return -1; for (i = 0; i < MAX_PASS_SIZE - 1; i++) { #ifndef _WIN32 ch = getchar(); #else ch = _getch(); #endif if (ch == 0 || ch == 3) break; if (ch == '\n' || ch == '\r') break; buf[i] = (char) ch; } #ifndef _WIN32 tcsetattr (fileno (stdout), TCSAFLUSH, &old); fputs("\n", stdout); #endif if (ch == 0 || ch == 3) { free(buf); return -1; } if (*lineptr && (!len || *len < i+1)) { free(*lineptr); *lineptr = NULL; } if (*lineptr) { memcpy(*lineptr,buf,i+1); memset(buf, 0, MAX_PASS_SIZE); free(buf); } else { *lineptr = buf; if (len) *len = MAX_PASS_SIZE; } return i; } size_t util_get_pin(const char *input, const char **pin) { size_t inputlen = strlen(input); size_t pinlen = 0; if(inputlen > 4 && strncasecmp(input, "env:", 4) == 0) { // Get a PIN from a environment variable *pin = getenv(input + 4); pinlen = *pin ? strlen(*pin) : 0; } else { //Just use the input *pin = input; pinlen = inputlen; } return pinlen; }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_342_10
crossvul-cpp_data_bad_4999_1
/* * Packet matching code. * * Copyright (C) 1999 Paul `Rusty' Russell & Michael J. Neuling * Copyright (C) 2000-2005 Netfilter Core Team <coreteam@netfilter.org> * Copyright (C) 2006-2010 Patrick McHardy <kaber@trash.net> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/cache.h> #include <linux/capability.h> #include <linux/skbuff.h> #include <linux/kmod.h> #include <linux/vmalloc.h> #include <linux/netdevice.h> #include <linux/module.h> #include <linux/icmp.h> #include <net/ip.h> #include <net/compat.h> #include <asm/uaccess.h> #include <linux/mutex.h> #include <linux/proc_fs.h> #include <linux/err.h> #include <linux/cpumask.h> #include <linux/netfilter/x_tables.h> #include <linux/netfilter_ipv4/ip_tables.h> #include <net/netfilter/nf_log.h> #include "../../netfilter/xt_repldata.h" MODULE_LICENSE("GPL"); MODULE_AUTHOR("Netfilter Core Team <coreteam@netfilter.org>"); MODULE_DESCRIPTION("IPv4 packet filter"); /*#define DEBUG_IP_FIREWALL*/ /*#define DEBUG_ALLOW_ALL*/ /* Useful for remote debugging */ /*#define DEBUG_IP_FIREWALL_USER*/ #ifdef DEBUG_IP_FIREWALL #define dprintf(format, args...) pr_info(format , ## args) #else #define dprintf(format, args...) #endif #ifdef DEBUG_IP_FIREWALL_USER #define duprintf(format, args...) pr_info(format , ## args) #else #define duprintf(format, args...) #endif #ifdef CONFIG_NETFILTER_DEBUG #define IP_NF_ASSERT(x) WARN_ON(!(x)) #else #define IP_NF_ASSERT(x) #endif #if 0 /* All the better to debug you with... */ #define static #define inline #endif void *ipt_alloc_initial_table(const struct xt_table *info) { return xt_alloc_initial_table(ipt, IPT); } EXPORT_SYMBOL_GPL(ipt_alloc_initial_table); /* Returns whether matches rule or not. */ /* Performance critical - called for every packet */ static inline bool ip_packet_match(const struct iphdr *ip, const char *indev, const char *outdev, const struct ipt_ip *ipinfo, int isfrag) { unsigned long ret; #define FWINV(bool, invflg) ((bool) ^ !!(ipinfo->invflags & (invflg))) if (FWINV((ip->saddr&ipinfo->smsk.s_addr) != ipinfo->src.s_addr, IPT_INV_SRCIP) || FWINV((ip->daddr&ipinfo->dmsk.s_addr) != ipinfo->dst.s_addr, IPT_INV_DSTIP)) { dprintf("Source or dest mismatch.\n"); dprintf("SRC: %pI4. Mask: %pI4. Target: %pI4.%s\n", &ip->saddr, &ipinfo->smsk.s_addr, &ipinfo->src.s_addr, ipinfo->invflags & IPT_INV_SRCIP ? " (INV)" : ""); dprintf("DST: %pI4 Mask: %pI4 Target: %pI4.%s\n", &ip->daddr, &ipinfo->dmsk.s_addr, &ipinfo->dst.s_addr, ipinfo->invflags & IPT_INV_DSTIP ? " (INV)" : ""); return false; } ret = ifname_compare_aligned(indev, ipinfo->iniface, ipinfo->iniface_mask); if (FWINV(ret != 0, IPT_INV_VIA_IN)) { dprintf("VIA in mismatch (%s vs %s).%s\n", indev, ipinfo->iniface, ipinfo->invflags & IPT_INV_VIA_IN ? " (INV)" : ""); return false; } ret = ifname_compare_aligned(outdev, ipinfo->outiface, ipinfo->outiface_mask); if (FWINV(ret != 0, IPT_INV_VIA_OUT)) { dprintf("VIA out mismatch (%s vs %s).%s\n", outdev, ipinfo->outiface, ipinfo->invflags & IPT_INV_VIA_OUT ? " (INV)" : ""); return false; } /* Check specific protocol */ if (ipinfo->proto && FWINV(ip->protocol != ipinfo->proto, IPT_INV_PROTO)) { dprintf("Packet protocol %hi does not match %hi.%s\n", ip->protocol, ipinfo->proto, ipinfo->invflags & IPT_INV_PROTO ? " (INV)" : ""); return false; } /* If we have a fragment rule but the packet is not a fragment * then we return zero */ if (FWINV((ipinfo->flags&IPT_F_FRAG) && !isfrag, IPT_INV_FRAG)) { dprintf("Fragment rule but not fragment.%s\n", ipinfo->invflags & IPT_INV_FRAG ? " (INV)" : ""); return false; } return true; } static bool ip_checkentry(const struct ipt_ip *ip) { if (ip->flags & ~IPT_F_MASK) { duprintf("Unknown flag bits set: %08X\n", ip->flags & ~IPT_F_MASK); return false; } if (ip->invflags & ~IPT_INV_MASK) { duprintf("Unknown invflag bits set: %08X\n", ip->invflags & ~IPT_INV_MASK); return false; } return true; } static unsigned int ipt_error(struct sk_buff *skb, const struct xt_action_param *par) { net_info_ratelimited("error: `%s'\n", (const char *)par->targinfo); return NF_DROP; } /* Performance critical */ static inline struct ipt_entry * get_entry(const void *base, unsigned int offset) { return (struct ipt_entry *)(base + offset); } /* All zeroes == unconditional rule. */ /* Mildly perf critical (only if packet tracing is on) */ static inline bool unconditional(const struct ipt_ip *ip) { static const struct ipt_ip uncond; return memcmp(ip, &uncond, sizeof(uncond)) == 0; #undef FWINV } /* for const-correctness */ static inline const struct xt_entry_target * ipt_get_target_c(const struct ipt_entry *e) { return ipt_get_target((struct ipt_entry *)e); } #if IS_ENABLED(CONFIG_NETFILTER_XT_TARGET_TRACE) static const char *const hooknames[] = { [NF_INET_PRE_ROUTING] = "PREROUTING", [NF_INET_LOCAL_IN] = "INPUT", [NF_INET_FORWARD] = "FORWARD", [NF_INET_LOCAL_OUT] = "OUTPUT", [NF_INET_POST_ROUTING] = "POSTROUTING", }; enum nf_ip_trace_comments { NF_IP_TRACE_COMMENT_RULE, NF_IP_TRACE_COMMENT_RETURN, NF_IP_TRACE_COMMENT_POLICY, }; static const char *const comments[] = { [NF_IP_TRACE_COMMENT_RULE] = "rule", [NF_IP_TRACE_COMMENT_RETURN] = "return", [NF_IP_TRACE_COMMENT_POLICY] = "policy", }; static struct nf_loginfo trace_loginfo = { .type = NF_LOG_TYPE_LOG, .u = { .log = { .level = 4, .logflags = NF_LOG_MASK, }, }, }; /* Mildly perf critical (only if packet tracing is on) */ static inline int get_chainname_rulenum(const struct ipt_entry *s, const struct ipt_entry *e, const char *hookname, const char **chainname, const char **comment, unsigned int *rulenum) { const struct xt_standard_target *t = (void *)ipt_get_target_c(s); if (strcmp(t->target.u.kernel.target->name, XT_ERROR_TARGET) == 0) { /* Head of user chain: ERROR target with chainname */ *chainname = t->target.data; (*rulenum) = 0; } else if (s == e) { (*rulenum)++; if (s->target_offset == sizeof(struct ipt_entry) && strcmp(t->target.u.kernel.target->name, XT_STANDARD_TARGET) == 0 && t->verdict < 0 && unconditional(&s->ip)) { /* Tail of chains: STANDARD target (return/policy) */ *comment = *chainname == hookname ? comments[NF_IP_TRACE_COMMENT_POLICY] : comments[NF_IP_TRACE_COMMENT_RETURN]; } return 1; } else (*rulenum)++; return 0; } static void trace_packet(struct net *net, const struct sk_buff *skb, unsigned int hook, const struct net_device *in, const struct net_device *out, const char *tablename, const struct xt_table_info *private, const struct ipt_entry *e) { const struct ipt_entry *root; const char *hookname, *chainname, *comment; const struct ipt_entry *iter; unsigned int rulenum = 0; root = get_entry(private->entries, private->hook_entry[hook]); hookname = chainname = hooknames[hook]; comment = comments[NF_IP_TRACE_COMMENT_RULE]; xt_entry_foreach(iter, root, private->size - private->hook_entry[hook]) if (get_chainname_rulenum(iter, e, hookname, &chainname, &comment, &rulenum) != 0) break; nf_log_trace(net, AF_INET, hook, skb, in, out, &trace_loginfo, "TRACE: %s:%s:%s:%u ", tablename, chainname, comment, rulenum); } #endif static inline struct ipt_entry *ipt_next_entry(const struct ipt_entry *entry) { return (void *)entry + entry->next_offset; } /* Returns one of the generic firewall policies, like NF_ACCEPT. */ unsigned int ipt_do_table(struct sk_buff *skb, const struct nf_hook_state *state, struct xt_table *table) { unsigned int hook = state->hook; static const char nulldevname[IFNAMSIZ] __attribute__((aligned(sizeof(long)))); const struct iphdr *ip; /* Initializing verdict to NF_DROP keeps gcc happy. */ unsigned int verdict = NF_DROP; const char *indev, *outdev; const void *table_base; struct ipt_entry *e, **jumpstack; unsigned int stackidx, cpu; const struct xt_table_info *private; struct xt_action_param acpar; unsigned int addend; /* Initialization */ stackidx = 0; ip = ip_hdr(skb); indev = state->in ? state->in->name : nulldevname; outdev = state->out ? state->out->name : nulldevname; /* We handle fragments by dealing with the first fragment as * if it was a normal packet. All other fragments are treated * normally, except that they will NEVER match rules that ask * things we don't know, ie. tcp syn flag or ports). If the * rule is also a fragment-specific rule, non-fragments won't * match it. */ acpar.fragoff = ntohs(ip->frag_off) & IP_OFFSET; acpar.thoff = ip_hdrlen(skb); acpar.hotdrop = false; acpar.net = state->net; acpar.in = state->in; acpar.out = state->out; acpar.family = NFPROTO_IPV4; acpar.hooknum = hook; IP_NF_ASSERT(table->valid_hooks & (1 << hook)); local_bh_disable(); addend = xt_write_recseq_begin(); private = table->private; cpu = smp_processor_id(); /* * Ensure we load private-> members after we've fetched the base * pointer. */ smp_read_barrier_depends(); table_base = private->entries; jumpstack = (struct ipt_entry **)private->jumpstack[cpu]; /* Switch to alternate jumpstack if we're being invoked via TEE. * TEE issues XT_CONTINUE verdict on original skb so we must not * clobber the jumpstack. * * For recursion via REJECT or SYNPROXY the stack will be clobbered * but it is no problem since absolute verdict is issued by these. */ if (static_key_false(&xt_tee_enabled)) jumpstack += private->stacksize * __this_cpu_read(nf_skb_duplicated); e = get_entry(table_base, private->hook_entry[hook]); pr_debug("Entering %s(hook %u), UF %p\n", table->name, hook, get_entry(table_base, private->underflow[hook])); do { const struct xt_entry_target *t; const struct xt_entry_match *ematch; struct xt_counters *counter; IP_NF_ASSERT(e); if (!ip_packet_match(ip, indev, outdev, &e->ip, acpar.fragoff)) { no_match: e = ipt_next_entry(e); continue; } xt_ematch_foreach(ematch, e) { acpar.match = ematch->u.kernel.match; acpar.matchinfo = ematch->data; if (!acpar.match->match(skb, &acpar)) goto no_match; } counter = xt_get_this_cpu_counter(&e->counters); ADD_COUNTER(*counter, skb->len, 1); t = ipt_get_target(e); IP_NF_ASSERT(t->u.kernel.target); #if IS_ENABLED(CONFIG_NETFILTER_XT_TARGET_TRACE) /* The packet is traced: log it */ if (unlikely(skb->nf_trace)) trace_packet(state->net, skb, hook, state->in, state->out, table->name, private, e); #endif /* Standard target? */ if (!t->u.kernel.target->target) { int v; v = ((struct xt_standard_target *)t)->verdict; if (v < 0) { /* Pop from stack? */ if (v != XT_RETURN) { verdict = (unsigned int)(-v) - 1; break; } if (stackidx == 0) { e = get_entry(table_base, private->underflow[hook]); pr_debug("Underflow (this is normal) " "to %p\n", e); } else { e = jumpstack[--stackidx]; pr_debug("Pulled %p out from pos %u\n", e, stackidx); e = ipt_next_entry(e); } continue; } if (table_base + v != ipt_next_entry(e) && !(e->ip.flags & IPT_F_GOTO)) { jumpstack[stackidx++] = e; pr_debug("Pushed %p into pos %u\n", e, stackidx - 1); } e = get_entry(table_base, v); continue; } acpar.target = t->u.kernel.target; acpar.targinfo = t->data; verdict = t->u.kernel.target->target(skb, &acpar); /* Target might have changed stuff. */ ip = ip_hdr(skb); if (verdict == XT_CONTINUE) e = ipt_next_entry(e); else /* Verdict */ break; } while (!acpar.hotdrop); pr_debug("Exiting %s; sp at %u\n", __func__, stackidx); xt_write_recseq_end(addend); local_bh_enable(); #ifdef DEBUG_ALLOW_ALL return NF_ACCEPT; #else if (acpar.hotdrop) return NF_DROP; else return verdict; #endif } /* Figures out from what hook each rule can be called: returns 0 if there are loops. Puts hook bitmask in comefrom. */ static int mark_source_chains(const struct xt_table_info *newinfo, unsigned int valid_hooks, void *entry0) { unsigned int hook; /* No recursion; use packet counter to save back ptrs (reset to 0 as we leave), and comefrom to save source hook bitmask */ for (hook = 0; hook < NF_INET_NUMHOOKS; hook++) { unsigned int pos = newinfo->hook_entry[hook]; struct ipt_entry *e = (struct ipt_entry *)(entry0 + pos); if (!(valid_hooks & (1 << hook))) continue; /* Set initial back pointer. */ e->counters.pcnt = pos; for (;;) { const struct xt_standard_target *t = (void *)ipt_get_target_c(e); int visited = e->comefrom & (1 << hook); if (e->comefrom & (1 << NF_INET_NUMHOOKS)) { pr_err("iptables: loop hook %u pos %u %08X.\n", hook, pos, e->comefrom); return 0; } e->comefrom |= ((1 << hook) | (1 << NF_INET_NUMHOOKS)); /* Unconditional return/END. */ if ((e->target_offset == sizeof(struct ipt_entry) && (strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0) && t->verdict < 0 && unconditional(&e->ip)) || visited) { unsigned int oldpos, size; if ((strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0) && t->verdict < -NF_MAX_VERDICT - 1) { duprintf("mark_source_chains: bad " "negative verdict (%i)\n", t->verdict); return 0; } /* Return: backtrack through the last big jump. */ do { e->comefrom ^= (1<<NF_INET_NUMHOOKS); #ifdef DEBUG_IP_FIREWALL_USER if (e->comefrom & (1 << NF_INET_NUMHOOKS)) { duprintf("Back unset " "on hook %u " "rule %u\n", hook, pos); } #endif oldpos = pos; pos = e->counters.pcnt; e->counters.pcnt = 0; /* We're at the start. */ if (pos == oldpos) goto next; e = (struct ipt_entry *) (entry0 + pos); } while (oldpos == pos + e->next_offset); /* Move along one */ size = e->next_offset; e = (struct ipt_entry *) (entry0 + pos + size); e->counters.pcnt = pos; pos += size; } else { int newpos = t->verdict; if (strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0 && newpos >= 0) { if (newpos > newinfo->size - sizeof(struct ipt_entry)) { duprintf("mark_source_chains: " "bad verdict (%i)\n", newpos); return 0; } /* This a jump; chase it. */ duprintf("Jump rule %u -> %u\n", pos, newpos); } else { /* ... this is a fallthru */ newpos = pos + e->next_offset; } e = (struct ipt_entry *) (entry0 + newpos); e->counters.pcnt = pos; pos = newpos; } } next: duprintf("Finished chain %u\n", hook); } return 1; } static void cleanup_match(struct xt_entry_match *m, struct net *net) { struct xt_mtdtor_param par; par.net = net; par.match = m->u.kernel.match; par.matchinfo = m->data; par.family = NFPROTO_IPV4; if (par.match->destroy != NULL) par.match->destroy(&par); module_put(par.match->me); } static int check_entry(const struct ipt_entry *e) { const struct xt_entry_target *t; if (!ip_checkentry(&e->ip)) return -EINVAL; if (e->target_offset + sizeof(struct xt_entry_target) > e->next_offset) return -EINVAL; t = ipt_get_target_c(e); if (e->target_offset + t->u.target_size > e->next_offset) return -EINVAL; return 0; } static int check_match(struct xt_entry_match *m, struct xt_mtchk_param *par) { const struct ipt_ip *ip = par->entryinfo; int ret; par->match = m->u.kernel.match; par->matchinfo = m->data; ret = xt_check_match(par, m->u.match_size - sizeof(*m), ip->proto, ip->invflags & IPT_INV_PROTO); if (ret < 0) { duprintf("check failed for `%s'.\n", par->match->name); return ret; } return 0; } static int find_check_match(struct xt_entry_match *m, struct xt_mtchk_param *par) { struct xt_match *match; int ret; match = xt_request_find_match(NFPROTO_IPV4, m->u.user.name, m->u.user.revision); if (IS_ERR(match)) { duprintf("find_check_match: `%s' not found\n", m->u.user.name); return PTR_ERR(match); } m->u.kernel.match = match; ret = check_match(m, par); if (ret) goto err; return 0; err: module_put(m->u.kernel.match->me); return ret; } static int check_target(struct ipt_entry *e, struct net *net, const char *name) { struct xt_entry_target *t = ipt_get_target(e); struct xt_tgchk_param par = { .net = net, .table = name, .entryinfo = e, .target = t->u.kernel.target, .targinfo = t->data, .hook_mask = e->comefrom, .family = NFPROTO_IPV4, }; int ret; ret = xt_check_target(&par, t->u.target_size - sizeof(*t), e->ip.proto, e->ip.invflags & IPT_INV_PROTO); if (ret < 0) { duprintf("check failed for `%s'.\n", t->u.kernel.target->name); return ret; } return 0; } static int find_check_entry(struct ipt_entry *e, struct net *net, const char *name, unsigned int size) { struct xt_entry_target *t; struct xt_target *target; int ret; unsigned int j; struct xt_mtchk_param mtpar; struct xt_entry_match *ematch; e->counters.pcnt = xt_percpu_counter_alloc(); if (IS_ERR_VALUE(e->counters.pcnt)) return -ENOMEM; j = 0; mtpar.net = net; mtpar.table = name; mtpar.entryinfo = &e->ip; mtpar.hook_mask = e->comefrom; mtpar.family = NFPROTO_IPV4; xt_ematch_foreach(ematch, e) { ret = find_check_match(ematch, &mtpar); if (ret != 0) goto cleanup_matches; ++j; } t = ipt_get_target(e); target = xt_request_find_target(NFPROTO_IPV4, t->u.user.name, t->u.user.revision); if (IS_ERR(target)) { duprintf("find_check_entry: `%s' not found\n", t->u.user.name); ret = PTR_ERR(target); goto cleanup_matches; } t->u.kernel.target = target; ret = check_target(e, net, name); if (ret) goto err; return 0; err: module_put(t->u.kernel.target->me); cleanup_matches: xt_ematch_foreach(ematch, e) { if (j-- == 0) break; cleanup_match(ematch, net); } xt_percpu_counter_free(e->counters.pcnt); return ret; } static bool check_underflow(const struct ipt_entry *e) { const struct xt_entry_target *t; unsigned int verdict; if (!unconditional(&e->ip)) return false; t = ipt_get_target_c(e); if (strcmp(t->u.user.name, XT_STANDARD_TARGET) != 0) return false; verdict = ((struct xt_standard_target *)t)->verdict; verdict = -verdict - 1; return verdict == NF_DROP || verdict == NF_ACCEPT; } static int check_entry_size_and_hooks(struct ipt_entry *e, struct xt_table_info *newinfo, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, unsigned int valid_hooks) { unsigned int h; int err; if ((unsigned long)e % __alignof__(struct ipt_entry) != 0 || (unsigned char *)e + sizeof(struct ipt_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf("Bad offset %p\n", e); return -EINVAL; } if (e->next_offset < sizeof(struct ipt_entry) + sizeof(struct xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } err = check_entry(e); if (err) return err; /* Check hooks & underflows */ for (h = 0; h < NF_INET_NUMHOOKS; h++) { if (!(valid_hooks & (1 << h))) continue; if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) { if (!check_underflow(e)) { pr_err("Underflows must be unconditional and " "use the STANDARD target with " "ACCEPT/DROP\n"); return -EINVAL; } newinfo->underflow[h] = underflows[h]; } } /* Clear counters and comefrom */ e->counters = ((struct xt_counters) { 0, 0 }); e->comefrom = 0; return 0; } static void cleanup_entry(struct ipt_entry *e, struct net *net) { struct xt_tgdtor_param par; struct xt_entry_target *t; struct xt_entry_match *ematch; /* Cleanup all matches */ xt_ematch_foreach(ematch, e) cleanup_match(ematch, net); t = ipt_get_target(e); par.net = net; par.target = t->u.kernel.target; par.targinfo = t->data; par.family = NFPROTO_IPV4; if (par.target->destroy != NULL) par.target->destroy(&par); module_put(par.target->me); xt_percpu_counter_free(e->counters.pcnt); } /* Checks and translates the user-supplied table segment (held in newinfo) */ static int translate_table(struct net *net, struct xt_table_info *newinfo, void *entry0, const struct ipt_replace *repl) { struct ipt_entry *iter; unsigned int i; int ret = 0; newinfo->size = repl->size; newinfo->number = repl->num_entries; /* Init all hooks to impossible value. */ for (i = 0; i < NF_INET_NUMHOOKS; i++) { newinfo->hook_entry[i] = 0xFFFFFFFF; newinfo->underflow[i] = 0xFFFFFFFF; } duprintf("translate_table: size %u\n", newinfo->size); i = 0; /* Walk through entries, checking offsets. */ xt_entry_foreach(iter, entry0, newinfo->size) { ret = check_entry_size_and_hooks(iter, newinfo, entry0, entry0 + repl->size, repl->hook_entry, repl->underflow, repl->valid_hooks); if (ret != 0) return ret; ++i; if (strcmp(ipt_get_target(iter)->u.user.name, XT_ERROR_TARGET) == 0) ++newinfo->stacksize; } if (i != repl->num_entries) { duprintf("translate_table: %u not %u entries\n", i, repl->num_entries); return -EINVAL; } /* Check hooks all assigned */ for (i = 0; i < NF_INET_NUMHOOKS; i++) { /* Only hooks which are valid */ if (!(repl->valid_hooks & (1 << i))) continue; if (newinfo->hook_entry[i] == 0xFFFFFFFF) { duprintf("Invalid hook entry %u %u\n", i, repl->hook_entry[i]); return -EINVAL; } if (newinfo->underflow[i] == 0xFFFFFFFF) { duprintf("Invalid underflow %u %u\n", i, repl->underflow[i]); return -EINVAL; } } if (!mark_source_chains(newinfo, repl->valid_hooks, entry0)) return -ELOOP; /* Finally, each sanity check must pass */ i = 0; xt_entry_foreach(iter, entry0, newinfo->size) { ret = find_check_entry(iter, net, repl->name, repl->size); if (ret != 0) break; ++i; } if (ret != 0) { xt_entry_foreach(iter, entry0, newinfo->size) { if (i-- == 0) break; cleanup_entry(iter, net); } return ret; } return ret; } static void get_counters(const struct xt_table_info *t, struct xt_counters counters[]) { struct ipt_entry *iter; unsigned int cpu; unsigned int i; for_each_possible_cpu(cpu) { seqcount_t *s = &per_cpu(xt_recseq, cpu); i = 0; xt_entry_foreach(iter, t->entries, t->size) { struct xt_counters *tmp; u64 bcnt, pcnt; unsigned int start; tmp = xt_get_per_cpu_counter(&iter->counters, cpu); do { start = read_seqcount_begin(s); bcnt = tmp->bcnt; pcnt = tmp->pcnt; } while (read_seqcount_retry(s, start)); ADD_COUNTER(counters[i], bcnt, pcnt); ++i; /* macro does multi eval of i */ } } } static struct xt_counters *alloc_counters(const struct xt_table *table) { unsigned int countersize; struct xt_counters *counters; const struct xt_table_info *private = table->private; /* We need atomic snapshot of counters: rest doesn't change (other than comefrom, which userspace doesn't care about). */ countersize = sizeof(struct xt_counters) * private->number; counters = vzalloc(countersize); if (counters == NULL) return ERR_PTR(-ENOMEM); get_counters(private, counters); return counters; } static int copy_entries_to_user(unsigned int total_size, const struct xt_table *table, void __user *userptr) { unsigned int off, num; const struct ipt_entry *e; struct xt_counters *counters; const struct xt_table_info *private = table->private; int ret = 0; const void *loc_cpu_entry; counters = alloc_counters(table); if (IS_ERR(counters)) return PTR_ERR(counters); loc_cpu_entry = private->entries; if (copy_to_user(userptr, loc_cpu_entry, total_size) != 0) { ret = -EFAULT; goto free_counters; } /* FIXME: use iterator macros --RR */ /* ... then go back and fix counters and names */ for (off = 0, num = 0; off < total_size; off += e->next_offset, num++){ unsigned int i; const struct xt_entry_match *m; const struct xt_entry_target *t; e = (struct ipt_entry *)(loc_cpu_entry + off); if (copy_to_user(userptr + off + offsetof(struct ipt_entry, counters), &counters[num], sizeof(counters[num])) != 0) { ret = -EFAULT; goto free_counters; } for (i = sizeof(struct ipt_entry); i < e->target_offset; i += m->u.match_size) { m = (void *)e + i; if (copy_to_user(userptr + off + i + offsetof(struct xt_entry_match, u.user.name), m->u.kernel.match->name, strlen(m->u.kernel.match->name)+1) != 0) { ret = -EFAULT; goto free_counters; } } t = ipt_get_target_c(e); if (copy_to_user(userptr + off + e->target_offset + offsetof(struct xt_entry_target, u.user.name), t->u.kernel.target->name, strlen(t->u.kernel.target->name)+1) != 0) { ret = -EFAULT; goto free_counters; } } free_counters: vfree(counters); return ret; } #ifdef CONFIG_COMPAT static void compat_standard_from_user(void *dst, const void *src) { int v = *(compat_int_t *)src; if (v > 0) v += xt_compat_calc_jump(AF_INET, v); memcpy(dst, &v, sizeof(v)); } static int compat_standard_to_user(void __user *dst, const void *src) { compat_int_t cv = *(int *)src; if (cv > 0) cv -= xt_compat_calc_jump(AF_INET, cv); return copy_to_user(dst, &cv, sizeof(cv)) ? -EFAULT : 0; } static int compat_calc_entry(const struct ipt_entry *e, const struct xt_table_info *info, const void *base, struct xt_table_info *newinfo) { const struct xt_entry_match *ematch; const struct xt_entry_target *t; unsigned int entry_offset; int off, i, ret; off = sizeof(struct ipt_entry) - sizeof(struct compat_ipt_entry); entry_offset = (void *)e - base; xt_ematch_foreach(ematch, e) off += xt_compat_match_offset(ematch->u.kernel.match); t = ipt_get_target_c(e); off += xt_compat_target_offset(t->u.kernel.target); newinfo->size -= off; ret = xt_compat_add_offset(AF_INET, entry_offset, off); if (ret) return ret; for (i = 0; i < NF_INET_NUMHOOKS; i++) { if (info->hook_entry[i] && (e < (struct ipt_entry *)(base + info->hook_entry[i]))) newinfo->hook_entry[i] -= off; if (info->underflow[i] && (e < (struct ipt_entry *)(base + info->underflow[i]))) newinfo->underflow[i] -= off; } return 0; } static int compat_table_info(const struct xt_table_info *info, struct xt_table_info *newinfo) { struct ipt_entry *iter; const void *loc_cpu_entry; int ret; if (!newinfo || !info) return -EINVAL; /* we dont care about newinfo->entries */ memcpy(newinfo, info, offsetof(struct xt_table_info, entries)); newinfo->initial_entries = 0; loc_cpu_entry = info->entries; xt_compat_init_offsets(AF_INET, info->number); xt_entry_foreach(iter, loc_cpu_entry, info->size) { ret = compat_calc_entry(iter, info, loc_cpu_entry, newinfo); if (ret != 0) return ret; } return 0; } #endif static int get_info(struct net *net, void __user *user, const int *len, int compat) { char name[XT_TABLE_MAXNAMELEN]; struct xt_table *t; int ret; if (*len != sizeof(struct ipt_getinfo)) { duprintf("length %u != %zu\n", *len, sizeof(struct ipt_getinfo)); return -EINVAL; } if (copy_from_user(name, user, sizeof(name)) != 0) return -EFAULT; name[XT_TABLE_MAXNAMELEN-1] = '\0'; #ifdef CONFIG_COMPAT if (compat) xt_compat_lock(AF_INET); #endif t = try_then_request_module(xt_find_table_lock(net, AF_INET, name), "iptable_%s", name); if (!IS_ERR_OR_NULL(t)) { struct ipt_getinfo info; const struct xt_table_info *private = t->private; #ifdef CONFIG_COMPAT struct xt_table_info tmp; if (compat) { ret = compat_table_info(private, &tmp); xt_compat_flush_offsets(AF_INET); private = &tmp; } #endif memset(&info, 0, sizeof(info)); info.valid_hooks = t->valid_hooks; memcpy(info.hook_entry, private->hook_entry, sizeof(info.hook_entry)); memcpy(info.underflow, private->underflow, sizeof(info.underflow)); info.num_entries = private->number; info.size = private->size; strcpy(info.name, name); if (copy_to_user(user, &info, *len) != 0) ret = -EFAULT; else ret = 0; xt_table_unlock(t); module_put(t->me); } else ret = t ? PTR_ERR(t) : -ENOENT; #ifdef CONFIG_COMPAT if (compat) xt_compat_unlock(AF_INET); #endif return ret; } static int get_entries(struct net *net, struct ipt_get_entries __user *uptr, const int *len) { int ret; struct ipt_get_entries get; struct xt_table *t; if (*len < sizeof(get)) { duprintf("get_entries: %u < %zu\n", *len, sizeof(get)); return -EINVAL; } if (copy_from_user(&get, uptr, sizeof(get)) != 0) return -EFAULT; if (*len != sizeof(struct ipt_get_entries) + get.size) { duprintf("get_entries: %u != %zu\n", *len, sizeof(get) + get.size); return -EINVAL; } t = xt_find_table_lock(net, AF_INET, get.name); if (!IS_ERR_OR_NULL(t)) { const struct xt_table_info *private = t->private; duprintf("t->private->number = %u\n", private->number); if (get.size == private->size) ret = copy_entries_to_user(private->size, t, uptr->entrytable); else { duprintf("get_entries: I've got %u not %u!\n", private->size, get.size); ret = -EAGAIN; } module_put(t->me); xt_table_unlock(t); } else ret = t ? PTR_ERR(t) : -ENOENT; return ret; } static int __do_replace(struct net *net, const char *name, unsigned int valid_hooks, struct xt_table_info *newinfo, unsigned int num_counters, void __user *counters_ptr) { int ret; struct xt_table *t; struct xt_table_info *oldinfo; struct xt_counters *counters; struct ipt_entry *iter; ret = 0; counters = vzalloc(num_counters * sizeof(struct xt_counters)); if (!counters) { ret = -ENOMEM; goto out; } t = try_then_request_module(xt_find_table_lock(net, AF_INET, name), "iptable_%s", name); if (IS_ERR_OR_NULL(t)) { ret = t ? PTR_ERR(t) : -ENOENT; goto free_newinfo_counters_untrans; } /* You lied! */ if (valid_hooks != t->valid_hooks) { duprintf("Valid hook crap: %08X vs %08X\n", valid_hooks, t->valid_hooks); ret = -EINVAL; goto put_module; } oldinfo = xt_replace_table(t, num_counters, newinfo, &ret); if (!oldinfo) goto put_module; /* Update module usage count based on number of rules */ duprintf("do_replace: oldnum=%u, initnum=%u, newnum=%u\n", oldinfo->number, oldinfo->initial_entries, newinfo->number); if ((oldinfo->number > oldinfo->initial_entries) || (newinfo->number <= oldinfo->initial_entries)) module_put(t->me); if ((oldinfo->number > oldinfo->initial_entries) && (newinfo->number <= oldinfo->initial_entries)) module_put(t->me); /* Get the old counters, and synchronize with replace */ get_counters(oldinfo, counters); /* Decrease module usage counts and free resource */ xt_entry_foreach(iter, oldinfo->entries, oldinfo->size) cleanup_entry(iter, net); xt_free_table_info(oldinfo); if (copy_to_user(counters_ptr, counters, sizeof(struct xt_counters) * num_counters) != 0) { /* Silent error, can't fail, new table is already in place */ net_warn_ratelimited("iptables: counters copy to user failed while replacing table\n"); } vfree(counters); xt_table_unlock(t); return ret; put_module: module_put(t->me); xt_table_unlock(t); free_newinfo_counters_untrans: vfree(counters); out: return ret; } static int do_replace(struct net *net, const void __user *user, unsigned int len) { int ret; struct ipt_replace tmp; struct xt_table_info *newinfo; void *loc_cpu_entry; struct ipt_entry *iter; if (copy_from_user(&tmp, user, sizeof(tmp)) != 0) return -EFAULT; /* overflow check */ if (tmp.num_counters >= INT_MAX / sizeof(struct xt_counters)) return -ENOMEM; if (tmp.num_counters == 0) return -EINVAL; tmp.name[sizeof(tmp.name)-1] = 0; newinfo = xt_alloc_table_info(tmp.size); if (!newinfo) return -ENOMEM; loc_cpu_entry = newinfo->entries; if (copy_from_user(loc_cpu_entry, user + sizeof(tmp), tmp.size) != 0) { ret = -EFAULT; goto free_newinfo; } ret = translate_table(net, newinfo, loc_cpu_entry, &tmp); if (ret != 0) goto free_newinfo; duprintf("Translated table\n"); ret = __do_replace(net, tmp.name, tmp.valid_hooks, newinfo, tmp.num_counters, tmp.counters); if (ret) goto free_newinfo_untrans; return 0; free_newinfo_untrans: xt_entry_foreach(iter, loc_cpu_entry, newinfo->size) cleanup_entry(iter, net); free_newinfo: xt_free_table_info(newinfo); return ret; } static int do_add_counters(struct net *net, const void __user *user, unsigned int len, int compat) { unsigned int i; struct xt_counters_info tmp; struct xt_counters *paddc; unsigned int num_counters; const char *name; int size; void *ptmp; struct xt_table *t; const struct xt_table_info *private; int ret = 0; struct ipt_entry *iter; unsigned int addend; #ifdef CONFIG_COMPAT struct compat_xt_counters_info compat_tmp; if (compat) { ptmp = &compat_tmp; size = sizeof(struct compat_xt_counters_info); } else #endif { ptmp = &tmp; size = sizeof(struct xt_counters_info); } if (copy_from_user(ptmp, user, size) != 0) return -EFAULT; #ifdef CONFIG_COMPAT if (compat) { num_counters = compat_tmp.num_counters; name = compat_tmp.name; } else #endif { num_counters = tmp.num_counters; name = tmp.name; } if (len != size + num_counters * sizeof(struct xt_counters)) return -EINVAL; paddc = vmalloc(len - size); if (!paddc) return -ENOMEM; if (copy_from_user(paddc, user + size, len - size) != 0) { ret = -EFAULT; goto free; } t = xt_find_table_lock(net, AF_INET, name); if (IS_ERR_OR_NULL(t)) { ret = t ? PTR_ERR(t) : -ENOENT; goto free; } local_bh_disable(); private = t->private; if (private->number != num_counters) { ret = -EINVAL; goto unlock_up_free; } i = 0; addend = xt_write_recseq_begin(); xt_entry_foreach(iter, private->entries, private->size) { struct xt_counters *tmp; tmp = xt_get_this_cpu_counter(&iter->counters); ADD_COUNTER(*tmp, paddc[i].bcnt, paddc[i].pcnt); ++i; } xt_write_recseq_end(addend); unlock_up_free: local_bh_enable(); xt_table_unlock(t); module_put(t->me); free: vfree(paddc); return ret; } #ifdef CONFIG_COMPAT struct compat_ipt_replace { char name[XT_TABLE_MAXNAMELEN]; u32 valid_hooks; u32 num_entries; u32 size; u32 hook_entry[NF_INET_NUMHOOKS]; u32 underflow[NF_INET_NUMHOOKS]; u32 num_counters; compat_uptr_t counters; /* struct xt_counters * */ struct compat_ipt_entry entries[0]; }; static int compat_copy_entry_to_user(struct ipt_entry *e, void __user **dstptr, unsigned int *size, struct xt_counters *counters, unsigned int i) { struct xt_entry_target *t; struct compat_ipt_entry __user *ce; u_int16_t target_offset, next_offset; compat_uint_t origsize; const struct xt_entry_match *ematch; int ret = 0; origsize = *size; ce = (struct compat_ipt_entry __user *)*dstptr; if (copy_to_user(ce, e, sizeof(struct ipt_entry)) != 0 || copy_to_user(&ce->counters, &counters[i], sizeof(counters[i])) != 0) return -EFAULT; *dstptr += sizeof(struct compat_ipt_entry); *size -= sizeof(struct ipt_entry) - sizeof(struct compat_ipt_entry); xt_ematch_foreach(ematch, e) { ret = xt_compat_match_to_user(ematch, dstptr, size); if (ret != 0) return ret; } target_offset = e->target_offset - (origsize - *size); t = ipt_get_target(e); ret = xt_compat_target_to_user(t, dstptr, size); if (ret) return ret; next_offset = e->next_offset - (origsize - *size); if (put_user(target_offset, &ce->target_offset) != 0 || put_user(next_offset, &ce->next_offset) != 0) return -EFAULT; return 0; } static int compat_find_calc_match(struct xt_entry_match *m, const char *name, const struct ipt_ip *ip, int *size) { struct xt_match *match; match = xt_request_find_match(NFPROTO_IPV4, m->u.user.name, m->u.user.revision); if (IS_ERR(match)) { duprintf("compat_check_calc_match: `%s' not found\n", m->u.user.name); return PTR_ERR(match); } m->u.kernel.match = match; *size += xt_compat_match_offset(match); return 0; } static void compat_release_entry(struct compat_ipt_entry *e) { struct xt_entry_target *t; struct xt_entry_match *ematch; /* Cleanup all matches */ xt_ematch_foreach(ematch, e) module_put(ematch->u.kernel.match->me); t = compat_ipt_get_target(e); module_put(t->u.kernel.target->me); } static int check_compat_entry_size_and_hooks(struct compat_ipt_entry *e, struct xt_table_info *newinfo, unsigned int *size, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, const char *name) { struct xt_entry_match *ematch; struct xt_entry_target *t; struct xt_target *target; unsigned int entry_offset; unsigned int j; int ret, off, h; duprintf("check_compat_entry_size_and_hooks %p\n", e); if ((unsigned long)e % __alignof__(struct compat_ipt_entry) != 0 || (unsigned char *)e + sizeof(struct compat_ipt_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf("Bad offset %p, limit = %p\n", e, limit); return -EINVAL; } if (e->next_offset < sizeof(struct compat_ipt_entry) + sizeof(struct compat_xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } /* For purposes of check_entry casting the compat entry is fine */ ret = check_entry((struct ipt_entry *)e); if (ret) return ret; off = sizeof(struct ipt_entry) - sizeof(struct compat_ipt_entry); entry_offset = (void *)e - (void *)base; j = 0; xt_ematch_foreach(ematch, e) { ret = compat_find_calc_match(ematch, name, &e->ip, &off); if (ret != 0) goto release_matches; ++j; } t = compat_ipt_get_target(e); target = xt_request_find_target(NFPROTO_IPV4, t->u.user.name, t->u.user.revision); if (IS_ERR(target)) { duprintf("check_compat_entry_size_and_hooks: `%s' not found\n", t->u.user.name); ret = PTR_ERR(target); goto release_matches; } t->u.kernel.target = target; off += xt_compat_target_offset(target); *size += off; ret = xt_compat_add_offset(AF_INET, entry_offset, off); if (ret) goto out; /* Check hooks & underflows */ for (h = 0; h < NF_INET_NUMHOOKS; h++) { if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) newinfo->underflow[h] = underflows[h]; } /* Clear counters and comefrom */ memset(&e->counters, 0, sizeof(e->counters)); e->comefrom = 0; return 0; out: module_put(t->u.kernel.target->me); release_matches: xt_ematch_foreach(ematch, e) { if (j-- == 0) break; module_put(ematch->u.kernel.match->me); } return ret; } static int compat_copy_entry_from_user(struct compat_ipt_entry *e, void **dstptr, unsigned int *size, const char *name, struct xt_table_info *newinfo, unsigned char *base) { struct xt_entry_target *t; struct xt_target *target; struct ipt_entry *de; unsigned int origsize; int ret, h; struct xt_entry_match *ematch; ret = 0; origsize = *size; de = (struct ipt_entry *)*dstptr; memcpy(de, e, sizeof(struct ipt_entry)); memcpy(&de->counters, &e->counters, sizeof(e->counters)); *dstptr += sizeof(struct ipt_entry); *size += sizeof(struct ipt_entry) - sizeof(struct compat_ipt_entry); xt_ematch_foreach(ematch, e) { ret = xt_compat_match_from_user(ematch, dstptr, size); if (ret != 0) return ret; } de->target_offset = e->target_offset - (origsize - *size); t = compat_ipt_get_target(e); target = t->u.kernel.target; xt_compat_target_from_user(t, dstptr, size); de->next_offset = e->next_offset - (origsize - *size); for (h = 0; h < NF_INET_NUMHOOKS; h++) { if ((unsigned char *)de - base < newinfo->hook_entry[h]) newinfo->hook_entry[h] -= origsize - *size; if ((unsigned char *)de - base < newinfo->underflow[h]) newinfo->underflow[h] -= origsize - *size; } return ret; } static int compat_check_entry(struct ipt_entry *e, struct net *net, const char *name) { struct xt_entry_match *ematch; struct xt_mtchk_param mtpar; unsigned int j; int ret = 0; e->counters.pcnt = xt_percpu_counter_alloc(); if (IS_ERR_VALUE(e->counters.pcnt)) return -ENOMEM; j = 0; mtpar.net = net; mtpar.table = name; mtpar.entryinfo = &e->ip; mtpar.hook_mask = e->comefrom; mtpar.family = NFPROTO_IPV4; xt_ematch_foreach(ematch, e) { ret = check_match(ematch, &mtpar); if (ret != 0) goto cleanup_matches; ++j; } ret = check_target(e, net, name); if (ret) goto cleanup_matches; return 0; cleanup_matches: xt_ematch_foreach(ematch, e) { if (j-- == 0) break; cleanup_match(ematch, net); } xt_percpu_counter_free(e->counters.pcnt); return ret; } static int translate_compat_table(struct net *net, const char *name, unsigned int valid_hooks, struct xt_table_info **pinfo, void **pentry0, unsigned int total_size, unsigned int number, unsigned int *hook_entries, unsigned int *underflows) { unsigned int i, j; struct xt_table_info *newinfo, *info; void *pos, *entry0, *entry1; struct compat_ipt_entry *iter0; struct ipt_entry *iter1; unsigned int size; int ret; info = *pinfo; entry0 = *pentry0; size = total_size; info->number = number; /* Init all hooks to impossible value. */ for (i = 0; i < NF_INET_NUMHOOKS; i++) { info->hook_entry[i] = 0xFFFFFFFF; info->underflow[i] = 0xFFFFFFFF; } duprintf("translate_compat_table: size %u\n", info->size); j = 0; xt_compat_lock(AF_INET); xt_compat_init_offsets(AF_INET, number); /* Walk through entries, checking offsets. */ xt_entry_foreach(iter0, entry0, total_size) { ret = check_compat_entry_size_and_hooks(iter0, info, &size, entry0, entry0 + total_size, hook_entries, underflows, name); if (ret != 0) goto out_unlock; ++j; } ret = -EINVAL; if (j != number) { duprintf("translate_compat_table: %u not %u entries\n", j, number); goto out_unlock; } /* Check hooks all assigned */ for (i = 0; i < NF_INET_NUMHOOKS; i++) { /* Only hooks which are valid */ if (!(valid_hooks & (1 << i))) continue; if (info->hook_entry[i] == 0xFFFFFFFF) { duprintf("Invalid hook entry %u %u\n", i, hook_entries[i]); goto out_unlock; } if (info->underflow[i] == 0xFFFFFFFF) { duprintf("Invalid underflow %u %u\n", i, underflows[i]); goto out_unlock; } } ret = -ENOMEM; newinfo = xt_alloc_table_info(size); if (!newinfo) goto out_unlock; newinfo->number = number; for (i = 0; i < NF_INET_NUMHOOKS; i++) { newinfo->hook_entry[i] = info->hook_entry[i]; newinfo->underflow[i] = info->underflow[i]; } entry1 = newinfo->entries; pos = entry1; size = total_size; xt_entry_foreach(iter0, entry0, total_size) { ret = compat_copy_entry_from_user(iter0, &pos, &size, name, newinfo, entry1); if (ret != 0) break; } xt_compat_flush_offsets(AF_INET); xt_compat_unlock(AF_INET); if (ret) goto free_newinfo; ret = -ELOOP; if (!mark_source_chains(newinfo, valid_hooks, entry1)) goto free_newinfo; i = 0; xt_entry_foreach(iter1, entry1, newinfo->size) { ret = compat_check_entry(iter1, net, name); if (ret != 0) break; ++i; if (strcmp(ipt_get_target(iter1)->u.user.name, XT_ERROR_TARGET) == 0) ++newinfo->stacksize; } if (ret) { /* * The first i matches need cleanup_entry (calls ->destroy) * because they had called ->check already. The other j-i * entries need only release. */ int skip = i; j -= i; xt_entry_foreach(iter0, entry0, newinfo->size) { if (skip-- > 0) continue; if (j-- == 0) break; compat_release_entry(iter0); } xt_entry_foreach(iter1, entry1, newinfo->size) { if (i-- == 0) break; cleanup_entry(iter1, net); } xt_free_table_info(newinfo); return ret; } *pinfo = newinfo; *pentry0 = entry1; xt_free_table_info(info); return 0; free_newinfo: xt_free_table_info(newinfo); out: xt_entry_foreach(iter0, entry0, total_size) { if (j-- == 0) break; compat_release_entry(iter0); } return ret; out_unlock: xt_compat_flush_offsets(AF_INET); xt_compat_unlock(AF_INET); goto out; } static int compat_do_replace(struct net *net, void __user *user, unsigned int len) { int ret; struct compat_ipt_replace tmp; struct xt_table_info *newinfo; void *loc_cpu_entry; struct ipt_entry *iter; if (copy_from_user(&tmp, user, sizeof(tmp)) != 0) return -EFAULT; /* overflow check */ if (tmp.size >= INT_MAX / num_possible_cpus()) return -ENOMEM; if (tmp.num_counters >= INT_MAX / sizeof(struct xt_counters)) return -ENOMEM; if (tmp.num_counters == 0) return -EINVAL; tmp.name[sizeof(tmp.name)-1] = 0; newinfo = xt_alloc_table_info(tmp.size); if (!newinfo) return -ENOMEM; loc_cpu_entry = newinfo->entries; if (copy_from_user(loc_cpu_entry, user + sizeof(tmp), tmp.size) != 0) { ret = -EFAULT; goto free_newinfo; } ret = translate_compat_table(net, tmp.name, tmp.valid_hooks, &newinfo, &loc_cpu_entry, tmp.size, tmp.num_entries, tmp.hook_entry, tmp.underflow); if (ret != 0) goto free_newinfo; duprintf("compat_do_replace: Translated table\n"); ret = __do_replace(net, tmp.name, tmp.valid_hooks, newinfo, tmp.num_counters, compat_ptr(tmp.counters)); if (ret) goto free_newinfo_untrans; return 0; free_newinfo_untrans: xt_entry_foreach(iter, loc_cpu_entry, newinfo->size) cleanup_entry(iter, net); free_newinfo: xt_free_table_info(newinfo); return ret; } static int compat_do_ipt_set_ctl(struct sock *sk, int cmd, void __user *user, unsigned int len) { int ret; if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) return -EPERM; switch (cmd) { case IPT_SO_SET_REPLACE: ret = compat_do_replace(sock_net(sk), user, len); break; case IPT_SO_SET_ADD_COUNTERS: ret = do_add_counters(sock_net(sk), user, len, 1); break; default: duprintf("do_ipt_set_ctl: unknown request %i\n", cmd); ret = -EINVAL; } return ret; } struct compat_ipt_get_entries { char name[XT_TABLE_MAXNAMELEN]; compat_uint_t size; struct compat_ipt_entry entrytable[0]; }; static int compat_copy_entries_to_user(unsigned int total_size, struct xt_table *table, void __user *userptr) { struct xt_counters *counters; const struct xt_table_info *private = table->private; void __user *pos; unsigned int size; int ret = 0; unsigned int i = 0; struct ipt_entry *iter; counters = alloc_counters(table); if (IS_ERR(counters)) return PTR_ERR(counters); pos = userptr; size = total_size; xt_entry_foreach(iter, private->entries, total_size) { ret = compat_copy_entry_to_user(iter, &pos, &size, counters, i++); if (ret != 0) break; } vfree(counters); return ret; } static int compat_get_entries(struct net *net, struct compat_ipt_get_entries __user *uptr, int *len) { int ret; struct compat_ipt_get_entries get; struct xt_table *t; if (*len < sizeof(get)) { duprintf("compat_get_entries: %u < %zu\n", *len, sizeof(get)); return -EINVAL; } if (copy_from_user(&get, uptr, sizeof(get)) != 0) return -EFAULT; if (*len != sizeof(struct compat_ipt_get_entries) + get.size) { duprintf("compat_get_entries: %u != %zu\n", *len, sizeof(get) + get.size); return -EINVAL; } xt_compat_lock(AF_INET); t = xt_find_table_lock(net, AF_INET, get.name); if (!IS_ERR_OR_NULL(t)) { const struct xt_table_info *private = t->private; struct xt_table_info info; duprintf("t->private->number = %u\n", private->number); ret = compat_table_info(private, &info); if (!ret && get.size == info.size) { ret = compat_copy_entries_to_user(private->size, t, uptr->entrytable); } else if (!ret) { duprintf("compat_get_entries: I've got %u not %u!\n", private->size, get.size); ret = -EAGAIN; } xt_compat_flush_offsets(AF_INET); module_put(t->me); xt_table_unlock(t); } else ret = t ? PTR_ERR(t) : -ENOENT; xt_compat_unlock(AF_INET); return ret; } static int do_ipt_get_ctl(struct sock *, int, void __user *, int *); static int compat_do_ipt_get_ctl(struct sock *sk, int cmd, void __user *user, int *len) { int ret; if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) return -EPERM; switch (cmd) { case IPT_SO_GET_INFO: ret = get_info(sock_net(sk), user, len, 1); break; case IPT_SO_GET_ENTRIES: ret = compat_get_entries(sock_net(sk), user, len); break; default: ret = do_ipt_get_ctl(sk, cmd, user, len); } return ret; } #endif static int do_ipt_set_ctl(struct sock *sk, int cmd, void __user *user, unsigned int len) { int ret; if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) return -EPERM; switch (cmd) { case IPT_SO_SET_REPLACE: ret = do_replace(sock_net(sk), user, len); break; case IPT_SO_SET_ADD_COUNTERS: ret = do_add_counters(sock_net(sk), user, len, 0); break; default: duprintf("do_ipt_set_ctl: unknown request %i\n", cmd); ret = -EINVAL; } return ret; } static int do_ipt_get_ctl(struct sock *sk, int cmd, void __user *user, int *len) { int ret; if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) return -EPERM; switch (cmd) { case IPT_SO_GET_INFO: ret = get_info(sock_net(sk), user, len, 0); break; case IPT_SO_GET_ENTRIES: ret = get_entries(sock_net(sk), user, len); break; case IPT_SO_GET_REVISION_MATCH: case IPT_SO_GET_REVISION_TARGET: { struct xt_get_revision rev; int target; if (*len != sizeof(rev)) { ret = -EINVAL; break; } if (copy_from_user(&rev, user, sizeof(rev)) != 0) { ret = -EFAULT; break; } rev.name[sizeof(rev.name)-1] = 0; if (cmd == IPT_SO_GET_REVISION_TARGET) target = 1; else target = 0; try_then_request_module(xt_find_revision(AF_INET, rev.name, rev.revision, target, &ret), "ipt_%s", rev.name); break; } default: duprintf("do_ipt_get_ctl: unknown request %i\n", cmd); ret = -EINVAL; } return ret; } static void __ipt_unregister_table(struct net *net, struct xt_table *table) { struct xt_table_info *private; void *loc_cpu_entry; struct module *table_owner = table->me; struct ipt_entry *iter; private = xt_unregister_table(table); /* Decrease module usage counts and free resources */ loc_cpu_entry = private->entries; xt_entry_foreach(iter, loc_cpu_entry, private->size) cleanup_entry(iter, net); if (private->number > private->initial_entries) module_put(table_owner); xt_free_table_info(private); } int ipt_register_table(struct net *net, const struct xt_table *table, const struct ipt_replace *repl, const struct nf_hook_ops *ops, struct xt_table **res) { int ret; struct xt_table_info *newinfo; struct xt_table_info bootstrap = {0}; void *loc_cpu_entry; struct xt_table *new_table; newinfo = xt_alloc_table_info(repl->size); if (!newinfo) return -ENOMEM; loc_cpu_entry = newinfo->entries; memcpy(loc_cpu_entry, repl->entries, repl->size); ret = translate_table(net, newinfo, loc_cpu_entry, repl); if (ret != 0) goto out_free; new_table = xt_register_table(net, table, &bootstrap, newinfo); if (IS_ERR(new_table)) { ret = PTR_ERR(new_table); goto out_free; } /* set res now, will see skbs right after nf_register_net_hooks */ WRITE_ONCE(*res, new_table); ret = nf_register_net_hooks(net, ops, hweight32(table->valid_hooks)); if (ret != 0) { __ipt_unregister_table(net, new_table); *res = NULL; } return ret; out_free: xt_free_table_info(newinfo); return ret; } void ipt_unregister_table(struct net *net, struct xt_table *table, const struct nf_hook_ops *ops) { nf_unregister_net_hooks(net, ops, hweight32(table->valid_hooks)); __ipt_unregister_table(net, table); } /* Returns 1 if the type and code is matched by the range, 0 otherwise */ static inline bool icmp_type_code_match(u_int8_t test_type, u_int8_t min_code, u_int8_t max_code, u_int8_t type, u_int8_t code, bool invert) { return ((test_type == 0xFF) || (type == test_type && code >= min_code && code <= max_code)) ^ invert; } static bool icmp_match(const struct sk_buff *skb, struct xt_action_param *par) { const struct icmphdr *ic; struct icmphdr _icmph; const struct ipt_icmp *icmpinfo = par->matchinfo; /* Must not be a fragment. */ if (par->fragoff != 0) return false; ic = skb_header_pointer(skb, par->thoff, sizeof(_icmph), &_icmph); if (ic == NULL) { /* We've been asked to examine this packet, and we * can't. Hence, no choice but to drop. */ duprintf("Dropping evil ICMP tinygram.\n"); par->hotdrop = true; return false; } return icmp_type_code_match(icmpinfo->type, icmpinfo->code[0], icmpinfo->code[1], ic->type, ic->code, !!(icmpinfo->invflags&IPT_ICMP_INV)); } static int icmp_checkentry(const struct xt_mtchk_param *par) { const struct ipt_icmp *icmpinfo = par->matchinfo; /* Must specify no unknown invflags */ return (icmpinfo->invflags & ~IPT_ICMP_INV) ? -EINVAL : 0; } static struct xt_target ipt_builtin_tg[] __read_mostly = { { .name = XT_STANDARD_TARGET, .targetsize = sizeof(int), .family = NFPROTO_IPV4, #ifdef CONFIG_COMPAT .compatsize = sizeof(compat_int_t), .compat_from_user = compat_standard_from_user, .compat_to_user = compat_standard_to_user, #endif }, { .name = XT_ERROR_TARGET, .target = ipt_error, .targetsize = XT_FUNCTION_MAXNAMELEN, .family = NFPROTO_IPV4, }, }; static struct nf_sockopt_ops ipt_sockopts = { .pf = PF_INET, .set_optmin = IPT_BASE_CTL, .set_optmax = IPT_SO_SET_MAX+1, .set = do_ipt_set_ctl, #ifdef CONFIG_COMPAT .compat_set = compat_do_ipt_set_ctl, #endif .get_optmin = IPT_BASE_CTL, .get_optmax = IPT_SO_GET_MAX+1, .get = do_ipt_get_ctl, #ifdef CONFIG_COMPAT .compat_get = compat_do_ipt_get_ctl, #endif .owner = THIS_MODULE, }; static struct xt_match ipt_builtin_mt[] __read_mostly = { { .name = "icmp", .match = icmp_match, .matchsize = sizeof(struct ipt_icmp), .checkentry = icmp_checkentry, .proto = IPPROTO_ICMP, .family = NFPROTO_IPV4, }, }; static int __net_init ip_tables_net_init(struct net *net) { return xt_proto_init(net, NFPROTO_IPV4); } static void __net_exit ip_tables_net_exit(struct net *net) { xt_proto_fini(net, NFPROTO_IPV4); } static struct pernet_operations ip_tables_net_ops = { .init = ip_tables_net_init, .exit = ip_tables_net_exit, }; static int __init ip_tables_init(void) { int ret; ret = register_pernet_subsys(&ip_tables_net_ops); if (ret < 0) goto err1; /* No one else will be downing sem now, so we won't sleep */ ret = xt_register_targets(ipt_builtin_tg, ARRAY_SIZE(ipt_builtin_tg)); if (ret < 0) goto err2; ret = xt_register_matches(ipt_builtin_mt, ARRAY_SIZE(ipt_builtin_mt)); if (ret < 0) goto err4; /* Register setsockopt */ ret = nf_register_sockopt(&ipt_sockopts); if (ret < 0) goto err5; pr_info("(C) 2000-2006 Netfilter Core Team\n"); return 0; err5: xt_unregister_matches(ipt_builtin_mt, ARRAY_SIZE(ipt_builtin_mt)); err4: xt_unregister_targets(ipt_builtin_tg, ARRAY_SIZE(ipt_builtin_tg)); err2: unregister_pernet_subsys(&ip_tables_net_ops); err1: return ret; } static void __exit ip_tables_fini(void) { nf_unregister_sockopt(&ipt_sockopts); xt_unregister_matches(ipt_builtin_mt, ARRAY_SIZE(ipt_builtin_mt)); xt_unregister_targets(ipt_builtin_tg, ARRAY_SIZE(ipt_builtin_tg)); unregister_pernet_subsys(&ip_tables_net_ops); } EXPORT_SYMBOL(ipt_register_table); EXPORT_SYMBOL(ipt_unregister_table); EXPORT_SYMBOL(ipt_do_table); module_init(ip_tables_init); module_exit(ip_tables_fini);
./CrossVul/dataset_final_sorted/CWE-119/c/bad_4999_1
crossvul-cpp_data_bad_4787_13
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % DDDD J V V U U % % D D J V V U U % % D D J V V U U % % D D J J V V U U % % DDDD JJJ V UUU % % % % % % Read DjVu Images. % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2015 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/colormap.h" #include "magick/constitute.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/list.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/pixel-accessor.h" #include "magick/quantum-private.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/module.h" #if defined(MAGICKCORE_DJVU_DELEGATE) #include <libdjvu/ddjvuapi.h> #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s D J V U % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsDJVU() returns MagickTrue if the image format type, identified by the % magick string, is DJVU. % % The format of the IsDJVU method is: % % MagickBooleanType IsDJVU(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 IsDJVU(const unsigned char *magick,const size_t length) { if (length < 8) return(MagickFalse); if (memcmp(magick,"AT&TFORM",8) == 0) return(MagickTrue); return(MagickFalse); } #if defined(MAGICKCORE_DJVU_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d D J V U I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadDJVUImage() reads DJVU image and returns it. It allocates the memory % necessary for the new Image structure and returns a pointer to the new % image or set of images. % % The format of the ReadDJVUImage method is: % % Image *ReadDJVUImage(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. % */ #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif typedef struct _LoadContext LoadContext; struct _LoadContext { ddjvu_context_t* context; ddjvu_document_t *document; ddjvu_page_t *page; int streamid; int pages; Image *image; }; #define BLOCKSIZE 65536 #if 0 static void pump_data(Image *image, LoadContext* lc) { int blocksize = BLOCKSIZE; char data[BLOCKSIZE]; int size; /* i might check for a condition! */ while ((size = (size_t) ReadBlob(image,(size_t) blocksize,data)) == blocksize) { ddjvu_stream_write(lc->document, lc->streamid, data, size); } if (size) ddjvu_stream_write(lc->document, lc->streamid, data, size); ddjvu_stream_close(lc->document, lc->streamid, 0); } #endif /* returns NULL only after all is delivered! */ static ddjvu_message_t* pump_data_until_message(LoadContext *lc,Image *image) /* ddjvu_context_t *context, type ddjvu_document_type_t */ { size_t blocksize = BLOCKSIZE; unsigned char data[BLOCKSIZE]; size_t size; ddjvu_message_t *message; /* i might check for a condition! */ size=0; while (!(message = ddjvu_message_peek(lc->context)) && (size = (size_t) ReadBlob(image,(size_t) blocksize,data)) == blocksize) { ddjvu_stream_write(lc->document, lc->streamid, (char *) data, size); } if (message) return message; if (size) ddjvu_stream_write(lc->document, lc->streamid, (char *) data, size); ddjvu_stream_close(lc->document, lc->streamid, 0); return NULL; } #define DEBUG 0 #if DEBUG static const char* message_tag_name(ddjvu_message_tag_t tag) { static char* names[] = { "ERROR", "INFO", "NEWSTREAM", "DOCINFO", "PAGEINFO", "RELAYOUT", "REDISPLAY", "CHUNK", "THUMBNAIL", "PROGRESS", }; if (tag <= DDJVU_PROGRESS) return names[tag]; else { /* bark! */ return 0; } } #endif /* write out nice info on the message, * and store in *user* data the info on progress. * */ int process_message(ddjvu_message_t *message) { #if 0 ddjvu_context_t* context= message->m_any.context; #endif if (! message) return(-1); #if DEBUG printf("*** %s: %s.\n",__FUNCTION__, message_tag_name(message->m_any.tag)); #endif switch (message->m_any.tag){ case DDJVU_DOCINFO: { ddjvu_document_t* document= message->m_any.document; /* ddjvu_document_decoding_status is set by libdjvu! */ /* we have some info on the document */ LoadContext *lc = (LoadContext *) ddjvu_document_get_user_data(document); lc->pages = ddjvu_document_get_pagenum(document); #if DEBUG printf("the doc has %d pages\n", ddjvu_document_get_pagenum(document)); #endif break; } case DDJVU_CHUNK: #if DEBUG printf("the name of the chunk is: %s\n", message->m_chunk.chunkid); #endif break; case DDJVU_RELAYOUT: case DDJVU_PAGEINFO: { #if 0 ddjvu_page_t* page = message->m_any.page; page_info* info = ddjvu_page_get_user_data(page); printf("page decoding status: %d %s%s%s\n", ddjvu_page_decoding_status(page), status_color, status_name(ddjvu_page_decoding_status(page)), color_reset); printf("the page LAYOUT changed: width x height: %d x %d @ %d dpi. Version %d, type %d\n", // printf("page info:\n width x height: %d x %d @ %d dpi, version %d, type %d\n", ddjvu_page_get_width(page), ddjvu_page_get_height(page), ddjvu_page_get_resolution(page), ddjvu_page_get_version(page), /* DDJVU_PAGETYPE_BITONAL */ ddjvu_page_get_type(page)); info->info = 1; #endif break; } case DDJVU_REDISPLAY: { #if 0 ddjvu_page_t* page = message->m_any.page; page_info* info = ddjvu_page_get_user_data(page); printf("the page can/should be REDISPLAYED\n"); info->display = 1; #endif break; } case DDJVU_PROGRESS: #if DEBUG printf("PROGRESS:\n"); #endif break; case DDJVU_ERROR: printf("simply ERROR!\n message:\t%s\nfunction:\t%s(file %s)\nlineno:\t%d\n", message->m_error.message, message->m_error.function, message->m_error.filename, message->m_error.lineno); break; case DDJVU_INFO: #if DEBUG printf("INFO: %s!\n", message->m_info.message); #endif break; default: printf("unexpected\n"); }; return(message->m_any.tag); } #if defined(__cplusplus) || defined(c_plusplus) } #endif #define RGB 1 /* * DjVu advertised readiness to provide bitmap: So get it! * we use the RGB format! */ static void get_page_image(LoadContext *lc, ddjvu_page_t *page, int x, int y, int w, int h, const ImageInfo *image_info ) { ddjvu_format_t *format; ddjvu_page_type_t type; Image *image; int ret, stride; unsigned char *q; ddjvu_rect_t rect; rect.x = x; rect.y = y; rect.w = (unsigned int) w; /* /10 */ rect.h = (unsigned int) h; /* /10 */ image = lc->image; type = ddjvu_page_get_type(lc->page); /* stride of this temporary buffer: */ stride = (type == DDJVU_PAGETYPE_BITONAL)? (image->columns + 7)/8 : image->columns *3; q = (unsigned char *) AcquireQuantumMemory(image->rows,stride); if (q == (unsigned char *) NULL) return; format = ddjvu_format_create( (type == DDJVU_PAGETYPE_BITONAL)?DDJVU_FORMAT_LSBTOMSB : DDJVU_FORMAT_RGB24, /* DDJVU_FORMAT_RGB24 * DDJVU_FORMAT_RGBMASK32*/ /* DDJVU_FORMAT_RGBMASK32 */ 0, NULL); #if 0 /* fixme: ThrowReaderException is a macro, which uses `exception' variable */ if (format == NULL) { abort(); /* ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); */ } #endif ddjvu_format_set_row_order(format, 1); ddjvu_format_set_y_direction(format, 1); ret = ddjvu_page_render(page, DDJVU_RENDER_COLOR, /* ddjvu_render_mode_t */ &rect, &rect, /* mmc: ?? */ format, stride, /* ?? */ (char*)q); (void) ret; ddjvu_format_release(format); if (type == DDJVU_PAGETYPE_BITONAL) { /* */ #if DEBUG printf("%s: expanding BITONAL page/image\n", __FUNCTION__); #endif register IndexPacket *indexes; size_t bit, byte; for (y=0; y < (ssize_t) image->rows; y++) { PixelPacket * o = QueueAuthenticPixels(image,0,y,image->columns,1,&image->exception); if (o == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); bit=0; byte=0; /* fixme: the non-aligned, last =<7 bits ! that's ok!!!*/ for (x= 0; x < (ssize_t) image->columns; x++) { if (bit == 0) byte= (size_t) q[(y * stride) + (x / 8)]; if (indexes != (IndexPacket *) NULL) SetPixelIndex(indexes+x,(IndexPacket) (((byte & 0x01) != 0) ? 0x00 : 0x01)); bit++; if (bit == 8) bit=0; byte>>=1; } if (SyncAuthenticPixels(image,&image->exception) == MagickFalse) break; } if (!image->ping) SyncImage(image); } else { #if DEBUG printf("%s: expanding PHOTO page/image\n", __FUNCTION__); #endif /* now transfer line-wise: */ ssize_t i; #if 0 /* old: */ char* r; #else register PixelPacket *r; unsigned char *s; #endif s=q; for (i = 0;i< (ssize_t) image->rows; i++) { #if DEBUG if (i % 1000 == 0) printf("%d\n",i); #endif r = QueueAuthenticPixels(image,0,i,image->columns,1,&image->exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(r,ScaleCharToQuantum(*s++)); SetPixelGreen(r,ScaleCharToQuantum(*s++)); SetPixelBlue(r,ScaleCharToQuantum(*s++)); r++; } (void) SyncAuthenticPixels(image,&image->exception); } } q=(unsigned char *) RelinquishMagickMemory(q); } #if defined(MAGICKCORE_DJVU_DELEGATE) #if 0 static int get_page_line(LoadContext *lc, int row, QuantumInfo* quantum_info) { ddjvu_format_t *format; int ret; size_t stride; unsigned char *q; ddjvu_rect_t rect, pagerect; rect.x = 0; rect.y = row; rect.w = lc->image->columns; /* /10 */ rect.h = 1; /* /10 */ pagerect.x = 0; pagerect.y = 0; pagerect.w = lc->image->columns; pagerect.h = lc->image->rows; format = ddjvu_format_create( #if RGB DDJVU_FORMAT_RGB24 #else DDJVU_FORMAT_GREY8 #endif , 0, NULL); ddjvu_format_set_row_order(format, 1); ddjvu_format_set_y_direction(format, 1); stride=1; #if RGB stride=3; #endif q = (unsigned char *) AcquireQuantumMemory(lc->image->columns,stride); ret = ddjvu_page_render(lc->page, DDJVU_RENDER_COLOR, /* ddjvu_render_mode_t */ &pagerect, &rect, /* mmc: ?? */ format, pagerect.w * 3, /* ?? */ (char*)q); ImportQuantumPixels(lc->image, (CacheView *) NULL, quantum_info, #if RGB RGBQuantum #else GrayQuantum #endif ,q,&lc->image->exception); q=(unsigned char *) RelinquishMagickMemory(q); ddjvu_format_release(format); return ret; } #endif #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d O n e D J V U I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadOneDJVUImage() reads a Portable Network Graphics (DJVU) image file % (minus the 8-byte signature) and returns it. It allocates the memory % necessary for the new Image structure and returns a pointer to the new % image. % % The format of the ReadOneDJVUImage method is: % % Image *ReadOneDJVUImage(MngInfo *mng_info, const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o mng_info: Specifies a pointer to a MngInfo structure. % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static inline double MagickMax(const double x,const double y) { if (x > y) return(x); return(y); } static Image *ReadOneDJVUImage(LoadContext* lc,const int pagenum, const ImageInfo *image_info,ExceptionInfo *exception) { ddjvu_page_type_t type; ddjvu_pageinfo_t info; ddjvu_message_t *message; Image *image; int logging; int tag; /* so, we know that the page is there! Get its dimension, and */ /* Read one DJVU image */ image = lc->image; /* register PixelPacket *q; */ logging=LogMagickEvent(CoderEvent,GetMagickModule(), " enter ReadOneDJVUImage()"); (void) logging; #if DEBUG printf("==== Loading the page %d\n", pagenum); #endif lc->page = ddjvu_page_create_by_pageno(lc->document, pagenum); /* 0? */ /* pump data untill the page is ready for rendering. */ tag=(-1); do { while ((message = ddjvu_message_peek(lc->context))) { tag=process_message(message); if (tag == 0) break; ddjvu_message_pop(lc->context); } /* fixme: maybe exit? */ /* if (lc->error) break; */ message = pump_data_until_message(lc,image); if (message) do { tag=process_message(message); if (tag == 0) break; ddjvu_message_pop(lc->context); } while ((message = ddjvu_message_peek(lc->context))); } while (!ddjvu_page_decoding_done(lc->page)); ddjvu_document_get_pageinfo(lc->document, pagenum, &info); image->x_resolution = (float) info.dpi; image->y_resolution =(float) info.dpi; if (image_info->density != (char *) NULL) { int flags; GeometryInfo geometry_info; /* Set rendering resolution. */ flags=ParseGeometry(image_info->density,&geometry_info); image->x_resolution=geometry_info.rho; image->y_resolution=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->y_resolution=image->x_resolution; info.width=(int) (info.width*image->x_resolution/info.dpi); info.height=(int) (info.height*image->y_resolution/info.dpi); info.dpi=(int) MagickMax(image->x_resolution,image->y_resolution); } type = ddjvu_page_get_type(lc->page); /* double -> float! */ /* image->gamma = (float)ddjvu_page_get_gamma(lc->page); */ /* mmc: set image->depth */ /* mmc: This from the type */ image->columns=(size_t) info.width; image->rows=(size_t) info.height; /* mmc: bitonal should be palettized, and compressed! */ if (type == DDJVU_PAGETYPE_BITONAL){ image->colorspace = GRAYColorspace; image->storage_class = PseudoClass; image->depth = 8UL; /* i only support that? */ image->colors= 2; if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } else { image->colorspace = RGBColorspace; image->storage_class = DirectClass; /* fixme: MAGICKCORE_QUANTUM_DEPTH ?*/ image->depth = 8UL; /* i only support that? */ image->matte = MagickTrue; /* is this useful? */ } #if DEBUG printf("now filling %.20g x %.20g\n",(double) image->columns,(double) image->rows); #endif #if 1 /* per_line */ /* q = QueueAuthenticPixels(image,0,0,image->columns,image->rows); */ get_page_image(lc, lc->page, 0, 0, info.width, info.height, image_info); #else int i; for (i = 0;i< image->rows; i++) { printf("%d\n",i); q = QueueAuthenticPixels(image,0,i,image->columns,1); get_page_line(lc, i, quantum_info); SyncAuthenticPixels(image); } #endif /* per_line */ #if DEBUG printf("END: finished filling %.20g x %.20g\n",(double) image->columns, (double) image->rows); #endif if (!image->ping) SyncImage(image); /* indexes=GetAuthenticIndexQueue(image); */ /* mmc: ??? Convert PNM pixels to runlength-encoded MIFF packets. */ /* image->colors = */ /* how is the line padding / stride? */ if (lc->page) { ddjvu_page_release(lc->page); lc->page = NULL; } /* image->page.y=mng_info->y_off[mng_info->object_id]; */ if (tag == 0) image=DestroyImage(image); return image; /* end of reading one DJVU page/image */ } #if 0 /* palette */ if (AcquireImageColormap(image,2) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Monochrome colormap. mmc: this the default! */ image->colormap[0].red=QuantumRange; image->colormap[0].green=QuantumRange; image->colormap[0].blue=QuantumRange; image->colormap[1].red=0; image->colormap[1].green=0; image->colormap[1].blue=0; #endif static void djvu_close_lc(LoadContext* lc) { if (lc->document) ddjvu_document_release(lc->document); if (lc->context) ddjvu_context_release(lc->context); if (lc->page) ddjvu_page_release(lc->page); RelinquishMagickMemory(lc); } static Image *ReadDJVUImage(const ImageInfo *image_info, ExceptionInfo *exception) { const char *url; ddjvu_message_t *message; Image *image, *images; int logging, use_cache; LoadContext *lc; MagickBooleanType status; register ssize_t i; /* * Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter ReadDJVUImage()"); (void) logging; image = AcquireImage(image_info); /* mmc: ?? */ lc = (LoadContext *) NULL; status = OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) ThrowReaderException(FileOpenError,"UnableToOpenFile"); /* Verify DJVU signature. */ #if 0 count = ReadBlob(image,8,(unsigned char *) magic_number); /* IsDJVU(const unsigned char *magick,const size_t length) */ if (memcmp(magic_number,"AT&TFORM",8) != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); #endif /* * Allocate a LoadContext structure. */ lc = (LoadContext *) AcquireMagickMemory(sizeof(*lc)); if (lc == NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* * Initialize members of the MngInfo structure. */ (void) ResetMagickMemory(lc,0,sizeof(LoadContext)); lc->image = image; lc->pages = 0; lc->context = ddjvu_context_create("ImageMagick djvu loader"); /* g_program_name */ ddjvu_cache_set_size(lc->context, 1); /* right? */ use_cache = 0; /* document: here we don't have a filename, but, for the sake of generality, a FILE* ! */ url="http://www.imagemagick.org/fake.djvu"; lc->document = ddjvu_document_create(lc->context, url, use_cache); /* don't cache */ ddjvu_document_set_user_data(lc->document, lc); /* now we wait the message-request for data: */ message = ddjvu_message_wait(lc->context); if (message->m_any.tag != DDJVU_NEWSTREAM) { /* fixme: the djvu context, document! */ ddjvu_document_release(lc->document); ddjvu_context_release(lc->context); RelinquishMagickMemory(lc); ThrowReaderException(ResourceLimitError,"Djvu initial message: unexpected type"); return NULL; /* error! */ }; lc->streamid = message->m_newstream.streamid; ddjvu_message_pop(lc->context); message = pump_data_until_message(lc,image); /* now process the messages: */ if (message) do { process_message(message); ddjvu_message_pop(lc->context); } while ((message = ddjvu_message_peek(lc->context))); /* fixme: i hope we have not read any messages pertinent(?) related to the page itself! */ while (lc->pages == 0) { message = ddjvu_message_wait(lc->context); process_message(message); ddjvu_message_pop(lc->context); } images=NewImageList(); i=0; if (image_info->number_scenes != 0) i=image_info->scene; for ( ; i < (ssize_t) lc->pages; i++) { image=ReadOneDJVUImage(lc,i,image_info,exception); if (image == (Image *) NULL) break; image->scene=i; AppendImageToList(&images,CloneImageList(image,exception)); images->extent=GetBlobSize(image); if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; } djvu_close_lc(lc); (void) CloseBlob(images); if (image != (Image *) NULL) image=DestroyImageList(image); #if 0 if ((image->page.width == 0) && (image->page.height == 0)) { image->page.width = image->columns+image->page.x; image->page.height = image->rows+image->page.y; } if (image->columns == 0 || image->rows == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadDJVUImage() with error."); ThrowReaderException(CorruptImageError,"CorruptImage"); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadDJVUImage()"); #endif return(GetFirstImageInList(images)); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r D J V U I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterDJVUImage() adds attributes for the DJVU 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 RegisterDJVUImage method is: % % size_t RegisterDJVUImage(void) % */ ModuleExport size_t RegisterDJVUImage(void) { char version[MaxTextExtent]; MagickInfo *entry; static const char *DJVUNote = { "See http://www.djvuzone.org/ for details about the DJVU format. The\n" "DJVU 1.2 specification is available there and at\n" "ftp://swrinde.nde.swri.edu/pub/djvu/documents/." }; *version='\0'; #if defined(DJVU_LIBDJVU_VER_STRING) (void) ConcatenateMagickString(version,"libdjvu ",MaxTextExtent); (void) ConcatenateMagickString(version,DJVU_LIBDJVU_VER_STRING,MaxTextExtent); #endif entry=SetMagickInfo("DJVU"); #if defined(MAGICKCORE_DJVU_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadDJVUImage; #endif entry->raw=MagickTrue; entry->magick=(IsImageFormatHandler *) IsDJVU; entry->adjoin=MagickFalse; entry->thread_support=MagickTrue; entry->description=AcquireString("D�j� vu"); entry->module=AcquireString("DJVU"); if (*version != '\0') entry->version=AcquireString(version); entry->note=AcquireString(DJVUNote); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r D J V U I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterDJVUImage() removes format registrations made by the % DJVU module from the list of supported formats. % % The format of the UnregisterDJVUImage method is: % % UnregisterDJVUImage(void) % */ ModuleExport void UnregisterDJVUImage(void) { (void) UnregisterMagickInfo("DJVU"); }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_4787_13
crossvul-cpp_data_good_5756_0
/* * Copyright (C) 2002 - 2007 Jeff Dike (jdike@{addtoit,linux.intel}.com) * Licensed under the GPL */ #include <linux/ctype.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/proc_fs.h> #include <linux/seq_file.h> #include <linux/types.h> #include <asm/uaccess.h> /* * If read and write race, the read will still atomically read a valid * value. */ int uml_exitcode = 0; static int exitcode_proc_show(struct seq_file *m, void *v) { int val; /* * Save uml_exitcode in a local so that we don't need to guarantee * that sprintf accesses it atomically. */ val = uml_exitcode; seq_printf(m, "%d\n", val); return 0; } static int exitcode_proc_open(struct inode *inode, struct file *file) { return single_open(file, exitcode_proc_show, NULL); } static ssize_t exitcode_proc_write(struct file *file, const char __user *buffer, size_t count, loff_t *pos) { char *end, buf[sizeof("nnnnn\0")]; size_t size; int tmp; size = min(count, sizeof(buf)); if (copy_from_user(buf, buffer, size)) return -EFAULT; tmp = simple_strtol(buf, &end, 0); if ((*end != '\0') && !isspace(*end)) return -EINVAL; uml_exitcode = tmp; return count; } static const struct file_operations exitcode_proc_fops = { .owner = THIS_MODULE, .open = exitcode_proc_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, .write = exitcode_proc_write, }; static int make_proc_exitcode(void) { struct proc_dir_entry *ent; ent = proc_create("exitcode", 0600, NULL, &exitcode_proc_fops); if (ent == NULL) { printk(KERN_WARNING "make_proc_exitcode : Failed to register " "/proc/exitcode\n"); return 0; } return 0; } __initcall(make_proc_exitcode);
./CrossVul/dataset_final_sorted/CWE-119/c/good_5756_0
crossvul-cpp_data_bad_3418_0
/* * VP7/VP8 compatible video decoder * * Copyright (C) 2010 David Conrad * Copyright (C) 2010 Ronald S. Bultje * Copyright (C) 2010 Fiona Glaser * Copyright (C) 2012 Daniel Kang * Copyright (C) 2014 Peter Ross * * 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 "libavutil/imgutils.h" #include "avcodec.h" #include "internal.h" #include "mathops.h" #include "rectangle.h" #include "thread.h" #include "vp8.h" #include "vp8data.h" #if ARCH_ARM # include "arm/vp8.h" #endif #if CONFIG_VP7_DECODER && CONFIG_VP8_DECODER #define VPX(vp7, f) (vp7 ? vp7_ ## f : vp8_ ## f) #elif CONFIG_VP7_DECODER #define VPX(vp7, f) vp7_ ## f #else // CONFIG_VP8_DECODER #define VPX(vp7, f) vp8_ ## f #endif static void free_buffers(VP8Context *s) { int i; if (s->thread_data) for (i = 0; i < MAX_THREADS; i++) { #if HAVE_THREADS pthread_cond_destroy(&s->thread_data[i].cond); pthread_mutex_destroy(&s->thread_data[i].lock); #endif av_freep(&s->thread_data[i].filter_strength); } av_freep(&s->thread_data); av_freep(&s->macroblocks_base); av_freep(&s->intra4x4_pred_mode_top); av_freep(&s->top_nnz); av_freep(&s->top_border); s->macroblocks = NULL; } static int vp8_alloc_frame(VP8Context *s, VP8Frame *f, int ref) { int ret; if ((ret = ff_thread_get_buffer(s->avctx, &f->tf, ref ? AV_GET_BUFFER_FLAG_REF : 0)) < 0) return ret; if (!(f->seg_map = av_buffer_allocz(s->mb_width * s->mb_height))) { ff_thread_release_buffer(s->avctx, &f->tf); return AVERROR(ENOMEM); } return 0; } static void vp8_release_frame(VP8Context *s, VP8Frame *f) { av_buffer_unref(&f->seg_map); ff_thread_release_buffer(s->avctx, &f->tf); } #if CONFIG_VP8_DECODER static int vp8_ref_frame(VP8Context *s, VP8Frame *dst, VP8Frame *src) { int ret; vp8_release_frame(s, dst); if ((ret = ff_thread_ref_frame(&dst->tf, &src->tf)) < 0) return ret; if (src->seg_map && !(dst->seg_map = av_buffer_ref(src->seg_map))) { vp8_release_frame(s, dst); return AVERROR(ENOMEM); } return 0; } #endif /* CONFIG_VP8_DECODER */ static void vp8_decode_flush_impl(AVCodecContext *avctx, int free_mem) { VP8Context *s = avctx->priv_data; int i; for (i = 0; i < FF_ARRAY_ELEMS(s->frames); i++) vp8_release_frame(s, &s->frames[i]); memset(s->framep, 0, sizeof(s->framep)); if (free_mem) free_buffers(s); } static void vp8_decode_flush(AVCodecContext *avctx) { vp8_decode_flush_impl(avctx, 0); } static VP8Frame *vp8_find_free_buffer(VP8Context *s) { VP8Frame *frame = NULL; int i; // find a free buffer for (i = 0; i < 5; i++) if (&s->frames[i] != s->framep[VP56_FRAME_CURRENT] && &s->frames[i] != s->framep[VP56_FRAME_PREVIOUS] && &s->frames[i] != s->framep[VP56_FRAME_GOLDEN] && &s->frames[i] != s->framep[VP56_FRAME_GOLDEN2]) { frame = &s->frames[i]; break; } if (i == 5) { av_log(s->avctx, AV_LOG_FATAL, "Ran out of free frames!\n"); abort(); } if (frame->tf.f->data[0]) vp8_release_frame(s, frame); return frame; } static av_always_inline int update_dimensions(VP8Context *s, int width, int height, int is_vp7) { AVCodecContext *avctx = s->avctx; int i, ret; if (width != s->avctx->width || ((width+15)/16 != s->mb_width || (height+15)/16 != s->mb_height) && s->macroblocks_base || height != s->avctx->height) { vp8_decode_flush_impl(s->avctx, 1); ret = ff_set_dimensions(s->avctx, width, height); if (ret < 0) return ret; } s->mb_width = (s->avctx->coded_width + 15) / 16; s->mb_height = (s->avctx->coded_height + 15) / 16; s->mb_layout = is_vp7 || avctx->active_thread_type == FF_THREAD_SLICE && avctx->thread_count > 1; if (!s->mb_layout) { // Frame threading and one thread s->macroblocks_base = av_mallocz((s->mb_width + s->mb_height * 2 + 1) * sizeof(*s->macroblocks)); s->intra4x4_pred_mode_top = av_mallocz(s->mb_width * 4); } else // Sliced threading s->macroblocks_base = av_mallocz((s->mb_width + 2) * (s->mb_height + 2) * sizeof(*s->macroblocks)); s->top_nnz = av_mallocz(s->mb_width * sizeof(*s->top_nnz)); s->top_border = av_mallocz((s->mb_width + 1) * sizeof(*s->top_border)); s->thread_data = av_mallocz(MAX_THREADS * sizeof(VP8ThreadData)); if (!s->macroblocks_base || !s->top_nnz || !s->top_border || !s->thread_data || (!s->intra4x4_pred_mode_top && !s->mb_layout)) { free_buffers(s); return AVERROR(ENOMEM); } for (i = 0; i < MAX_THREADS; i++) { s->thread_data[i].filter_strength = av_mallocz(s->mb_width * sizeof(*s->thread_data[0].filter_strength)); if (!s->thread_data[i].filter_strength) { free_buffers(s); return AVERROR(ENOMEM); } #if HAVE_THREADS pthread_mutex_init(&s->thread_data[i].lock, NULL); pthread_cond_init(&s->thread_data[i].cond, NULL); #endif } s->macroblocks = s->macroblocks_base + 1; return 0; } static int vp7_update_dimensions(VP8Context *s, int width, int height) { return update_dimensions(s, width, height, IS_VP7); } static int vp8_update_dimensions(VP8Context *s, int width, int height) { return update_dimensions(s, width, height, IS_VP8); } static void parse_segment_info(VP8Context *s) { VP56RangeCoder *c = &s->c; int i; s->segmentation.update_map = vp8_rac_get(c); if (vp8_rac_get(c)) { // update segment feature data s->segmentation.absolute_vals = vp8_rac_get(c); for (i = 0; i < 4; i++) s->segmentation.base_quant[i] = vp8_rac_get_sint(c, 7); for (i = 0; i < 4; i++) s->segmentation.filter_level[i] = vp8_rac_get_sint(c, 6); } if (s->segmentation.update_map) for (i = 0; i < 3; i++) s->prob->segmentid[i] = vp8_rac_get(c) ? vp8_rac_get_uint(c, 8) : 255; } static void update_lf_deltas(VP8Context *s) { VP56RangeCoder *c = &s->c; int i; for (i = 0; i < 4; i++) { if (vp8_rac_get(c)) { s->lf_delta.ref[i] = vp8_rac_get_uint(c, 6); if (vp8_rac_get(c)) s->lf_delta.ref[i] = -s->lf_delta.ref[i]; } } for (i = MODE_I4x4; i <= VP8_MVMODE_SPLIT; i++) { if (vp8_rac_get(c)) { s->lf_delta.mode[i] = vp8_rac_get_uint(c, 6); if (vp8_rac_get(c)) s->lf_delta.mode[i] = -s->lf_delta.mode[i]; } } } static int setup_partitions(VP8Context *s, const uint8_t *buf, int buf_size) { const uint8_t *sizes = buf; int i; int ret; s->num_coeff_partitions = 1 << vp8_rac_get_uint(&s->c, 2); buf += 3 * (s->num_coeff_partitions - 1); buf_size -= 3 * (s->num_coeff_partitions - 1); if (buf_size < 0) return -1; for (i = 0; i < s->num_coeff_partitions - 1; i++) { int size = AV_RL24(sizes + 3 * i); if (buf_size - size < 0) return -1; ret = ff_vp56_init_range_decoder(&s->coeff_partition[i], buf, size); if (ret < 0) return ret; buf += size; buf_size -= size; } return ff_vp56_init_range_decoder(&s->coeff_partition[i], buf, buf_size); } static void vp7_get_quants(VP8Context *s) { VP56RangeCoder *c = &s->c; int yac_qi = vp8_rac_get_uint(c, 7); int ydc_qi = vp8_rac_get(c) ? vp8_rac_get_uint(c, 7) : yac_qi; int y2dc_qi = vp8_rac_get(c) ? vp8_rac_get_uint(c, 7) : yac_qi; int y2ac_qi = vp8_rac_get(c) ? vp8_rac_get_uint(c, 7) : yac_qi; int uvdc_qi = vp8_rac_get(c) ? vp8_rac_get_uint(c, 7) : yac_qi; int uvac_qi = vp8_rac_get(c) ? vp8_rac_get_uint(c, 7) : yac_qi; s->qmat[0].luma_qmul[0] = vp7_ydc_qlookup[ydc_qi]; s->qmat[0].luma_qmul[1] = vp7_yac_qlookup[yac_qi]; s->qmat[0].luma_dc_qmul[0] = vp7_y2dc_qlookup[y2dc_qi]; s->qmat[0].luma_dc_qmul[1] = vp7_y2ac_qlookup[y2ac_qi]; s->qmat[0].chroma_qmul[0] = FFMIN(vp7_ydc_qlookup[uvdc_qi], 132); s->qmat[0].chroma_qmul[1] = vp7_yac_qlookup[uvac_qi]; } static void vp8_get_quants(VP8Context *s) { VP56RangeCoder *c = &s->c; int i, base_qi; int yac_qi = vp8_rac_get_uint(c, 7); int ydc_delta = vp8_rac_get_sint(c, 4); int y2dc_delta = vp8_rac_get_sint(c, 4); int y2ac_delta = vp8_rac_get_sint(c, 4); int uvdc_delta = vp8_rac_get_sint(c, 4); int uvac_delta = vp8_rac_get_sint(c, 4); for (i = 0; i < 4; i++) { if (s->segmentation.enabled) { base_qi = s->segmentation.base_quant[i]; if (!s->segmentation.absolute_vals) base_qi += yac_qi; } else base_qi = yac_qi; s->qmat[i].luma_qmul[0] = vp8_dc_qlookup[av_clip_uintp2(base_qi + ydc_delta, 7)]; s->qmat[i].luma_qmul[1] = vp8_ac_qlookup[av_clip_uintp2(base_qi, 7)]; s->qmat[i].luma_dc_qmul[0] = vp8_dc_qlookup[av_clip_uintp2(base_qi + y2dc_delta, 7)] * 2; /* 101581>>16 is equivalent to 155/100 */ s->qmat[i].luma_dc_qmul[1] = vp8_ac_qlookup[av_clip_uintp2(base_qi + y2ac_delta, 7)] * 101581 >> 16; s->qmat[i].chroma_qmul[0] = vp8_dc_qlookup[av_clip_uintp2(base_qi + uvdc_delta, 7)]; s->qmat[i].chroma_qmul[1] = vp8_ac_qlookup[av_clip_uintp2(base_qi + uvac_delta, 7)]; s->qmat[i].luma_dc_qmul[1] = FFMAX(s->qmat[i].luma_dc_qmul[1], 8); s->qmat[i].chroma_qmul[0] = FFMIN(s->qmat[i].chroma_qmul[0], 132); } } /** * Determine which buffers golden and altref should be updated with after this frame. * The spec isn't clear here, so I'm going by my understanding of what libvpx does * * Intra frames update all 3 references * Inter frames update VP56_FRAME_PREVIOUS if the update_last flag is set * If the update (golden|altref) flag is set, it's updated with the current frame * if update_last is set, and VP56_FRAME_PREVIOUS otherwise. * If the flag is not set, the number read means: * 0: no update * 1: VP56_FRAME_PREVIOUS * 2: update golden with altref, or update altref with golden */ static VP56Frame ref_to_update(VP8Context *s, int update, VP56Frame ref) { VP56RangeCoder *c = &s->c; if (update) return VP56_FRAME_CURRENT; switch (vp8_rac_get_uint(c, 2)) { case 1: return VP56_FRAME_PREVIOUS; case 2: return (ref == VP56_FRAME_GOLDEN) ? VP56_FRAME_GOLDEN2 : VP56_FRAME_GOLDEN; } return VP56_FRAME_NONE; } static void vp78_reset_probability_tables(VP8Context *s) { int i, j; for (i = 0; i < 4; i++) for (j = 0; j < 16; j++) memcpy(s->prob->token[i][j], vp8_token_default_probs[i][vp8_coeff_band[j]], sizeof(s->prob->token[i][j])); } static void vp78_update_probability_tables(VP8Context *s) { VP56RangeCoder *c = &s->c; int i, j, k, l, m; for (i = 0; i < 4; i++) for (j = 0; j < 8; j++) for (k = 0; k < 3; k++) for (l = 0; l < NUM_DCT_TOKENS-1; l++) if (vp56_rac_get_prob_branchy(c, vp8_token_update_probs[i][j][k][l])) { int prob = vp8_rac_get_uint(c, 8); for (m = 0; vp8_coeff_band_indexes[j][m] >= 0; m++) s->prob->token[i][vp8_coeff_band_indexes[j][m]][k][l] = prob; } } #define VP7_MVC_SIZE 17 #define VP8_MVC_SIZE 19 static void vp78_update_pred16x16_pred8x8_mvc_probabilities(VP8Context *s, int mvc_size) { VP56RangeCoder *c = &s->c; int i, j; if (vp8_rac_get(c)) for (i = 0; i < 4; i++) s->prob->pred16x16[i] = vp8_rac_get_uint(c, 8); if (vp8_rac_get(c)) for (i = 0; i < 3; i++) s->prob->pred8x8c[i] = vp8_rac_get_uint(c, 8); // 17.2 MV probability update for (i = 0; i < 2; i++) for (j = 0; j < mvc_size; j++) if (vp56_rac_get_prob_branchy(c, vp8_mv_update_prob[i][j])) s->prob->mvc[i][j] = vp8_rac_get_nn(c); } static void update_refs(VP8Context *s) { VP56RangeCoder *c = &s->c; int update_golden = vp8_rac_get(c); int update_altref = vp8_rac_get(c); s->update_golden = ref_to_update(s, update_golden, VP56_FRAME_GOLDEN); s->update_altref = ref_to_update(s, update_altref, VP56_FRAME_GOLDEN2); } static void copy_chroma(AVFrame *dst, AVFrame *src, int width, int height) { int i, j; for (j = 1; j < 3; j++) { for (i = 0; i < height / 2; i++) memcpy(dst->data[j] + i * dst->linesize[j], src->data[j] + i * src->linesize[j], width / 2); } } static void fade(uint8_t *dst, ptrdiff_t dst_linesize, const uint8_t *src, ptrdiff_t src_linesize, int width, int height, int alpha, int beta) { int i, j; for (j = 0; j < height; j++) { for (i = 0; i < width; i++) { uint8_t y = src[j * src_linesize + i]; dst[j * dst_linesize + i] = av_clip_uint8(y + ((y * beta) >> 8) + alpha); } } } static int vp7_fade_frame(VP8Context *s, VP56RangeCoder *c) { int alpha = (int8_t) vp8_rac_get_uint(c, 8); int beta = (int8_t) vp8_rac_get_uint(c, 8); int ret; if (!s->keyframe && (alpha || beta)) { int width = s->mb_width * 16; int height = s->mb_height * 16; AVFrame *src, *dst; if (!s->framep[VP56_FRAME_PREVIOUS] || !s->framep[VP56_FRAME_GOLDEN]) { av_log(s->avctx, AV_LOG_WARNING, "Discarding interframe without a prior keyframe!\n"); return AVERROR_INVALIDDATA; } dst = src = s->framep[VP56_FRAME_PREVIOUS]->tf.f; /* preserve the golden frame, write a new previous frame */ if (s->framep[VP56_FRAME_GOLDEN] == s->framep[VP56_FRAME_PREVIOUS]) { s->framep[VP56_FRAME_PREVIOUS] = vp8_find_free_buffer(s); if ((ret = vp8_alloc_frame(s, s->framep[VP56_FRAME_PREVIOUS], 1)) < 0) return ret; dst = s->framep[VP56_FRAME_PREVIOUS]->tf.f; copy_chroma(dst, src, width, height); } fade(dst->data[0], dst->linesize[0], src->data[0], src->linesize[0], width, height, alpha, beta); } return 0; } static int vp7_decode_frame_header(VP8Context *s, const uint8_t *buf, int buf_size) { VP56RangeCoder *c = &s->c; int part1_size, hscale, vscale, i, j, ret; int width = s->avctx->width; int height = s->avctx->height; if (buf_size < 4) { return AVERROR_INVALIDDATA; } s->profile = (buf[0] >> 1) & 7; if (s->profile > 1) { avpriv_request_sample(s->avctx, "Unknown profile %d", s->profile); return AVERROR_INVALIDDATA; } s->keyframe = !(buf[0] & 1); s->invisible = 0; part1_size = AV_RL24(buf) >> 4; if (buf_size < 4 - s->profile + part1_size) { av_log(s->avctx, AV_LOG_ERROR, "Buffer size %d is too small, needed : %d\n", buf_size, 4 - s->profile + part1_size); return AVERROR_INVALIDDATA; } buf += 4 - s->profile; buf_size -= 4 - s->profile; memcpy(s->put_pixels_tab, s->vp8dsp.put_vp8_epel_pixels_tab, sizeof(s->put_pixels_tab)); ret = ff_vp56_init_range_decoder(c, buf, part1_size); if (ret < 0) return ret; buf += part1_size; buf_size -= part1_size; /* A. Dimension information (keyframes only) */ if (s->keyframe) { width = vp8_rac_get_uint(c, 12); height = vp8_rac_get_uint(c, 12); hscale = vp8_rac_get_uint(c, 2); vscale = vp8_rac_get_uint(c, 2); if (hscale || vscale) avpriv_request_sample(s->avctx, "Upscaling"); s->update_golden = s->update_altref = VP56_FRAME_CURRENT; vp78_reset_probability_tables(s); memcpy(s->prob->pred16x16, vp8_pred16x16_prob_inter, sizeof(s->prob->pred16x16)); memcpy(s->prob->pred8x8c, vp8_pred8x8c_prob_inter, sizeof(s->prob->pred8x8c)); for (i = 0; i < 2; i++) memcpy(s->prob->mvc[i], vp7_mv_default_prob[i], sizeof(vp7_mv_default_prob[i])); memset(&s->segmentation, 0, sizeof(s->segmentation)); memset(&s->lf_delta, 0, sizeof(s->lf_delta)); memcpy(s->prob[0].scan, ff_zigzag_scan, sizeof(s->prob[0].scan)); } if (s->keyframe || s->profile > 0) memset(s->inter_dc_pred, 0 , sizeof(s->inter_dc_pred)); /* B. Decoding information for all four macroblock-level features */ for (i = 0; i < 4; i++) { s->feature_enabled[i] = vp8_rac_get(c); if (s->feature_enabled[i]) { s->feature_present_prob[i] = vp8_rac_get_uint(c, 8); for (j = 0; j < 3; j++) s->feature_index_prob[i][j] = vp8_rac_get(c) ? vp8_rac_get_uint(c, 8) : 255; if (vp7_feature_value_size[s->profile][i]) for (j = 0; j < 4; j++) s->feature_value[i][j] = vp8_rac_get(c) ? vp8_rac_get_uint(c, vp7_feature_value_size[s->profile][i]) : 0; } } s->segmentation.enabled = 0; s->segmentation.update_map = 0; s->lf_delta.enabled = 0; s->num_coeff_partitions = 1; ret = ff_vp56_init_range_decoder(&s->coeff_partition[0], buf, buf_size); if (ret < 0) return ret; if (!s->macroblocks_base || /* first frame */ width != s->avctx->width || height != s->avctx->height || (width + 15) / 16 != s->mb_width || (height + 15) / 16 != s->mb_height) { if ((ret = vp7_update_dimensions(s, width, height)) < 0) return ret; } /* C. Dequantization indices */ vp7_get_quants(s); /* D. Golden frame update flag (a Flag) for interframes only */ if (!s->keyframe) { s->update_golden = vp8_rac_get(c) ? VP56_FRAME_CURRENT : VP56_FRAME_NONE; s->sign_bias[VP56_FRAME_GOLDEN] = 0; } s->update_last = 1; s->update_probabilities = 1; s->fade_present = 1; if (s->profile > 0) { s->update_probabilities = vp8_rac_get(c); if (!s->update_probabilities) s->prob[1] = s->prob[0]; if (!s->keyframe) s->fade_present = vp8_rac_get(c); } /* E. Fading information for previous frame */ if (s->fade_present && vp8_rac_get(c)) { if ((ret = vp7_fade_frame(s ,c)) < 0) return ret; } /* F. Loop filter type */ if (!s->profile) s->filter.simple = vp8_rac_get(c); /* G. DCT coefficient ordering specification */ if (vp8_rac_get(c)) for (i = 1; i < 16; i++) s->prob[0].scan[i] = ff_zigzag_scan[vp8_rac_get_uint(c, 4)]; /* H. Loop filter levels */ if (s->profile > 0) s->filter.simple = vp8_rac_get(c); s->filter.level = vp8_rac_get_uint(c, 6); s->filter.sharpness = vp8_rac_get_uint(c, 3); /* I. DCT coefficient probability update; 13.3 Token Probability Updates */ vp78_update_probability_tables(s); s->mbskip_enabled = 0; /* J. The remaining frame header data occurs ONLY FOR INTERFRAMES */ if (!s->keyframe) { s->prob->intra = vp8_rac_get_uint(c, 8); s->prob->last = vp8_rac_get_uint(c, 8); vp78_update_pred16x16_pred8x8_mvc_probabilities(s, VP7_MVC_SIZE); } return 0; } static int vp8_decode_frame_header(VP8Context *s, const uint8_t *buf, int buf_size) { VP56RangeCoder *c = &s->c; int header_size, hscale, vscale, ret; int width = s->avctx->width; int height = s->avctx->height; if (buf_size < 3) { av_log(s->avctx, AV_LOG_ERROR, "Insufficent data (%d) for header\n", buf_size); return AVERROR_INVALIDDATA; } s->keyframe = !(buf[0] & 1); s->profile = (buf[0]>>1) & 7; s->invisible = !(buf[0] & 0x10); header_size = AV_RL24(buf) >> 5; buf += 3; buf_size -= 3; if (s->profile > 3) av_log(s->avctx, AV_LOG_WARNING, "Unknown profile %d\n", s->profile); if (!s->profile) memcpy(s->put_pixels_tab, s->vp8dsp.put_vp8_epel_pixels_tab, sizeof(s->put_pixels_tab)); else // profile 1-3 use bilinear, 4+ aren't defined so whatever memcpy(s->put_pixels_tab, s->vp8dsp.put_vp8_bilinear_pixels_tab, sizeof(s->put_pixels_tab)); if (header_size > buf_size - 7 * s->keyframe) { av_log(s->avctx, AV_LOG_ERROR, "Header size larger than data provided\n"); return AVERROR_INVALIDDATA; } if (s->keyframe) { if (AV_RL24(buf) != 0x2a019d) { av_log(s->avctx, AV_LOG_ERROR, "Invalid start code 0x%x\n", AV_RL24(buf)); return AVERROR_INVALIDDATA; } width = AV_RL16(buf + 3) & 0x3fff; height = AV_RL16(buf + 5) & 0x3fff; hscale = buf[4] >> 6; vscale = buf[6] >> 6; buf += 7; buf_size -= 7; if (hscale || vscale) avpriv_request_sample(s->avctx, "Upscaling"); s->update_golden = s->update_altref = VP56_FRAME_CURRENT; vp78_reset_probability_tables(s); memcpy(s->prob->pred16x16, vp8_pred16x16_prob_inter, sizeof(s->prob->pred16x16)); memcpy(s->prob->pred8x8c, vp8_pred8x8c_prob_inter, sizeof(s->prob->pred8x8c)); memcpy(s->prob->mvc, vp8_mv_default_prob, sizeof(s->prob->mvc)); memset(&s->segmentation, 0, sizeof(s->segmentation)); memset(&s->lf_delta, 0, sizeof(s->lf_delta)); } ret = ff_vp56_init_range_decoder(c, buf, header_size); if (ret < 0) return ret; buf += header_size; buf_size -= header_size; if (s->keyframe) { s->colorspace = vp8_rac_get(c); if (s->colorspace) av_log(s->avctx, AV_LOG_WARNING, "Unspecified colorspace\n"); s->fullrange = vp8_rac_get(c); } if ((s->segmentation.enabled = vp8_rac_get(c))) parse_segment_info(s); else s->segmentation.update_map = 0; // FIXME: move this to some init function? s->filter.simple = vp8_rac_get(c); s->filter.level = vp8_rac_get_uint(c, 6); s->filter.sharpness = vp8_rac_get_uint(c, 3); if ((s->lf_delta.enabled = vp8_rac_get(c))) if (vp8_rac_get(c)) update_lf_deltas(s); if (setup_partitions(s, buf, buf_size)) { av_log(s->avctx, AV_LOG_ERROR, "Invalid partitions\n"); return AVERROR_INVALIDDATA; } if (!s->macroblocks_base || /* first frame */ width != s->avctx->width || height != s->avctx->height || (width+15)/16 != s->mb_width || (height+15)/16 != s->mb_height) if ((ret = vp8_update_dimensions(s, width, height)) < 0) return ret; vp8_get_quants(s); if (!s->keyframe) { update_refs(s); s->sign_bias[VP56_FRAME_GOLDEN] = vp8_rac_get(c); s->sign_bias[VP56_FRAME_GOLDEN2 /* altref */] = vp8_rac_get(c); } // if we aren't saving this frame's probabilities for future frames, // make a copy of the current probabilities if (!(s->update_probabilities = vp8_rac_get(c))) s->prob[1] = s->prob[0]; s->update_last = s->keyframe || vp8_rac_get(c); vp78_update_probability_tables(s); if ((s->mbskip_enabled = vp8_rac_get(c))) s->prob->mbskip = vp8_rac_get_uint(c, 8); if (!s->keyframe) { s->prob->intra = vp8_rac_get_uint(c, 8); s->prob->last = vp8_rac_get_uint(c, 8); s->prob->golden = vp8_rac_get_uint(c, 8); vp78_update_pred16x16_pred8x8_mvc_probabilities(s, VP8_MVC_SIZE); } return 0; } static av_always_inline void clamp_mv(VP8mvbounds *s, VP56mv *dst, const VP56mv *src) { dst->x = av_clip(src->x, av_clip(s->mv_min.x, INT16_MIN, INT16_MAX), av_clip(s->mv_max.x, INT16_MIN, INT16_MAX)); dst->y = av_clip(src->y, av_clip(s->mv_min.y, INT16_MIN, INT16_MAX), av_clip(s->mv_max.y, INT16_MIN, INT16_MAX)); } /** * Motion vector coding, 17.1. */ static av_always_inline int read_mv_component(VP56RangeCoder *c, const uint8_t *p, int vp7) { int bit, x = 0; if (vp56_rac_get_prob_branchy(c, p[0])) { int i; for (i = 0; i < 3; i++) x += vp56_rac_get_prob(c, p[9 + i]) << i; for (i = (vp7 ? 7 : 9); i > 3; i--) x += vp56_rac_get_prob(c, p[9 + i]) << i; if (!(x & (vp7 ? 0xF0 : 0xFFF0)) || vp56_rac_get_prob(c, p[12])) x += 8; } else { // small_mvtree const uint8_t *ps = p + 2; bit = vp56_rac_get_prob(c, *ps); ps += 1 + 3 * bit; x += 4 * bit; bit = vp56_rac_get_prob(c, *ps); ps += 1 + bit; x += 2 * bit; x += vp56_rac_get_prob(c, *ps); } return (x && vp56_rac_get_prob(c, p[1])) ? -x : x; } static int vp7_read_mv_component(VP56RangeCoder *c, const uint8_t *p) { return read_mv_component(c, p, 1); } static int vp8_read_mv_component(VP56RangeCoder *c, const uint8_t *p) { return read_mv_component(c, p, 0); } static av_always_inline const uint8_t *get_submv_prob(uint32_t left, uint32_t top, int is_vp7) { if (is_vp7) return vp7_submv_prob; if (left == top) return vp8_submv_prob[4 - !!left]; if (!top) return vp8_submv_prob[2]; return vp8_submv_prob[1 - !!left]; } /** * Split motion vector prediction, 16.4. * @returns the number of motion vectors parsed (2, 4 or 16) */ static av_always_inline int decode_splitmvs(VP8Context *s, VP56RangeCoder *c, VP8Macroblock *mb, int layout, int is_vp7) { int part_idx; int n, num; VP8Macroblock *top_mb; VP8Macroblock *left_mb = &mb[-1]; const uint8_t *mbsplits_left = vp8_mbsplits[left_mb->partitioning]; const uint8_t *mbsplits_top, *mbsplits_cur, *firstidx; VP56mv *top_mv; VP56mv *left_mv = left_mb->bmv; VP56mv *cur_mv = mb->bmv; if (!layout) // layout is inlined, s->mb_layout is not top_mb = &mb[2]; else top_mb = &mb[-s->mb_width - 1]; mbsplits_top = vp8_mbsplits[top_mb->partitioning]; top_mv = top_mb->bmv; if (vp56_rac_get_prob_branchy(c, vp8_mbsplit_prob[0])) { if (vp56_rac_get_prob_branchy(c, vp8_mbsplit_prob[1])) part_idx = VP8_SPLITMVMODE_16x8 + vp56_rac_get_prob(c, vp8_mbsplit_prob[2]); else part_idx = VP8_SPLITMVMODE_8x8; } else { part_idx = VP8_SPLITMVMODE_4x4; } num = vp8_mbsplit_count[part_idx]; mbsplits_cur = vp8_mbsplits[part_idx], firstidx = vp8_mbfirstidx[part_idx]; mb->partitioning = part_idx; for (n = 0; n < num; n++) { int k = firstidx[n]; uint32_t left, above; const uint8_t *submv_prob; if (!(k & 3)) left = AV_RN32A(&left_mv[mbsplits_left[k + 3]]); else left = AV_RN32A(&cur_mv[mbsplits_cur[k - 1]]); if (k <= 3) above = AV_RN32A(&top_mv[mbsplits_top[k + 12]]); else above = AV_RN32A(&cur_mv[mbsplits_cur[k - 4]]); submv_prob = get_submv_prob(left, above, is_vp7); if (vp56_rac_get_prob_branchy(c, submv_prob[0])) { if (vp56_rac_get_prob_branchy(c, submv_prob[1])) { if (vp56_rac_get_prob_branchy(c, submv_prob[2])) { mb->bmv[n].y = mb->mv.y + read_mv_component(c, s->prob->mvc[0], is_vp7); mb->bmv[n].x = mb->mv.x + read_mv_component(c, s->prob->mvc[1], is_vp7); } else { AV_ZERO32(&mb->bmv[n]); } } else { AV_WN32A(&mb->bmv[n], above); } } else { AV_WN32A(&mb->bmv[n], left); } } return num; } /** * The vp7 reference decoder uses a padding macroblock column (added to right * edge of the frame) to guard against illegal macroblock offsets. The * algorithm has bugs that permit offsets to straddle the padding column. * This function replicates those bugs. * * @param[out] edge_x macroblock x address * @param[out] edge_y macroblock y address * * @return macroblock offset legal (boolean) */ static int vp7_calculate_mb_offset(int mb_x, int mb_y, int mb_width, int xoffset, int yoffset, int boundary, int *edge_x, int *edge_y) { int vwidth = mb_width + 1; int new = (mb_y + yoffset) * vwidth + mb_x + xoffset; if (new < boundary || new % vwidth == vwidth - 1) return 0; *edge_y = new / vwidth; *edge_x = new % vwidth; return 1; } static const VP56mv *get_bmv_ptr(const VP8Macroblock *mb, int subblock) { return &mb->bmv[mb->mode == VP8_MVMODE_SPLIT ? vp8_mbsplits[mb->partitioning][subblock] : 0]; } static av_always_inline void vp7_decode_mvs(VP8Context *s, VP8Macroblock *mb, int mb_x, int mb_y, int layout) { VP8Macroblock *mb_edge[12]; enum { CNT_ZERO, CNT_NEAREST, CNT_NEAR }; enum { VP8_EDGE_TOP, VP8_EDGE_LEFT, VP8_EDGE_TOPLEFT }; int idx = CNT_ZERO; VP56mv near_mv[3]; uint8_t cnt[3] = { 0 }; VP56RangeCoder *c = &s->c; int i; AV_ZERO32(&near_mv[0]); AV_ZERO32(&near_mv[1]); AV_ZERO32(&near_mv[2]); for (i = 0; i < VP7_MV_PRED_COUNT; i++) { const VP7MVPred * pred = &vp7_mv_pred[i]; int edge_x, edge_y; if (vp7_calculate_mb_offset(mb_x, mb_y, s->mb_width, pred->xoffset, pred->yoffset, !s->profile, &edge_x, &edge_y)) { VP8Macroblock *edge = mb_edge[i] = (s->mb_layout == 1) ? s->macroblocks_base + 1 + edge_x + (s->mb_width + 1) * (edge_y + 1) : s->macroblocks + edge_x + (s->mb_height - edge_y - 1) * 2; uint32_t mv = AV_RN32A(get_bmv_ptr(edge, vp7_mv_pred[i].subblock)); if (mv) { if (AV_RN32A(&near_mv[CNT_NEAREST])) { if (mv == AV_RN32A(&near_mv[CNT_NEAREST])) { idx = CNT_NEAREST; } else if (AV_RN32A(&near_mv[CNT_NEAR])) { if (mv != AV_RN32A(&near_mv[CNT_NEAR])) continue; idx = CNT_NEAR; } else { AV_WN32A(&near_mv[CNT_NEAR], mv); idx = CNT_NEAR; } } else { AV_WN32A(&near_mv[CNT_NEAREST], mv); idx = CNT_NEAREST; } } else { idx = CNT_ZERO; } } else { idx = CNT_ZERO; } cnt[idx] += vp7_mv_pred[i].score; } mb->partitioning = VP8_SPLITMVMODE_NONE; if (vp56_rac_get_prob_branchy(c, vp7_mode_contexts[cnt[CNT_ZERO]][0])) { mb->mode = VP8_MVMODE_MV; if (vp56_rac_get_prob_branchy(c, vp7_mode_contexts[cnt[CNT_NEAREST]][1])) { if (vp56_rac_get_prob_branchy(c, vp7_mode_contexts[cnt[CNT_NEAR]][2])) { if (cnt[CNT_NEAREST] > cnt[CNT_NEAR]) AV_WN32A(&mb->mv, cnt[CNT_ZERO] > cnt[CNT_NEAREST] ? 0 : AV_RN32A(&near_mv[CNT_NEAREST])); else AV_WN32A(&mb->mv, cnt[CNT_ZERO] > cnt[CNT_NEAR] ? 0 : AV_RN32A(&near_mv[CNT_NEAR])); if (vp56_rac_get_prob_branchy(c, vp7_mode_contexts[cnt[CNT_NEAR]][3])) { mb->mode = VP8_MVMODE_SPLIT; mb->mv = mb->bmv[decode_splitmvs(s, c, mb, layout, IS_VP7) - 1]; } else { mb->mv.y += vp7_read_mv_component(c, s->prob->mvc[0]); mb->mv.x += vp7_read_mv_component(c, s->prob->mvc[1]); mb->bmv[0] = mb->mv; } } else { mb->mv = near_mv[CNT_NEAR]; mb->bmv[0] = mb->mv; } } else { mb->mv = near_mv[CNT_NEAREST]; mb->bmv[0] = mb->mv; } } else { mb->mode = VP8_MVMODE_ZERO; AV_ZERO32(&mb->mv); mb->bmv[0] = mb->mv; } } static av_always_inline void vp8_decode_mvs(VP8Context *s, VP8mvbounds *mv_bounds, VP8Macroblock *mb, int mb_x, int mb_y, int layout) { VP8Macroblock *mb_edge[3] = { 0 /* top */, mb - 1 /* left */, 0 /* top-left */ }; enum { CNT_ZERO, CNT_NEAREST, CNT_NEAR, CNT_SPLITMV }; enum { VP8_EDGE_TOP, VP8_EDGE_LEFT, VP8_EDGE_TOPLEFT }; int idx = CNT_ZERO; int cur_sign_bias = s->sign_bias[mb->ref_frame]; int8_t *sign_bias = s->sign_bias; VP56mv near_mv[4]; uint8_t cnt[4] = { 0 }; VP56RangeCoder *c = &s->c; if (!layout) { // layout is inlined (s->mb_layout is not) mb_edge[0] = mb + 2; mb_edge[2] = mb + 1; } else { mb_edge[0] = mb - s->mb_width - 1; mb_edge[2] = mb - s->mb_width - 2; } AV_ZERO32(&near_mv[0]); AV_ZERO32(&near_mv[1]); AV_ZERO32(&near_mv[2]); /* Process MB on top, left and top-left */ #define MV_EDGE_CHECK(n) \ { \ VP8Macroblock *edge = mb_edge[n]; \ int edge_ref = edge->ref_frame; \ if (edge_ref != VP56_FRAME_CURRENT) { \ uint32_t mv = AV_RN32A(&edge->mv); \ if (mv) { \ if (cur_sign_bias != sign_bias[edge_ref]) { \ /* SWAR negate of the values in mv. */ \ mv = ~mv; \ mv = ((mv & 0x7fff7fff) + \ 0x00010001) ^ (mv & 0x80008000); \ } \ if (!n || mv != AV_RN32A(&near_mv[idx])) \ AV_WN32A(&near_mv[++idx], mv); \ cnt[idx] += 1 + (n != 2); \ } else \ cnt[CNT_ZERO] += 1 + (n != 2); \ } \ } MV_EDGE_CHECK(0) MV_EDGE_CHECK(1) MV_EDGE_CHECK(2) mb->partitioning = VP8_SPLITMVMODE_NONE; if (vp56_rac_get_prob_branchy(c, vp8_mode_contexts[cnt[CNT_ZERO]][0])) { mb->mode = VP8_MVMODE_MV; /* If we have three distinct MVs, merge first and last if they're the same */ if (cnt[CNT_SPLITMV] && AV_RN32A(&near_mv[1 + VP8_EDGE_TOP]) == AV_RN32A(&near_mv[1 + VP8_EDGE_TOPLEFT])) cnt[CNT_NEAREST] += 1; /* Swap near and nearest if necessary */ if (cnt[CNT_NEAR] > cnt[CNT_NEAREST]) { FFSWAP(uint8_t, cnt[CNT_NEAREST], cnt[CNT_NEAR]); FFSWAP( VP56mv, near_mv[CNT_NEAREST], near_mv[CNT_NEAR]); } if (vp56_rac_get_prob_branchy(c, vp8_mode_contexts[cnt[CNT_NEAREST]][1])) { if (vp56_rac_get_prob_branchy(c, vp8_mode_contexts[cnt[CNT_NEAR]][2])) { /* Choose the best mv out of 0,0 and the nearest mv */ clamp_mv(mv_bounds, &mb->mv, &near_mv[CNT_ZERO + (cnt[CNT_NEAREST] >= cnt[CNT_ZERO])]); cnt[CNT_SPLITMV] = ((mb_edge[VP8_EDGE_LEFT]->mode == VP8_MVMODE_SPLIT) + (mb_edge[VP8_EDGE_TOP]->mode == VP8_MVMODE_SPLIT)) * 2 + (mb_edge[VP8_EDGE_TOPLEFT]->mode == VP8_MVMODE_SPLIT); if (vp56_rac_get_prob_branchy(c, vp8_mode_contexts[cnt[CNT_SPLITMV]][3])) { mb->mode = VP8_MVMODE_SPLIT; mb->mv = mb->bmv[decode_splitmvs(s, c, mb, layout, IS_VP8) - 1]; } else { mb->mv.y += vp8_read_mv_component(c, s->prob->mvc[0]); mb->mv.x += vp8_read_mv_component(c, s->prob->mvc[1]); mb->bmv[0] = mb->mv; } } else { clamp_mv(mv_bounds, &mb->mv, &near_mv[CNT_NEAR]); mb->bmv[0] = mb->mv; } } else { clamp_mv(mv_bounds, &mb->mv, &near_mv[CNT_NEAREST]); mb->bmv[0] = mb->mv; } } else { mb->mode = VP8_MVMODE_ZERO; AV_ZERO32(&mb->mv); mb->bmv[0] = mb->mv; } } static av_always_inline void decode_intra4x4_modes(VP8Context *s, VP56RangeCoder *c, VP8Macroblock *mb, int mb_x, int keyframe, int layout) { uint8_t *intra4x4 = mb->intra4x4_pred_mode_mb; if (layout) { VP8Macroblock *mb_top = mb - s->mb_width - 1; memcpy(mb->intra4x4_pred_mode_top, mb_top->intra4x4_pred_mode_top, 4); } if (keyframe) { int x, y; uint8_t *top; uint8_t *const left = s->intra4x4_pred_mode_left; if (layout) top = mb->intra4x4_pred_mode_top; else top = s->intra4x4_pred_mode_top + 4 * mb_x; for (y = 0; y < 4; y++) { for (x = 0; x < 4; x++) { const uint8_t *ctx; ctx = vp8_pred4x4_prob_intra[top[x]][left[y]]; *intra4x4 = vp8_rac_get_tree(c, vp8_pred4x4_tree, ctx); left[y] = top[x] = *intra4x4; intra4x4++; } } } else { int i; for (i = 0; i < 16; i++) intra4x4[i] = vp8_rac_get_tree(c, vp8_pred4x4_tree, vp8_pred4x4_prob_inter); } } static av_always_inline void decode_mb_mode(VP8Context *s, VP8mvbounds *mv_bounds, VP8Macroblock *mb, int mb_x, int mb_y, uint8_t *segment, uint8_t *ref, int layout, int is_vp7) { VP56RangeCoder *c = &s->c; static const char *vp7_feature_name[] = { "q-index", "lf-delta", "partial-golden-update", "blit-pitch" }; if (is_vp7) { int i; *segment = 0; for (i = 0; i < 4; i++) { if (s->feature_enabled[i]) { if (vp56_rac_get_prob_branchy(c, s->feature_present_prob[i])) { int index = vp8_rac_get_tree(c, vp7_feature_index_tree, s->feature_index_prob[i]); av_log(s->avctx, AV_LOG_WARNING, "Feature %s present in macroblock (value 0x%x)\n", vp7_feature_name[i], s->feature_value[i][index]); } } } } else if (s->segmentation.update_map) { int bit = vp56_rac_get_prob(c, s->prob->segmentid[0]); *segment = vp56_rac_get_prob(c, s->prob->segmentid[1+bit]) + 2*bit; } else if (s->segmentation.enabled) *segment = ref ? *ref : *segment; mb->segment = *segment; mb->skip = s->mbskip_enabled ? vp56_rac_get_prob(c, s->prob->mbskip) : 0; if (s->keyframe) { mb->mode = vp8_rac_get_tree(c, vp8_pred16x16_tree_intra, vp8_pred16x16_prob_intra); if (mb->mode == MODE_I4x4) { decode_intra4x4_modes(s, c, mb, mb_x, 1, layout); } else { const uint32_t modes = (is_vp7 ? vp7_pred4x4_mode : vp8_pred4x4_mode)[mb->mode] * 0x01010101u; if (s->mb_layout) AV_WN32A(mb->intra4x4_pred_mode_top, modes); else AV_WN32A(s->intra4x4_pred_mode_top + 4 * mb_x, modes); AV_WN32A(s->intra4x4_pred_mode_left, modes); } mb->chroma_pred_mode = vp8_rac_get_tree(c, vp8_pred8x8c_tree, vp8_pred8x8c_prob_intra); mb->ref_frame = VP56_FRAME_CURRENT; } else if (vp56_rac_get_prob_branchy(c, s->prob->intra)) { // inter MB, 16.2 if (vp56_rac_get_prob_branchy(c, s->prob->last)) mb->ref_frame = (!is_vp7 && vp56_rac_get_prob(c, s->prob->golden)) ? VP56_FRAME_GOLDEN2 /* altref */ : VP56_FRAME_GOLDEN; else mb->ref_frame = VP56_FRAME_PREVIOUS; s->ref_count[mb->ref_frame - 1]++; // motion vectors, 16.3 if (is_vp7) vp7_decode_mvs(s, mb, mb_x, mb_y, layout); else vp8_decode_mvs(s, mv_bounds, mb, mb_x, mb_y, layout); } else { // intra MB, 16.1 mb->mode = vp8_rac_get_tree(c, vp8_pred16x16_tree_inter, s->prob->pred16x16); if (mb->mode == MODE_I4x4) decode_intra4x4_modes(s, c, mb, mb_x, 0, layout); mb->chroma_pred_mode = vp8_rac_get_tree(c, vp8_pred8x8c_tree, s->prob->pred8x8c); mb->ref_frame = VP56_FRAME_CURRENT; mb->partitioning = VP8_SPLITMVMODE_NONE; AV_ZERO32(&mb->bmv[0]); } } /** * @param r arithmetic bitstream reader context * @param block destination for block coefficients * @param probs probabilities to use when reading trees from the bitstream * @param i initial coeff index, 0 unless a separate DC block is coded * @param qmul array holding the dc/ac dequant factor at position 0/1 * * @return 0 if no coeffs were decoded * otherwise, the index of the last coeff decoded plus one */ static av_always_inline int decode_block_coeffs_internal(VP56RangeCoder *r, int16_t block[16], uint8_t probs[16][3][NUM_DCT_TOKENS - 1], int i, uint8_t *token_prob, int16_t qmul[2], const uint8_t scan[16], int vp7) { VP56RangeCoder c = *r; goto skip_eob; do { int coeff; restart: if (!vp56_rac_get_prob_branchy(&c, token_prob[0])) // DCT_EOB break; skip_eob: if (!vp56_rac_get_prob_branchy(&c, token_prob[1])) { // DCT_0 if (++i == 16) break; // invalid input; blocks should end with EOB token_prob = probs[i][0]; if (vp7) goto restart; goto skip_eob; } if (!vp56_rac_get_prob_branchy(&c, token_prob[2])) { // DCT_1 coeff = 1; token_prob = probs[i + 1][1]; } else { if (!vp56_rac_get_prob_branchy(&c, token_prob[3])) { // DCT 2,3,4 coeff = vp56_rac_get_prob_branchy(&c, token_prob[4]); if (coeff) coeff += vp56_rac_get_prob(&c, token_prob[5]); coeff += 2; } else { // DCT_CAT* if (!vp56_rac_get_prob_branchy(&c, token_prob[6])) { if (!vp56_rac_get_prob_branchy(&c, token_prob[7])) { // DCT_CAT1 coeff = 5 + vp56_rac_get_prob(&c, vp8_dct_cat1_prob[0]); } else { // DCT_CAT2 coeff = 7; coeff += vp56_rac_get_prob(&c, vp8_dct_cat2_prob[0]) << 1; coeff += vp56_rac_get_prob(&c, vp8_dct_cat2_prob[1]); } } else { // DCT_CAT3 and up int a = vp56_rac_get_prob(&c, token_prob[8]); int b = vp56_rac_get_prob(&c, token_prob[9 + a]); int cat = (a << 1) + b; coeff = 3 + (8 << cat); coeff += vp8_rac_get_coeff(&c, ff_vp8_dct_cat_prob[cat]); } } token_prob = probs[i + 1][2]; } block[scan[i]] = (vp8_rac_get(&c) ? -coeff : coeff) * qmul[!!i]; } while (++i < 16); *r = c; return i; } static av_always_inline int inter_predict_dc(int16_t block[16], int16_t pred[2]) { int16_t dc = block[0]; int ret = 0; if (pred[1] > 3) { dc += pred[0]; ret = 1; } if (!pred[0] | !dc | ((int32_t)pred[0] ^ (int32_t)dc) >> 31) { block[0] = pred[0] = dc; pred[1] = 0; } else { if (pred[0] == dc) pred[1]++; block[0] = pred[0] = dc; } return ret; } static int vp7_decode_block_coeffs_internal(VP56RangeCoder *r, int16_t block[16], uint8_t probs[16][3][NUM_DCT_TOKENS - 1], int i, uint8_t *token_prob, int16_t qmul[2], const uint8_t scan[16]) { return decode_block_coeffs_internal(r, block, probs, i, token_prob, qmul, scan, IS_VP7); } #ifndef vp8_decode_block_coeffs_internal static int vp8_decode_block_coeffs_internal(VP56RangeCoder *r, int16_t block[16], uint8_t probs[16][3][NUM_DCT_TOKENS - 1], int i, uint8_t *token_prob, int16_t qmul[2]) { return decode_block_coeffs_internal(r, block, probs, i, token_prob, qmul, ff_zigzag_scan, IS_VP8); } #endif /** * @param c arithmetic bitstream reader context * @param block destination for block coefficients * @param probs probabilities to use when reading trees from the bitstream * @param i initial coeff index, 0 unless a separate DC block is coded * @param zero_nhood the initial prediction context for number of surrounding * all-zero blocks (only left/top, so 0-2) * @param qmul array holding the dc/ac dequant factor at position 0/1 * @param scan scan pattern (VP7 only) * * @return 0 if no coeffs were decoded * otherwise, the index of the last coeff decoded plus one */ static av_always_inline int decode_block_coeffs(VP56RangeCoder *c, int16_t block[16], uint8_t probs[16][3][NUM_DCT_TOKENS - 1], int i, int zero_nhood, int16_t qmul[2], const uint8_t scan[16], int vp7) { uint8_t *token_prob = probs[i][zero_nhood]; if (!vp56_rac_get_prob_branchy(c, token_prob[0])) // DCT_EOB return 0; return vp7 ? vp7_decode_block_coeffs_internal(c, block, probs, i, token_prob, qmul, scan) : vp8_decode_block_coeffs_internal(c, block, probs, i, token_prob, qmul); } static av_always_inline void decode_mb_coeffs(VP8Context *s, VP8ThreadData *td, VP56RangeCoder *c, VP8Macroblock *mb, uint8_t t_nnz[9], uint8_t l_nnz[9], int is_vp7) { int i, x, y, luma_start = 0, luma_ctx = 3; int nnz_pred, nnz, nnz_total = 0; int segment = mb->segment; int block_dc = 0; if (mb->mode != MODE_I4x4 && (is_vp7 || mb->mode != VP8_MVMODE_SPLIT)) { nnz_pred = t_nnz[8] + l_nnz[8]; // decode DC values and do hadamard nnz = decode_block_coeffs(c, td->block_dc, s->prob->token[1], 0, nnz_pred, s->qmat[segment].luma_dc_qmul, ff_zigzag_scan, is_vp7); l_nnz[8] = t_nnz[8] = !!nnz; if (is_vp7 && mb->mode > MODE_I4x4) { nnz |= inter_predict_dc(td->block_dc, s->inter_dc_pred[mb->ref_frame - 1]); } if (nnz) { nnz_total += nnz; block_dc = 1; if (nnz == 1) s->vp8dsp.vp8_luma_dc_wht_dc(td->block, td->block_dc); else s->vp8dsp.vp8_luma_dc_wht(td->block, td->block_dc); } luma_start = 1; luma_ctx = 0; } // luma blocks for (y = 0; y < 4; y++) for (x = 0; x < 4; x++) { nnz_pred = l_nnz[y] + t_nnz[x]; nnz = decode_block_coeffs(c, td->block[y][x], s->prob->token[luma_ctx], luma_start, nnz_pred, s->qmat[segment].luma_qmul, s->prob[0].scan, is_vp7); /* nnz+block_dc may be one more than the actual last index, * but we don't care */ td->non_zero_count_cache[y][x] = nnz + block_dc; t_nnz[x] = l_nnz[y] = !!nnz; nnz_total += nnz; } // chroma blocks // TODO: what to do about dimensions? 2nd dim for luma is x, // but for chroma it's (y<<1)|x for (i = 4; i < 6; i++) for (y = 0; y < 2; y++) for (x = 0; x < 2; x++) { nnz_pred = l_nnz[i + 2 * y] + t_nnz[i + 2 * x]; nnz = decode_block_coeffs(c, td->block[i][(y << 1) + x], s->prob->token[2], 0, nnz_pred, s->qmat[segment].chroma_qmul, s->prob[0].scan, is_vp7); td->non_zero_count_cache[i][(y << 1) + x] = nnz; t_nnz[i + 2 * x] = l_nnz[i + 2 * y] = !!nnz; nnz_total += nnz; } // if there were no coded coeffs despite the macroblock not being marked skip, // we MUST not do the inner loop filter and should not do IDCT // Since skip isn't used for bitstream prediction, just manually set it. if (!nnz_total) mb->skip = 1; } static av_always_inline void backup_mb_border(uint8_t *top_border, uint8_t *src_y, uint8_t *src_cb, uint8_t *src_cr, ptrdiff_t linesize, ptrdiff_t uvlinesize, int simple) { AV_COPY128(top_border, src_y + 15 * linesize); if (!simple) { AV_COPY64(top_border + 16, src_cb + 7 * uvlinesize); AV_COPY64(top_border + 24, src_cr + 7 * uvlinesize); } } static av_always_inline void xchg_mb_border(uint8_t *top_border, uint8_t *src_y, uint8_t *src_cb, uint8_t *src_cr, ptrdiff_t linesize, ptrdiff_t uvlinesize, int mb_x, int mb_y, int mb_width, int simple, int xchg) { uint8_t *top_border_m1 = top_border - 32; // for TL prediction src_y -= linesize; src_cb -= uvlinesize; src_cr -= uvlinesize; #define XCHG(a, b, xchg) \ do { \ if (xchg) \ AV_SWAP64(b, a); \ else \ AV_COPY64(b, a); \ } while (0) XCHG(top_border_m1 + 8, src_y - 8, xchg); XCHG(top_border, src_y, xchg); XCHG(top_border + 8, src_y + 8, 1); if (mb_x < mb_width - 1) XCHG(top_border + 32, src_y + 16, 1); // only copy chroma for normal loop filter // or to initialize the top row to 127 if (!simple || !mb_y) { XCHG(top_border_m1 + 16, src_cb - 8, xchg); XCHG(top_border_m1 + 24, src_cr - 8, xchg); XCHG(top_border + 16, src_cb, 1); XCHG(top_border + 24, src_cr, 1); } } static av_always_inline int check_dc_pred8x8_mode(int mode, int mb_x, int mb_y) { if (!mb_x) return mb_y ? TOP_DC_PRED8x8 : DC_128_PRED8x8; else return mb_y ? mode : LEFT_DC_PRED8x8; } static av_always_inline int check_tm_pred8x8_mode(int mode, int mb_x, int mb_y, int vp7) { if (!mb_x) return mb_y ? VERT_PRED8x8 : (vp7 ? DC_128_PRED8x8 : DC_129_PRED8x8); else return mb_y ? mode : HOR_PRED8x8; } static av_always_inline int check_intra_pred8x8_mode_emuedge(int mode, int mb_x, int mb_y, int vp7) { switch (mode) { case DC_PRED8x8: return check_dc_pred8x8_mode(mode, mb_x, mb_y); case VERT_PRED8x8: return !mb_y ? (vp7 ? DC_128_PRED8x8 : DC_127_PRED8x8) : mode; case HOR_PRED8x8: return !mb_x ? (vp7 ? DC_128_PRED8x8 : DC_129_PRED8x8) : mode; case PLANE_PRED8x8: /* TM */ return check_tm_pred8x8_mode(mode, mb_x, mb_y, vp7); } return mode; } static av_always_inline int check_tm_pred4x4_mode(int mode, int mb_x, int mb_y, int vp7) { if (!mb_x) { return mb_y ? VERT_VP8_PRED : (vp7 ? DC_128_PRED : DC_129_PRED); } else { return mb_y ? mode : HOR_VP8_PRED; } } static av_always_inline int check_intra_pred4x4_mode_emuedge(int mode, int mb_x, int mb_y, int *copy_buf, int vp7) { switch (mode) { case VERT_PRED: if (!mb_x && mb_y) { *copy_buf = 1; return mode; } /* fall-through */ case DIAG_DOWN_LEFT_PRED: case VERT_LEFT_PRED: return !mb_y ? (vp7 ? DC_128_PRED : DC_127_PRED) : mode; case HOR_PRED: if (!mb_y) { *copy_buf = 1; return mode; } /* fall-through */ case HOR_UP_PRED: return !mb_x ? (vp7 ? DC_128_PRED : DC_129_PRED) : mode; case TM_VP8_PRED: return check_tm_pred4x4_mode(mode, mb_x, mb_y, vp7); case DC_PRED: /* 4x4 DC doesn't use the same "H.264-style" exceptions * as 16x16/8x8 DC */ case DIAG_DOWN_RIGHT_PRED: case VERT_RIGHT_PRED: case HOR_DOWN_PRED: if (!mb_y || !mb_x) *copy_buf = 1; return mode; } return mode; } static av_always_inline void intra_predict(VP8Context *s, VP8ThreadData *td, uint8_t *dst[3], VP8Macroblock *mb, int mb_x, int mb_y, int is_vp7) { int x, y, mode, nnz; uint32_t tr; /* for the first row, we need to run xchg_mb_border to init the top edge * to 127 otherwise, skip it if we aren't going to deblock */ if (mb_y && (s->deblock_filter || !mb_y) && td->thread_nr == 0) xchg_mb_border(s->top_border[mb_x + 1], dst[0], dst[1], dst[2], s->linesize, s->uvlinesize, mb_x, mb_y, s->mb_width, s->filter.simple, 1); if (mb->mode < MODE_I4x4) { mode = check_intra_pred8x8_mode_emuedge(mb->mode, mb_x, mb_y, is_vp7); s->hpc.pred16x16[mode](dst[0], s->linesize); } else { uint8_t *ptr = dst[0]; uint8_t *intra4x4 = mb->intra4x4_pred_mode_mb; const uint8_t lo = is_vp7 ? 128 : 127; const uint8_t hi = is_vp7 ? 128 : 129; uint8_t tr_top[4] = { lo, lo, lo, lo }; // all blocks on the right edge of the macroblock use bottom edge // the top macroblock for their topright edge uint8_t *tr_right = ptr - s->linesize + 16; // if we're on the right edge of the frame, said edge is extended // from the top macroblock if (mb_y && mb_x == s->mb_width - 1) { tr = tr_right[-1] * 0x01010101u; tr_right = (uint8_t *) &tr; } if (mb->skip) AV_ZERO128(td->non_zero_count_cache); for (y = 0; y < 4; y++) { uint8_t *topright = ptr + 4 - s->linesize; for (x = 0; x < 4; x++) { int copy = 0; ptrdiff_t linesize = s->linesize; uint8_t *dst = ptr + 4 * x; LOCAL_ALIGNED(4, uint8_t, copy_dst, [5 * 8]); if ((y == 0 || x == 3) && mb_y == 0) { topright = tr_top; } else if (x == 3) topright = tr_right; mode = check_intra_pred4x4_mode_emuedge(intra4x4[x], mb_x + x, mb_y + y, &copy, is_vp7); if (copy) { dst = copy_dst + 12; linesize = 8; if (!(mb_y + y)) { copy_dst[3] = lo; AV_WN32A(copy_dst + 4, lo * 0x01010101U); } else { AV_COPY32(copy_dst + 4, ptr + 4 * x - s->linesize); if (!(mb_x + x)) { copy_dst[3] = hi; } else { copy_dst[3] = ptr[4 * x - s->linesize - 1]; } } if (!(mb_x + x)) { copy_dst[11] = copy_dst[19] = copy_dst[27] = copy_dst[35] = hi; } else { copy_dst[11] = ptr[4 * x - 1]; copy_dst[19] = ptr[4 * x + s->linesize - 1]; copy_dst[27] = ptr[4 * x + s->linesize * 2 - 1]; copy_dst[35] = ptr[4 * x + s->linesize * 3 - 1]; } } s->hpc.pred4x4[mode](dst, topright, linesize); if (copy) { AV_COPY32(ptr + 4 * x, copy_dst + 12); AV_COPY32(ptr + 4 * x + s->linesize, copy_dst + 20); AV_COPY32(ptr + 4 * x + s->linesize * 2, copy_dst + 28); AV_COPY32(ptr + 4 * x + s->linesize * 3, copy_dst + 36); } nnz = td->non_zero_count_cache[y][x]; if (nnz) { if (nnz == 1) s->vp8dsp.vp8_idct_dc_add(ptr + 4 * x, td->block[y][x], s->linesize); else s->vp8dsp.vp8_idct_add(ptr + 4 * x, td->block[y][x], s->linesize); } topright += 4; } ptr += 4 * s->linesize; intra4x4 += 4; } } mode = check_intra_pred8x8_mode_emuedge(mb->chroma_pred_mode, mb_x, mb_y, is_vp7); s->hpc.pred8x8[mode](dst[1], s->uvlinesize); s->hpc.pred8x8[mode](dst[2], s->uvlinesize); if (mb_y && (s->deblock_filter || !mb_y) && td->thread_nr == 0) xchg_mb_border(s->top_border[mb_x + 1], dst[0], dst[1], dst[2], s->linesize, s->uvlinesize, mb_x, mb_y, s->mb_width, s->filter.simple, 0); } static const uint8_t subpel_idx[3][8] = { { 0, 1, 2, 1, 2, 1, 2, 1 }, // nr. of left extra pixels, // also function pointer index { 0, 3, 5, 3, 5, 3, 5, 3 }, // nr. of extra pixels required { 0, 2, 3, 2, 3, 2, 3, 2 }, // nr. of right extra pixels }; /** * luma MC function * * @param s VP8 decoding context * @param dst target buffer for block data at block position * @param ref reference picture buffer at origin (0, 0) * @param mv motion vector (relative to block position) to get pixel data from * @param x_off horizontal position of block from origin (0, 0) * @param y_off vertical position of block from origin (0, 0) * @param block_w width of block (16, 8 or 4) * @param block_h height of block (always same as block_w) * @param width width of src/dst plane data * @param height height of src/dst plane data * @param linesize size of a single line of plane data, including padding * @param mc_func motion compensation function pointers (bilinear or sixtap MC) */ static av_always_inline void vp8_mc_luma(VP8Context *s, VP8ThreadData *td, uint8_t *dst, ThreadFrame *ref, const VP56mv *mv, int x_off, int y_off, int block_w, int block_h, int width, int height, ptrdiff_t linesize, vp8_mc_func mc_func[3][3]) { uint8_t *src = ref->f->data[0]; if (AV_RN32A(mv)) { ptrdiff_t src_linesize = linesize; int mx = (mv->x * 2) & 7, mx_idx = subpel_idx[0][mx]; int my = (mv->y * 2) & 7, my_idx = subpel_idx[0][my]; x_off += mv->x >> 2; y_off += mv->y >> 2; // edge emulation ff_thread_await_progress(ref, (3 + y_off + block_h + subpel_idx[2][my]) >> 4, 0); src += y_off * linesize + x_off; if (x_off < mx_idx || x_off >= width - block_w - subpel_idx[2][mx] || y_off < my_idx || y_off >= height - block_h - subpel_idx[2][my]) { s->vdsp.emulated_edge_mc(td->edge_emu_buffer, src - my_idx * linesize - mx_idx, EDGE_EMU_LINESIZE, linesize, block_w + subpel_idx[1][mx], block_h + subpel_idx[1][my], x_off - mx_idx, y_off - my_idx, width, height); src = td->edge_emu_buffer + mx_idx + EDGE_EMU_LINESIZE * my_idx; src_linesize = EDGE_EMU_LINESIZE; } mc_func[my_idx][mx_idx](dst, linesize, src, src_linesize, block_h, mx, my); } else { ff_thread_await_progress(ref, (3 + y_off + block_h) >> 4, 0); mc_func[0][0](dst, linesize, src + y_off * linesize + x_off, linesize, block_h, 0, 0); } } /** * chroma MC function * * @param s VP8 decoding context * @param dst1 target buffer for block data at block position (U plane) * @param dst2 target buffer for block data at block position (V plane) * @param ref reference picture buffer at origin (0, 0) * @param mv motion vector (relative to block position) to get pixel data from * @param x_off horizontal position of block from origin (0, 0) * @param y_off vertical position of block from origin (0, 0) * @param block_w width of block (16, 8 or 4) * @param block_h height of block (always same as block_w) * @param width width of src/dst plane data * @param height height of src/dst plane data * @param linesize size of a single line of plane data, including padding * @param mc_func motion compensation function pointers (bilinear or sixtap MC) */ static av_always_inline void vp8_mc_chroma(VP8Context *s, VP8ThreadData *td, uint8_t *dst1, uint8_t *dst2, ThreadFrame *ref, const VP56mv *mv, int x_off, int y_off, int block_w, int block_h, int width, int height, ptrdiff_t linesize, vp8_mc_func mc_func[3][3]) { uint8_t *src1 = ref->f->data[1], *src2 = ref->f->data[2]; if (AV_RN32A(mv)) { int mx = mv->x & 7, mx_idx = subpel_idx[0][mx]; int my = mv->y & 7, my_idx = subpel_idx[0][my]; x_off += mv->x >> 3; y_off += mv->y >> 3; // edge emulation src1 += y_off * linesize + x_off; src2 += y_off * linesize + x_off; ff_thread_await_progress(ref, (3 + y_off + block_h + subpel_idx[2][my]) >> 3, 0); if (x_off < mx_idx || x_off >= width - block_w - subpel_idx[2][mx] || y_off < my_idx || y_off >= height - block_h - subpel_idx[2][my]) { s->vdsp.emulated_edge_mc(td->edge_emu_buffer, src1 - my_idx * linesize - mx_idx, EDGE_EMU_LINESIZE, linesize, block_w + subpel_idx[1][mx], block_h + subpel_idx[1][my], x_off - mx_idx, y_off - my_idx, width, height); src1 = td->edge_emu_buffer + mx_idx + EDGE_EMU_LINESIZE * my_idx; mc_func[my_idx][mx_idx](dst1, linesize, src1, EDGE_EMU_LINESIZE, block_h, mx, my); s->vdsp.emulated_edge_mc(td->edge_emu_buffer, src2 - my_idx * linesize - mx_idx, EDGE_EMU_LINESIZE, linesize, block_w + subpel_idx[1][mx], block_h + subpel_idx[1][my], x_off - mx_idx, y_off - my_idx, width, height); src2 = td->edge_emu_buffer + mx_idx + EDGE_EMU_LINESIZE * my_idx; mc_func[my_idx][mx_idx](dst2, linesize, src2, EDGE_EMU_LINESIZE, block_h, mx, my); } else { mc_func[my_idx][mx_idx](dst1, linesize, src1, linesize, block_h, mx, my); mc_func[my_idx][mx_idx](dst2, linesize, src2, linesize, block_h, mx, my); } } else { ff_thread_await_progress(ref, (3 + y_off + block_h) >> 3, 0); mc_func[0][0](dst1, linesize, src1 + y_off * linesize + x_off, linesize, block_h, 0, 0); mc_func[0][0](dst2, linesize, src2 + y_off * linesize + x_off, linesize, block_h, 0, 0); } } static av_always_inline void vp8_mc_part(VP8Context *s, VP8ThreadData *td, uint8_t *dst[3], ThreadFrame *ref_frame, int x_off, int y_off, int bx_off, int by_off, int block_w, int block_h, int width, int height, VP56mv *mv) { VP56mv uvmv = *mv; /* Y */ vp8_mc_luma(s, td, dst[0] + by_off * s->linesize + bx_off, ref_frame, mv, x_off + bx_off, y_off + by_off, block_w, block_h, width, height, s->linesize, s->put_pixels_tab[block_w == 8]); /* U/V */ if (s->profile == 3) { /* this block only applies VP8; it is safe to check * only the profile, as VP7 profile <= 1 */ uvmv.x &= ~7; uvmv.y &= ~7; } x_off >>= 1; y_off >>= 1; bx_off >>= 1; by_off >>= 1; width >>= 1; height >>= 1; block_w >>= 1; block_h >>= 1; vp8_mc_chroma(s, td, dst[1] + by_off * s->uvlinesize + bx_off, dst[2] + by_off * s->uvlinesize + bx_off, ref_frame, &uvmv, x_off + bx_off, y_off + by_off, block_w, block_h, width, height, s->uvlinesize, s->put_pixels_tab[1 + (block_w == 4)]); } /* Fetch pixels for estimated mv 4 macroblocks ahead. * Optimized for 64-byte cache lines. Inspired by ffh264 prefetch_motion. */ static av_always_inline void prefetch_motion(VP8Context *s, VP8Macroblock *mb, int mb_x, int mb_y, int mb_xy, int ref) { /* Don't prefetch refs that haven't been used very often this frame. */ if (s->ref_count[ref - 1] > (mb_xy >> 5)) { int x_off = mb_x << 4, y_off = mb_y << 4; int mx = (mb->mv.x >> 2) + x_off + 8; int my = (mb->mv.y >> 2) + y_off; uint8_t **src = s->framep[ref]->tf.f->data; int off = mx + (my + (mb_x & 3) * 4) * s->linesize + 64; /* For threading, a ff_thread_await_progress here might be useful, but * it actually slows down the decoder. Since a bad prefetch doesn't * generate bad decoder output, we don't run it here. */ s->vdsp.prefetch(src[0] + off, s->linesize, 4); off = (mx >> 1) + ((my >> 1) + (mb_x & 7)) * s->uvlinesize + 64; s->vdsp.prefetch(src[1] + off, src[2] - src[1], 2); } } /** * Apply motion vectors to prediction buffer, chapter 18. */ static av_always_inline void inter_predict(VP8Context *s, VP8ThreadData *td, uint8_t *dst[3], VP8Macroblock *mb, int mb_x, int mb_y) { int x_off = mb_x << 4, y_off = mb_y << 4; int width = 16 * s->mb_width, height = 16 * s->mb_height; ThreadFrame *ref = &s->framep[mb->ref_frame]->tf; VP56mv *bmv = mb->bmv; switch (mb->partitioning) { case VP8_SPLITMVMODE_NONE: vp8_mc_part(s, td, dst, ref, x_off, y_off, 0, 0, 16, 16, width, height, &mb->mv); break; case VP8_SPLITMVMODE_4x4: { int x, y; VP56mv uvmv; /* Y */ for (y = 0; y < 4; y++) { for (x = 0; x < 4; x++) { vp8_mc_luma(s, td, dst[0] + 4 * y * s->linesize + x * 4, ref, &bmv[4 * y + x], 4 * x + x_off, 4 * y + y_off, 4, 4, width, height, s->linesize, s->put_pixels_tab[2]); } } /* U/V */ x_off >>= 1; y_off >>= 1; width >>= 1; height >>= 1; for (y = 0; y < 2; y++) { for (x = 0; x < 2; x++) { uvmv.x = mb->bmv[2 * y * 4 + 2 * x ].x + mb->bmv[2 * y * 4 + 2 * x + 1].x + mb->bmv[(2 * y + 1) * 4 + 2 * x ].x + mb->bmv[(2 * y + 1) * 4 + 2 * x + 1].x; uvmv.y = mb->bmv[2 * y * 4 + 2 * x ].y + mb->bmv[2 * y * 4 + 2 * x + 1].y + mb->bmv[(2 * y + 1) * 4 + 2 * x ].y + mb->bmv[(2 * y + 1) * 4 + 2 * x + 1].y; uvmv.x = (uvmv.x + 2 + FF_SIGNBIT(uvmv.x)) >> 2; uvmv.y = (uvmv.y + 2 + FF_SIGNBIT(uvmv.y)) >> 2; if (s->profile == 3) { uvmv.x &= ~7; uvmv.y &= ~7; } vp8_mc_chroma(s, td, dst[1] + 4 * y * s->uvlinesize + x * 4, dst[2] + 4 * y * s->uvlinesize + x * 4, ref, &uvmv, 4 * x + x_off, 4 * y + y_off, 4, 4, width, height, s->uvlinesize, s->put_pixels_tab[2]); } } break; } case VP8_SPLITMVMODE_16x8: vp8_mc_part(s, td, dst, ref, x_off, y_off, 0, 0, 16, 8, width, height, &bmv[0]); vp8_mc_part(s, td, dst, ref, x_off, y_off, 0, 8, 16, 8, width, height, &bmv[1]); break; case VP8_SPLITMVMODE_8x16: vp8_mc_part(s, td, dst, ref, x_off, y_off, 0, 0, 8, 16, width, height, &bmv[0]); vp8_mc_part(s, td, dst, ref, x_off, y_off, 8, 0, 8, 16, width, height, &bmv[1]); break; case VP8_SPLITMVMODE_8x8: vp8_mc_part(s, td, dst, ref, x_off, y_off, 0, 0, 8, 8, width, height, &bmv[0]); vp8_mc_part(s, td, dst, ref, x_off, y_off, 8, 0, 8, 8, width, height, &bmv[1]); vp8_mc_part(s, td, dst, ref, x_off, y_off, 0, 8, 8, 8, width, height, &bmv[2]); vp8_mc_part(s, td, dst, ref, x_off, y_off, 8, 8, 8, 8, width, height, &bmv[3]); break; } } static av_always_inline void idct_mb(VP8Context *s, VP8ThreadData *td, uint8_t *dst[3], VP8Macroblock *mb) { int x, y, ch; if (mb->mode != MODE_I4x4) { uint8_t *y_dst = dst[0]; for (y = 0; y < 4; y++) { uint32_t nnz4 = AV_RL32(td->non_zero_count_cache[y]); if (nnz4) { if (nnz4 & ~0x01010101) { for (x = 0; x < 4; x++) { if ((uint8_t) nnz4 == 1) s->vp8dsp.vp8_idct_dc_add(y_dst + 4 * x, td->block[y][x], s->linesize); else if ((uint8_t) nnz4 > 1) s->vp8dsp.vp8_idct_add(y_dst + 4 * x, td->block[y][x], s->linesize); nnz4 >>= 8; if (!nnz4) break; } } else { s->vp8dsp.vp8_idct_dc_add4y(y_dst, td->block[y], s->linesize); } } y_dst += 4 * s->linesize; } } for (ch = 0; ch < 2; ch++) { uint32_t nnz4 = AV_RL32(td->non_zero_count_cache[4 + ch]); if (nnz4) { uint8_t *ch_dst = dst[1 + ch]; if (nnz4 & ~0x01010101) { for (y = 0; y < 2; y++) { for (x = 0; x < 2; x++) { if ((uint8_t) nnz4 == 1) s->vp8dsp.vp8_idct_dc_add(ch_dst + 4 * x, td->block[4 + ch][(y << 1) + x], s->uvlinesize); else if ((uint8_t) nnz4 > 1) s->vp8dsp.vp8_idct_add(ch_dst + 4 * x, td->block[4 + ch][(y << 1) + x], s->uvlinesize); nnz4 >>= 8; if (!nnz4) goto chroma_idct_end; } ch_dst += 4 * s->uvlinesize; } } else { s->vp8dsp.vp8_idct_dc_add4uv(ch_dst, td->block[4 + ch], s->uvlinesize); } } chroma_idct_end: ; } } static av_always_inline void filter_level_for_mb(VP8Context *s, VP8Macroblock *mb, VP8FilterStrength *f, int is_vp7) { int interior_limit, filter_level; if (s->segmentation.enabled) { filter_level = s->segmentation.filter_level[mb->segment]; if (!s->segmentation.absolute_vals) filter_level += s->filter.level; } else filter_level = s->filter.level; if (s->lf_delta.enabled) { filter_level += s->lf_delta.ref[mb->ref_frame]; filter_level += s->lf_delta.mode[mb->mode]; } filter_level = av_clip_uintp2(filter_level, 6); interior_limit = filter_level; if (s->filter.sharpness) { interior_limit >>= (s->filter.sharpness + 3) >> 2; interior_limit = FFMIN(interior_limit, 9 - s->filter.sharpness); } interior_limit = FFMAX(interior_limit, 1); f->filter_level = filter_level; f->inner_limit = interior_limit; f->inner_filter = is_vp7 || !mb->skip || mb->mode == MODE_I4x4 || mb->mode == VP8_MVMODE_SPLIT; } static av_always_inline void filter_mb(VP8Context *s, uint8_t *dst[3], VP8FilterStrength *f, int mb_x, int mb_y, int is_vp7) { int mbedge_lim, bedge_lim_y, bedge_lim_uv, hev_thresh; int filter_level = f->filter_level; int inner_limit = f->inner_limit; int inner_filter = f->inner_filter; ptrdiff_t linesize = s->linesize; ptrdiff_t uvlinesize = s->uvlinesize; static const uint8_t hev_thresh_lut[2][64] = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 } }; if (!filter_level) return; if (is_vp7) { bedge_lim_y = filter_level; bedge_lim_uv = filter_level * 2; mbedge_lim = filter_level + 2; } else { bedge_lim_y = bedge_lim_uv = filter_level * 2 + inner_limit; mbedge_lim = bedge_lim_y + 4; } hev_thresh = hev_thresh_lut[s->keyframe][filter_level]; if (mb_x) { s->vp8dsp.vp8_h_loop_filter16y(dst[0], linesize, mbedge_lim, inner_limit, hev_thresh); s->vp8dsp.vp8_h_loop_filter8uv(dst[1], dst[2], uvlinesize, mbedge_lim, inner_limit, hev_thresh); } #define H_LOOP_FILTER_16Y_INNER(cond) \ if (cond && inner_filter) { \ s->vp8dsp.vp8_h_loop_filter16y_inner(dst[0] + 4, linesize, \ bedge_lim_y, inner_limit, \ hev_thresh); \ s->vp8dsp.vp8_h_loop_filter16y_inner(dst[0] + 8, linesize, \ bedge_lim_y, inner_limit, \ hev_thresh); \ s->vp8dsp.vp8_h_loop_filter16y_inner(dst[0] + 12, linesize, \ bedge_lim_y, inner_limit, \ hev_thresh); \ s->vp8dsp.vp8_h_loop_filter8uv_inner(dst[1] + 4, dst[2] + 4, \ uvlinesize, bedge_lim_uv, \ inner_limit, hev_thresh); \ } H_LOOP_FILTER_16Y_INNER(!is_vp7) if (mb_y) { s->vp8dsp.vp8_v_loop_filter16y(dst[0], linesize, mbedge_lim, inner_limit, hev_thresh); s->vp8dsp.vp8_v_loop_filter8uv(dst[1], dst[2], uvlinesize, mbedge_lim, inner_limit, hev_thresh); } if (inner_filter) { s->vp8dsp.vp8_v_loop_filter16y_inner(dst[0] + 4 * linesize, linesize, bedge_lim_y, inner_limit, hev_thresh); s->vp8dsp.vp8_v_loop_filter16y_inner(dst[0] + 8 * linesize, linesize, bedge_lim_y, inner_limit, hev_thresh); s->vp8dsp.vp8_v_loop_filter16y_inner(dst[0] + 12 * linesize, linesize, bedge_lim_y, inner_limit, hev_thresh); s->vp8dsp.vp8_v_loop_filter8uv_inner(dst[1] + 4 * uvlinesize, dst[2] + 4 * uvlinesize, uvlinesize, bedge_lim_uv, inner_limit, hev_thresh); } H_LOOP_FILTER_16Y_INNER(is_vp7) } static av_always_inline void filter_mb_simple(VP8Context *s, uint8_t *dst, VP8FilterStrength *f, int mb_x, int mb_y) { int mbedge_lim, bedge_lim; int filter_level = f->filter_level; int inner_limit = f->inner_limit; int inner_filter = f->inner_filter; ptrdiff_t linesize = s->linesize; if (!filter_level) return; bedge_lim = 2 * filter_level + inner_limit; mbedge_lim = bedge_lim + 4; if (mb_x) s->vp8dsp.vp8_h_loop_filter_simple(dst, linesize, mbedge_lim); if (inner_filter) { s->vp8dsp.vp8_h_loop_filter_simple(dst + 4, linesize, bedge_lim); s->vp8dsp.vp8_h_loop_filter_simple(dst + 8, linesize, bedge_lim); s->vp8dsp.vp8_h_loop_filter_simple(dst + 12, linesize, bedge_lim); } if (mb_y) s->vp8dsp.vp8_v_loop_filter_simple(dst, linesize, mbedge_lim); if (inner_filter) { s->vp8dsp.vp8_v_loop_filter_simple(dst + 4 * linesize, linesize, bedge_lim); s->vp8dsp.vp8_v_loop_filter_simple(dst + 8 * linesize, linesize, bedge_lim); s->vp8dsp.vp8_v_loop_filter_simple(dst + 12 * linesize, linesize, bedge_lim); } } #define MARGIN (16 << 2) static av_always_inline void vp78_decode_mv_mb_modes(AVCodecContext *avctx, VP8Frame *curframe, VP8Frame *prev_frame, int is_vp7) { VP8Context *s = avctx->priv_data; int mb_x, mb_y; s->mv_bounds.mv_min.y = -MARGIN; s->mv_bounds.mv_max.y = ((s->mb_height - 1) << 6) + MARGIN; for (mb_y = 0; mb_y < s->mb_height; mb_y++) { VP8Macroblock *mb = s->macroblocks_base + ((s->mb_width + 1) * (mb_y + 1) + 1); int mb_xy = mb_y * s->mb_width; AV_WN32A(s->intra4x4_pred_mode_left, DC_PRED * 0x01010101); s->mv_bounds.mv_min.x = -MARGIN; s->mv_bounds.mv_max.x = ((s->mb_width - 1) << 6) + MARGIN; for (mb_x = 0; mb_x < s->mb_width; mb_x++, mb_xy++, mb++) { if (mb_y == 0) AV_WN32A((mb - s->mb_width - 1)->intra4x4_pred_mode_top, DC_PRED * 0x01010101); decode_mb_mode(s, &s->mv_bounds, mb, mb_x, mb_y, curframe->seg_map->data + mb_xy, prev_frame && prev_frame->seg_map ? prev_frame->seg_map->data + mb_xy : NULL, 1, is_vp7); s->mv_bounds.mv_min.x -= 64; s->mv_bounds.mv_max.x -= 64; } s->mv_bounds.mv_min.y -= 64; s->mv_bounds.mv_max.y -= 64; } } static void vp7_decode_mv_mb_modes(AVCodecContext *avctx, VP8Frame *cur_frame, VP8Frame *prev_frame) { vp78_decode_mv_mb_modes(avctx, cur_frame, prev_frame, IS_VP7); } static void vp8_decode_mv_mb_modes(AVCodecContext *avctx, VP8Frame *cur_frame, VP8Frame *prev_frame) { vp78_decode_mv_mb_modes(avctx, cur_frame, prev_frame, IS_VP8); } #if HAVE_THREADS #define check_thread_pos(td, otd, mb_x_check, mb_y_check) \ do { \ int tmp = (mb_y_check << 16) | (mb_x_check & 0xFFFF); \ if (atomic_load(&otd->thread_mb_pos) < tmp) { \ pthread_mutex_lock(&otd->lock); \ atomic_store(&td->wait_mb_pos, tmp); \ do { \ if (atomic_load(&otd->thread_mb_pos) >= tmp) \ break; \ pthread_cond_wait(&otd->cond, &otd->lock); \ } while (1); \ atomic_store(&td->wait_mb_pos, INT_MAX); \ pthread_mutex_unlock(&otd->lock); \ } \ } while (0) #define update_pos(td, mb_y, mb_x) \ do { \ int pos = (mb_y << 16) | (mb_x & 0xFFFF); \ int sliced_threading = (avctx->active_thread_type == FF_THREAD_SLICE) && \ (num_jobs > 1); \ int is_null = !next_td || !prev_td; \ int pos_check = (is_null) ? 1 : \ (next_td != td && pos >= atomic_load(&next_td->wait_mb_pos)) || \ (prev_td != td && pos >= atomic_load(&prev_td->wait_mb_pos)); \ atomic_store(&td->thread_mb_pos, pos); \ if (sliced_threading && pos_check) { \ pthread_mutex_lock(&td->lock); \ pthread_cond_broadcast(&td->cond); \ pthread_mutex_unlock(&td->lock); \ } \ } while (0) #else #define check_thread_pos(td, otd, mb_x_check, mb_y_check) while(0) #define update_pos(td, mb_y, mb_x) while(0) #endif static av_always_inline int decode_mb_row_no_filter(AVCodecContext *avctx, void *tdata, int jobnr, int threadnr, int is_vp7) { VP8Context *s = avctx->priv_data; VP8ThreadData *prev_td, *next_td, *td = &s->thread_data[threadnr]; int mb_y = atomic_load(&td->thread_mb_pos) >> 16; int mb_x, mb_xy = mb_y * s->mb_width; int num_jobs = s->num_jobs; VP8Frame *curframe = s->curframe, *prev_frame = s->prev_frame; VP56RangeCoder *c = &s->coeff_partition[mb_y & (s->num_coeff_partitions - 1)]; VP8Macroblock *mb; uint8_t *dst[3] = { curframe->tf.f->data[0] + 16 * mb_y * s->linesize, curframe->tf.f->data[1] + 8 * mb_y * s->uvlinesize, curframe->tf.f->data[2] + 8 * mb_y * s->uvlinesize }; if (c->end <= c->buffer && c->bits >= 0) return AVERROR_INVALIDDATA; if (mb_y == 0) prev_td = td; else prev_td = &s->thread_data[(jobnr + num_jobs - 1) % num_jobs]; if (mb_y == s->mb_height - 1) next_td = td; else next_td = &s->thread_data[(jobnr + 1) % num_jobs]; if (s->mb_layout == 1) mb = s->macroblocks_base + ((s->mb_width + 1) * (mb_y + 1) + 1); else { // Make sure the previous frame has read its segmentation map, // if we re-use the same map. if (prev_frame && s->segmentation.enabled && !s->segmentation.update_map) ff_thread_await_progress(&prev_frame->tf, mb_y, 0); mb = s->macroblocks + (s->mb_height - mb_y - 1) * 2; memset(mb - 1, 0, sizeof(*mb)); // zero left macroblock AV_WN32A(s->intra4x4_pred_mode_left, DC_PRED * 0x01010101); } if (!is_vp7 || mb_y == 0) memset(td->left_nnz, 0, sizeof(td->left_nnz)); td->mv_bounds.mv_min.x = -MARGIN; td->mv_bounds.mv_max.x = ((s->mb_width - 1) << 6) + MARGIN; for (mb_x = 0; mb_x < s->mb_width; mb_x++, mb_xy++, mb++) { if (c->end <= c->buffer && c->bits >= 0) return AVERROR_INVALIDDATA; // Wait for previous thread to read mb_x+2, and reach mb_y-1. if (prev_td != td) { if (threadnr != 0) { check_thread_pos(td, prev_td, mb_x + (is_vp7 ? 2 : 1), mb_y - (is_vp7 ? 2 : 1)); } else { check_thread_pos(td, prev_td, mb_x + (is_vp7 ? 2 : 1) + s->mb_width + 3, mb_y - (is_vp7 ? 2 : 1)); } } s->vdsp.prefetch(dst[0] + (mb_x & 3) * 4 * s->linesize + 64, s->linesize, 4); s->vdsp.prefetch(dst[1] + (mb_x & 7) * s->uvlinesize + 64, dst[2] - dst[1], 2); if (!s->mb_layout) decode_mb_mode(s, &td->mv_bounds, mb, mb_x, mb_y, curframe->seg_map->data + mb_xy, prev_frame && prev_frame->seg_map ? prev_frame->seg_map->data + mb_xy : NULL, 0, is_vp7); prefetch_motion(s, mb, mb_x, mb_y, mb_xy, VP56_FRAME_PREVIOUS); if (!mb->skip) decode_mb_coeffs(s, td, c, mb, s->top_nnz[mb_x], td->left_nnz, is_vp7); if (mb->mode <= MODE_I4x4) intra_predict(s, td, dst, mb, mb_x, mb_y, is_vp7); else inter_predict(s, td, dst, mb, mb_x, mb_y); prefetch_motion(s, mb, mb_x, mb_y, mb_xy, VP56_FRAME_GOLDEN); if (!mb->skip) { idct_mb(s, td, dst, mb); } else { AV_ZERO64(td->left_nnz); AV_WN64(s->top_nnz[mb_x], 0); // array of 9, so unaligned /* Reset DC block predictors if they would exist * if the mb had coefficients */ if (mb->mode != MODE_I4x4 && mb->mode != VP8_MVMODE_SPLIT) { td->left_nnz[8] = 0; s->top_nnz[mb_x][8] = 0; } } if (s->deblock_filter) filter_level_for_mb(s, mb, &td->filter_strength[mb_x], is_vp7); if (s->deblock_filter && num_jobs != 1 && threadnr == num_jobs - 1) { if (s->filter.simple) backup_mb_border(s->top_border[mb_x + 1], dst[0], NULL, NULL, s->linesize, 0, 1); else backup_mb_border(s->top_border[mb_x + 1], dst[0], dst[1], dst[2], s->linesize, s->uvlinesize, 0); } prefetch_motion(s, mb, mb_x, mb_y, mb_xy, VP56_FRAME_GOLDEN2); dst[0] += 16; dst[1] += 8; dst[2] += 8; td->mv_bounds.mv_min.x -= 64; td->mv_bounds.mv_max.x -= 64; if (mb_x == s->mb_width + 1) { update_pos(td, mb_y, s->mb_width + 3); } else { update_pos(td, mb_y, mb_x); } } return 0; } static int vp7_decode_mb_row_no_filter(AVCodecContext *avctx, void *tdata, int jobnr, int threadnr) { return decode_mb_row_no_filter(avctx, tdata, jobnr, threadnr, 1); } static int vp8_decode_mb_row_no_filter(AVCodecContext *avctx, void *tdata, int jobnr, int threadnr) { return decode_mb_row_no_filter(avctx, tdata, jobnr, threadnr, 0); } static av_always_inline void filter_mb_row(AVCodecContext *avctx, void *tdata, int jobnr, int threadnr, int is_vp7) { VP8Context *s = avctx->priv_data; VP8ThreadData *td = &s->thread_data[threadnr]; int mb_x, mb_y = atomic_load(&td->thread_mb_pos) >> 16, num_jobs = s->num_jobs; AVFrame *curframe = s->curframe->tf.f; VP8Macroblock *mb; VP8ThreadData *prev_td, *next_td; uint8_t *dst[3] = { curframe->data[0] + 16 * mb_y * s->linesize, curframe->data[1] + 8 * mb_y * s->uvlinesize, curframe->data[2] + 8 * mb_y * s->uvlinesize }; if (s->mb_layout == 1) mb = s->macroblocks_base + ((s->mb_width + 1) * (mb_y + 1) + 1); else mb = s->macroblocks + (s->mb_height - mb_y - 1) * 2; if (mb_y == 0) prev_td = td; else prev_td = &s->thread_data[(jobnr + num_jobs - 1) % num_jobs]; if (mb_y == s->mb_height - 1) next_td = td; else next_td = &s->thread_data[(jobnr + 1) % num_jobs]; for (mb_x = 0; mb_x < s->mb_width; mb_x++, mb++) { VP8FilterStrength *f = &td->filter_strength[mb_x]; if (prev_td != td) check_thread_pos(td, prev_td, (mb_x + 1) + (s->mb_width + 3), mb_y - 1); if (next_td != td) if (next_td != &s->thread_data[0]) check_thread_pos(td, next_td, mb_x + 1, mb_y + 1); if (num_jobs == 1) { if (s->filter.simple) backup_mb_border(s->top_border[mb_x + 1], dst[0], NULL, NULL, s->linesize, 0, 1); else backup_mb_border(s->top_border[mb_x + 1], dst[0], dst[1], dst[2], s->linesize, s->uvlinesize, 0); } if (s->filter.simple) filter_mb_simple(s, dst[0], f, mb_x, mb_y); else filter_mb(s, dst, f, mb_x, mb_y, is_vp7); dst[0] += 16; dst[1] += 8; dst[2] += 8; update_pos(td, mb_y, (s->mb_width + 3) + mb_x); } } static void vp7_filter_mb_row(AVCodecContext *avctx, void *tdata, int jobnr, int threadnr) { filter_mb_row(avctx, tdata, jobnr, threadnr, 1); } static void vp8_filter_mb_row(AVCodecContext *avctx, void *tdata, int jobnr, int threadnr) { filter_mb_row(avctx, tdata, jobnr, threadnr, 0); } static av_always_inline int vp78_decode_mb_row_sliced(AVCodecContext *avctx, void *tdata, int jobnr, int threadnr, int is_vp7) { VP8Context *s = avctx->priv_data; VP8ThreadData *td = &s->thread_data[jobnr]; VP8ThreadData *next_td = NULL, *prev_td = NULL; VP8Frame *curframe = s->curframe; int mb_y, num_jobs = s->num_jobs; int ret; td->thread_nr = threadnr; td->mv_bounds.mv_min.y = -MARGIN - 64 * threadnr; td->mv_bounds.mv_max.y = ((s->mb_height - 1) << 6) + MARGIN - 64 * threadnr; for (mb_y = jobnr; mb_y < s->mb_height; mb_y += num_jobs) { atomic_store(&td->thread_mb_pos, mb_y << 16); ret = s->decode_mb_row_no_filter(avctx, tdata, jobnr, threadnr); if (ret < 0) { update_pos(td, s->mb_height, INT_MAX & 0xFFFF); return ret; } if (s->deblock_filter) s->filter_mb_row(avctx, tdata, jobnr, threadnr); update_pos(td, mb_y, INT_MAX & 0xFFFF); td->mv_bounds.mv_min.y -= 64 * num_jobs; td->mv_bounds.mv_max.y -= 64 * num_jobs; if (avctx->active_thread_type == FF_THREAD_FRAME) ff_thread_report_progress(&curframe->tf, mb_y, 0); } return 0; } static int vp7_decode_mb_row_sliced(AVCodecContext *avctx, void *tdata, int jobnr, int threadnr) { return vp78_decode_mb_row_sliced(avctx, tdata, jobnr, threadnr, IS_VP7); } static int vp8_decode_mb_row_sliced(AVCodecContext *avctx, void *tdata, int jobnr, int threadnr) { return vp78_decode_mb_row_sliced(avctx, tdata, jobnr, threadnr, IS_VP8); } static av_always_inline int vp78_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt, int is_vp7) { VP8Context *s = avctx->priv_data; int ret, i, referenced, num_jobs; enum AVDiscard skip_thresh; VP8Frame *av_uninit(curframe), *prev_frame; if (is_vp7) ret = vp7_decode_frame_header(s, avpkt->data, avpkt->size); else ret = vp8_decode_frame_header(s, avpkt->data, avpkt->size); if (ret < 0) goto err; prev_frame = s->framep[VP56_FRAME_CURRENT]; referenced = s->update_last || s->update_golden == VP56_FRAME_CURRENT || s->update_altref == VP56_FRAME_CURRENT; skip_thresh = !referenced ? AVDISCARD_NONREF : !s->keyframe ? AVDISCARD_NONKEY : AVDISCARD_ALL; if (avctx->skip_frame >= skip_thresh) { s->invisible = 1; memcpy(&s->next_framep[0], &s->framep[0], sizeof(s->framep[0]) * 4); goto skip_decode; } s->deblock_filter = s->filter.level && avctx->skip_loop_filter < skip_thresh; // release no longer referenced frames for (i = 0; i < 5; i++) if (s->frames[i].tf.f->data[0] && &s->frames[i] != prev_frame && &s->frames[i] != s->framep[VP56_FRAME_PREVIOUS] && &s->frames[i] != s->framep[VP56_FRAME_GOLDEN] && &s->frames[i] != s->framep[VP56_FRAME_GOLDEN2]) vp8_release_frame(s, &s->frames[i]); curframe = s->framep[VP56_FRAME_CURRENT] = vp8_find_free_buffer(s); if (!s->colorspace) avctx->colorspace = AVCOL_SPC_BT470BG; if (s->fullrange) avctx->color_range = AVCOL_RANGE_JPEG; else avctx->color_range = AVCOL_RANGE_MPEG; /* Given that arithmetic probabilities are updated every frame, it's quite * likely that the values we have on a random interframe are complete * junk if we didn't start decode on a keyframe. So just don't display * anything rather than junk. */ if (!s->keyframe && (!s->framep[VP56_FRAME_PREVIOUS] || !s->framep[VP56_FRAME_GOLDEN] || !s->framep[VP56_FRAME_GOLDEN2])) { av_log(avctx, AV_LOG_WARNING, "Discarding interframe without a prior keyframe!\n"); ret = AVERROR_INVALIDDATA; goto err; } curframe->tf.f->key_frame = s->keyframe; curframe->tf.f->pict_type = s->keyframe ? AV_PICTURE_TYPE_I : AV_PICTURE_TYPE_P; if ((ret = vp8_alloc_frame(s, curframe, referenced)) < 0) goto err; // check if golden and altref are swapped if (s->update_altref != VP56_FRAME_NONE) s->next_framep[VP56_FRAME_GOLDEN2] = s->framep[s->update_altref]; else s->next_framep[VP56_FRAME_GOLDEN2] = s->framep[VP56_FRAME_GOLDEN2]; if (s->update_golden != VP56_FRAME_NONE) s->next_framep[VP56_FRAME_GOLDEN] = s->framep[s->update_golden]; else s->next_framep[VP56_FRAME_GOLDEN] = s->framep[VP56_FRAME_GOLDEN]; if (s->update_last) s->next_framep[VP56_FRAME_PREVIOUS] = curframe; else s->next_framep[VP56_FRAME_PREVIOUS] = s->framep[VP56_FRAME_PREVIOUS]; s->next_framep[VP56_FRAME_CURRENT] = curframe; if (avctx->codec->update_thread_context) ff_thread_finish_setup(avctx); s->linesize = curframe->tf.f->linesize[0]; s->uvlinesize = curframe->tf.f->linesize[1]; memset(s->top_nnz, 0, s->mb_width * sizeof(*s->top_nnz)); /* Zero macroblock structures for top/top-left prediction * from outside the frame. */ if (!s->mb_layout) memset(s->macroblocks + s->mb_height * 2 - 1, 0, (s->mb_width + 1) * sizeof(*s->macroblocks)); if (!s->mb_layout && s->keyframe) memset(s->intra4x4_pred_mode_top, DC_PRED, s->mb_width * 4); memset(s->ref_count, 0, sizeof(s->ref_count)); if (s->mb_layout == 1) { // Make sure the previous frame has read its segmentation map, // if we re-use the same map. if (prev_frame && s->segmentation.enabled && !s->segmentation.update_map) ff_thread_await_progress(&prev_frame->tf, 1, 0); if (is_vp7) vp7_decode_mv_mb_modes(avctx, curframe, prev_frame); else vp8_decode_mv_mb_modes(avctx, curframe, prev_frame); } if (avctx->active_thread_type == FF_THREAD_FRAME) num_jobs = 1; else num_jobs = FFMIN(s->num_coeff_partitions, avctx->thread_count); s->num_jobs = num_jobs; s->curframe = curframe; s->prev_frame = prev_frame; s->mv_bounds.mv_min.y = -MARGIN; s->mv_bounds.mv_max.y = ((s->mb_height - 1) << 6) + MARGIN; for (i = 0; i < MAX_THREADS; i++) { VP8ThreadData *td = &s->thread_data[i]; atomic_init(&td->thread_mb_pos, 0); atomic_init(&td->wait_mb_pos, INT_MAX); } if (is_vp7) avctx->execute2(avctx, vp7_decode_mb_row_sliced, s->thread_data, NULL, num_jobs); else avctx->execute2(avctx, vp8_decode_mb_row_sliced, s->thread_data, NULL, num_jobs); ff_thread_report_progress(&curframe->tf, INT_MAX, 0); memcpy(&s->framep[0], &s->next_framep[0], sizeof(s->framep[0]) * 4); skip_decode: // if future frames don't use the updated probabilities, // reset them to the values we saved if (!s->update_probabilities) s->prob[0] = s->prob[1]; if (!s->invisible) { if ((ret = av_frame_ref(data, curframe->tf.f)) < 0) return ret; *got_frame = 1; } return avpkt->size; err: memcpy(&s->next_framep[0], &s->framep[0], sizeof(s->framep[0]) * 4); return ret; } int ff_vp8_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { return vp78_decode_frame(avctx, data, got_frame, avpkt, IS_VP8); } #if CONFIG_VP7_DECODER static int vp7_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { return vp78_decode_frame(avctx, data, got_frame, avpkt, IS_VP7); } #endif /* CONFIG_VP7_DECODER */ av_cold int ff_vp8_decode_free(AVCodecContext *avctx) { VP8Context *s = avctx->priv_data; int i; if (!s) return 0; vp8_decode_flush_impl(avctx, 1); for (i = 0; i < FF_ARRAY_ELEMS(s->frames); i++) av_frame_free(&s->frames[i].tf.f); return 0; } static av_cold int vp8_init_frames(VP8Context *s) { int i; for (i = 0; i < FF_ARRAY_ELEMS(s->frames); i++) { s->frames[i].tf.f = av_frame_alloc(); if (!s->frames[i].tf.f) return AVERROR(ENOMEM); } return 0; } static av_always_inline int vp78_decode_init(AVCodecContext *avctx, int is_vp7) { VP8Context *s = avctx->priv_data; int ret; s->avctx = avctx; s->vp7 = avctx->codec->id == AV_CODEC_ID_VP7; avctx->pix_fmt = AV_PIX_FMT_YUV420P; avctx->internal->allocate_progress = 1; ff_videodsp_init(&s->vdsp, 8); ff_vp78dsp_init(&s->vp8dsp); if (CONFIG_VP7_DECODER && is_vp7) { ff_h264_pred_init(&s->hpc, AV_CODEC_ID_VP7, 8, 1); ff_vp7dsp_init(&s->vp8dsp); s->decode_mb_row_no_filter = vp7_decode_mb_row_no_filter; s->filter_mb_row = vp7_filter_mb_row; } else if (CONFIG_VP8_DECODER && !is_vp7) { ff_h264_pred_init(&s->hpc, AV_CODEC_ID_VP8, 8, 1); ff_vp8dsp_init(&s->vp8dsp); s->decode_mb_row_no_filter = vp8_decode_mb_row_no_filter; s->filter_mb_row = vp8_filter_mb_row; } /* does not change for VP8 */ memcpy(s->prob[0].scan, ff_zigzag_scan, sizeof(s->prob[0].scan)); if ((ret = vp8_init_frames(s)) < 0) { ff_vp8_decode_free(avctx); return ret; } return 0; } #if CONFIG_VP7_DECODER static int vp7_decode_init(AVCodecContext *avctx) { return vp78_decode_init(avctx, IS_VP7); } #endif /* CONFIG_VP7_DECODER */ av_cold int ff_vp8_decode_init(AVCodecContext *avctx) { return vp78_decode_init(avctx, IS_VP8); } #if CONFIG_VP8_DECODER #if HAVE_THREADS static av_cold int vp8_decode_init_thread_copy(AVCodecContext *avctx) { VP8Context *s = avctx->priv_data; int ret; s->avctx = avctx; if ((ret = vp8_init_frames(s)) < 0) { ff_vp8_decode_free(avctx); return ret; } return 0; } #define REBASE(pic) ((pic) ? (pic) - &s_src->frames[0] + &s->frames[0] : NULL) static int vp8_decode_update_thread_context(AVCodecContext *dst, const AVCodecContext *src) { VP8Context *s = dst->priv_data, *s_src = src->priv_data; int i; if (s->macroblocks_base && (s_src->mb_width != s->mb_width || s_src->mb_height != s->mb_height)) { free_buffers(s); s->mb_width = s_src->mb_width; s->mb_height = s_src->mb_height; } s->prob[0] = s_src->prob[!s_src->update_probabilities]; s->segmentation = s_src->segmentation; s->lf_delta = s_src->lf_delta; memcpy(s->sign_bias, s_src->sign_bias, sizeof(s->sign_bias)); for (i = 0; i < FF_ARRAY_ELEMS(s_src->frames); i++) { if (s_src->frames[i].tf.f->data[0]) { int ret = vp8_ref_frame(s, &s->frames[i], &s_src->frames[i]); if (ret < 0) return ret; } } s->framep[0] = REBASE(s_src->next_framep[0]); s->framep[1] = REBASE(s_src->next_framep[1]); s->framep[2] = REBASE(s_src->next_framep[2]); s->framep[3] = REBASE(s_src->next_framep[3]); return 0; } #endif /* HAVE_THREADS */ #endif /* CONFIG_VP8_DECODER */ #if CONFIG_VP7_DECODER AVCodec ff_vp7_decoder = { .name = "vp7", .long_name = NULL_IF_CONFIG_SMALL("On2 VP7"), .type = AVMEDIA_TYPE_VIDEO, .id = AV_CODEC_ID_VP7, .priv_data_size = sizeof(VP8Context), .init = vp7_decode_init, .close = ff_vp8_decode_free, .decode = vp7_decode_frame, .capabilities = AV_CODEC_CAP_DR1, .flush = vp8_decode_flush, }; #endif /* CONFIG_VP7_DECODER */ #if CONFIG_VP8_DECODER AVCodec ff_vp8_decoder = { .name = "vp8", .long_name = NULL_IF_CONFIG_SMALL("On2 VP8"), .type = AVMEDIA_TYPE_VIDEO, .id = AV_CODEC_ID_VP8, .priv_data_size = sizeof(VP8Context), .init = ff_vp8_decode_init, .close = ff_vp8_decode_free, .decode = ff_vp8_decode_frame, .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS | AV_CODEC_CAP_SLICE_THREADS, .flush = vp8_decode_flush, .init_thread_copy = ONLY_IF_THREADS_ENABLED(vp8_decode_init_thread_copy), .update_thread_context = ONLY_IF_THREADS_ENABLED(vp8_decode_update_thread_context), }; #endif /* CONFIG_VP7_DECODER */
./CrossVul/dataset_final_sorted/CWE-119/c/bad_3418_0
crossvul-cpp_data_bad_3407_2
/* 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-119/c/bad_3407_2
crossvul-cpp_data_bad_2834_0
/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * COPYRIGHT (C) 2006,2007 * THE REGENTS OF THE UNIVERSITY OF MICHIGAN * ALL RIGHTS RESERVED * * Permission is granted to use, copy, create derivative works * and redistribute this software and such derivative works * for any purpose, so long as the name of The University of * Michigan is not used in any advertising or publicity * pertaining to the use of distribution of this software * without specific, written prior authorization. If the * above copyright notice or any other identification of the * University of Michigan is included in any copy of any * portion of this software, then the disclaimer below must * also be included. * * THIS SOFTWARE IS PROVIDED AS IS, WITHOUT REPRESENTATION * FROM THE UNIVERSITY OF MICHIGAN AS TO ITS FITNESS FOR ANY * PURPOSE, AND WITHOUT WARRANTY BY THE UNIVERSITY OF * MICHIGAN OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING * WITHOUT LIMITATION THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE * REGENTS OF THE UNIVERSITY OF MICHIGAN SHALL NOT BE LIABLE * FOR ANY DAMAGES, INCLUDING SPECIAL, INDIRECT, INCIDENTAL, OR * CONSEQUENTIAL DAMAGES, WITH RESPECT TO ANY CLAIM ARISING * OUT OF OR IN CONNECTION WITH THE USE OF THE SOFTWARE, EVEN * IF IT HAS BEEN OR IS HEREAFTER ADVISED OF THE POSSIBILITY OF * SUCH DAMAGES. */ #include "pkinit_crypto_openssl.h" #include "k5-buf.h" #include <dlfcn.h> #include <unistd.h> #include <dirent.h> #include <arpa/inet.h> static krb5_error_code pkinit_init_pkinit_oids(pkinit_plg_crypto_context ); static void pkinit_fini_pkinit_oids(pkinit_plg_crypto_context ); static krb5_error_code pkinit_init_dh_params(pkinit_plg_crypto_context ); static void pkinit_fini_dh_params(pkinit_plg_crypto_context ); static krb5_error_code pkinit_init_certs(pkinit_identity_crypto_context ctx); static void pkinit_fini_certs(pkinit_identity_crypto_context ctx); static krb5_error_code pkinit_init_pkcs11(pkinit_identity_crypto_context ctx); static void pkinit_fini_pkcs11(pkinit_identity_crypto_context ctx); static krb5_error_code pkinit_encode_dh_params (const BIGNUM *, const BIGNUM *, const BIGNUM *, uint8_t **, unsigned int *); static DH *decode_dh_params(const uint8_t *, unsigned int ); static int pkinit_check_dh_params(DH *dh1, DH *dh2); static krb5_error_code pkinit_sign_data (krb5_context context, pkinit_identity_crypto_context cryptoctx, unsigned char *data, unsigned int data_len, unsigned char **sig, unsigned int *sig_len); static krb5_error_code create_signature (unsigned char **, unsigned int *, unsigned char *, unsigned int, EVP_PKEY *pkey); static krb5_error_code pkinit_decode_data (krb5_context context, pkinit_identity_crypto_context cryptoctx, const uint8_t *data, unsigned int data_len, uint8_t **decoded, unsigned int *decoded_len); #ifdef DEBUG_DH static void print_dh(DH *, char *); static void print_pubkey(BIGNUM *, char *); #endif static int prepare_enc_data (const uint8_t *indata, int indata_len, uint8_t **outdata, int *outdata_len); static int openssl_callback (int, X509_STORE_CTX *); static int openssl_callback_ignore_crls (int, X509_STORE_CTX *); static int pkcs7_decrypt (krb5_context context, pkinit_identity_crypto_context id_cryptoctx, PKCS7 *p7, BIO *bio); static BIO * pkcs7_dataDecode (krb5_context context, pkinit_identity_crypto_context id_cryptoctx, PKCS7 *p7); static ASN1_OBJECT * pkinit_pkcs7type2oid (pkinit_plg_crypto_context plg_cryptoctx, int pkcs7_type); static krb5_error_code pkinit_create_sequence_of_principal_identifiers (krb5_context context, pkinit_plg_crypto_context plg_cryptoctx, pkinit_req_crypto_context req_cryptoctx, pkinit_identity_crypto_context id_cryptoctx, int type, krb5_pa_data ***e_data_out); #ifndef WITHOUT_PKCS11 static krb5_error_code pkinit_find_private_key (pkinit_identity_crypto_context, CK_ATTRIBUTE_TYPE usage, CK_OBJECT_HANDLE *objp); static krb5_error_code pkinit_login (krb5_context context, pkinit_identity_crypto_context id_cryptoctx, CK_TOKEN_INFO *tip, const char *password); static krb5_error_code pkinit_open_session (krb5_context context, pkinit_identity_crypto_context id_cryptoctx); static void * pkinit_C_LoadModule(const char *modname, CK_FUNCTION_LIST_PTR_PTR p11p); static CK_RV pkinit_C_UnloadModule(void *handle); #ifdef SILLYDECRYPT CK_RV pkinit_C_Decrypt (pkinit_identity_crypto_context id_cryptoctx, CK_BYTE_PTR pEncryptedData, CK_ULONG ulEncryptedDataLen, CK_BYTE_PTR pData, CK_ULONG_PTR pulDataLen); #endif static krb5_error_code pkinit_sign_data_pkcs11 (krb5_context context, pkinit_identity_crypto_context id_cryptoctx, unsigned char *data, unsigned int data_len, unsigned char **sig, unsigned int *sig_len); static krb5_error_code pkinit_decode_data_pkcs11 (krb5_context context, pkinit_identity_crypto_context id_cryptoctx, const uint8_t *data, unsigned int data_len, uint8_t **decoded_data, unsigned int *decoded_data_len); #endif /* WITHOUT_PKCS11 */ static krb5_error_code pkinit_sign_data_fs (krb5_context context, pkinit_identity_crypto_context id_cryptoctx, unsigned char *data, unsigned int data_len, unsigned char **sig, unsigned int *sig_len); static krb5_error_code pkinit_decode_data_fs (krb5_context context, pkinit_identity_crypto_context id_cryptoctx, const uint8_t *data, unsigned int data_len, uint8_t **decoded_data, unsigned int *decoded_data_len); static krb5_error_code create_krb5_invalidCertificates(krb5_context context, pkinit_plg_crypto_context plg_cryptoctx, pkinit_req_crypto_context req_cryptoctx, pkinit_identity_crypto_context id_cryptoctx, krb5_external_principal_identifier *** ids); static krb5_error_code create_identifiers_from_stack(STACK_OF(X509) *sk, krb5_external_principal_identifier *** ids); static int wrap_signeddata(unsigned char *data, unsigned int data_len, unsigned char **out, unsigned int *out_len); static char * pkinit_pkcs11_code_to_text(int err); #ifdef HAVE_OPENSSL_CMS /* Use CMS support present in OpenSSL. */ #include <openssl/cms.h> #define pkinit_CMS_get0_content_signed(_cms) CMS_get0_content(_cms) #define pkinit_CMS_get0_content_data(_cms) CMS_get0_content(_cms) #define pkinit_CMS_free1_crls(_sk_x509crl) \ sk_X509_CRL_pop_free((_sk_x509crl), X509_CRL_free) #define pkinit_CMS_free1_certs(_sk_x509) \ sk_X509_pop_free((_sk_x509), X509_free) #define pkinit_CMS_SignerInfo_get_cert(_cms,_si,_x509_pp) \ CMS_SignerInfo_get0_algs(_si,NULL,_x509_pp,NULL,NULL) #else /* Fake up CMS support using PKCS7. */ #define pkinit_CMS_free1_crls(_stack_of_x509crls) /* Don't free these */ #define pkinit_CMS_free1_certs(_stack_of_x509certs) /* Don't free these */ #define CMS_NO_SIGNER_CERT_VERIFY PKCS7_NOVERIFY #define CMS_NOATTR PKCS7_NOATTR #define CMS_ContentInfo PKCS7 #define CMS_SignerInfo PKCS7_SIGNER_INFO #define d2i_CMS_ContentInfo d2i_PKCS7 #define CMS_get0_type(_p7) ((_p7)->type) #define pkinit_CMS_get0_content_signed(_p7) (&((_p7)->d.sign->contents->d.other->value.octet_string)) #define pkinit_CMS_get0_content_data(_p7) (&((_p7)->d.other->value.octet_string)) #define CMS_set1_signers_certs(_p7,_stack_of_x509,_uint) #define CMS_get0_SignerInfos PKCS7_get_signer_info #define stack_st_CMS_SignerInfo stack_st_PKCS7_SIGNER_INFO #undef sk_CMS_SignerInfo_value #define sk_CMS_SignerInfo_value sk_PKCS7_SIGNER_INFO_value #define CMS_get0_eContentType(_p7) (_p7->d.sign->contents->type) #define CMS_verify PKCS7_verify #define CMS_get1_crls(_p7) (_p7->d.sign->crl) #define CMS_get1_certs(_p7) (_p7->d.sign->cert) #define CMS_ContentInfo_free(_p7) PKCS7_free(_p7) #define pkinit_CMS_SignerInfo_get_cert(_p7,_si,_x509_pp) \ (*_x509_pp) = PKCS7_cert_from_signer_info(_p7,_si) #endif #if OPENSSL_VERSION_NUMBER < 0x10100000L /* 1.1 standardizes constructor and destructor names, renaming * EVP_MD_CTX_{create,destroy} and deprecating ASN1_STRING_data. */ #define EVP_MD_CTX_new EVP_MD_CTX_create #define EVP_MD_CTX_free EVP_MD_CTX_destroy #define ASN1_STRING_get0_data ASN1_STRING_data /* 1.1 makes many handle types opaque and adds accessors. Add compatibility * versions of the new accessors we use for pre-1.1. */ #define OBJ_get0_data(o) ((o)->data) #define OBJ_length(o) ((o)->length) #define DH_set0_pqg compat_dh_set0_pqg static int compat_dh_set0_pqg(DH *dh, BIGNUM *p, BIGNUM *q, BIGNUM *g) { /* The real function frees the old values and does argument checking, but * our code doesn't need that. */ dh->p = p; dh->q = q; dh->g = g; return 1; } #define DH_get0_pqg compat_dh_get0_pqg static void compat_dh_get0_pqg(const DH *dh, const BIGNUM **p, const BIGNUM **q, const BIGNUM **g) { if (p != NULL) *p = dh->p; if (q != NULL) *q = dh->q; if (g != NULL) *g = dh->g; } #define DH_get0_key compat_dh_get0_key static void compat_dh_get0_key(const DH *dh, const BIGNUM **pub, const BIGNUM **priv) { if (pub != NULL) *pub = dh->pub_key; if (priv != NULL) *priv = dh->priv_key; } /* Return true if the cert c includes a key usage which doesn't include u. * Define using direct member access for pre-1.1. */ #define ku_reject(c, u) \ (((c)->ex_flags & EXFLAG_KUSAGE) && !((c)->ex_kusage & (u))) #else /* OPENSSL_VERSION_NUMBER >= 0x10100000L */ /* Return true if the cert x includes a key usage which doesn't include u. */ #define ku_reject(c, u) (!(X509_get_key_usage(c) & (u))) #endif static struct pkcs11_errstrings { short code; char *text; } pkcs11_errstrings[] = { { 0x0, "ok" }, { 0x1, "cancel" }, { 0x2, "host memory" }, { 0x3, "slot id invalid" }, { 0x5, "general error" }, { 0x6, "function failed" }, { 0x7, "arguments bad" }, { 0x8, "no event" }, { 0x9, "need to create threads" }, { 0xa, "cant lock" }, { 0x10, "attribute read only" }, { 0x11, "attribute sensitive" }, { 0x12, "attribute type invalid" }, { 0x13, "attribute value invalid" }, { 0x20, "data invalid" }, { 0x21, "data len range" }, { 0x30, "device error" }, { 0x31, "device memory" }, { 0x32, "device removed" }, { 0x40, "encrypted data invalid" }, { 0x41, "encrypted data len range" }, { 0x50, "function canceled" }, { 0x51, "function not parallel" }, { 0x54, "function not supported" }, { 0x60, "key handle invalid" }, { 0x62, "key size range" }, { 0x63, "key type inconsistent" }, { 0x64, "key not needed" }, { 0x65, "key changed" }, { 0x66, "key needed" }, { 0x67, "key indigestible" }, { 0x68, "key function not permitted" }, { 0x69, "key not wrappable" }, { 0x6a, "key unextractable" }, { 0x70, "mechanism invalid" }, { 0x71, "mechanism param invalid" }, { 0x82, "object handle invalid" }, { 0x90, "operation active" }, { 0x91, "operation not initialized" }, { 0xa0, "pin incorrect" }, { 0xa1, "pin invalid" }, { 0xa2, "pin len range" }, { 0xa3, "pin expired" }, { 0xa4, "pin locked" }, { 0xb0, "session closed" }, { 0xb1, "session count" }, { 0xb3, "session handle invalid" }, { 0xb4, "session parallel not supported" }, { 0xb5, "session read only" }, { 0xb6, "session exists" }, { 0xb7, "session read only exists" }, { 0xb8, "session read write so exists" }, { 0xc0, "signature invalid" }, { 0xc1, "signature len range" }, { 0xd0, "template incomplete" }, { 0xd1, "template inconsistent" }, { 0xe0, "token not present" }, { 0xe1, "token not recognized" }, { 0xe2, "token write protected" }, { 0xf0, "unwrapping key handle invalid" }, { 0xf1, "unwrapping key size range" }, { 0xf2, "unwrapping key type inconsistent" }, { 0x100, "user already logged in" }, { 0x101, "user not logged in" }, { 0x102, "user pin not initialized" }, { 0x103, "user type invalid" }, { 0x104, "user another already logged in" }, { 0x105, "user too many types" }, { 0x110, "wrapped key invalid" }, { 0x112, "wrapped key len range" }, { 0x113, "wrapping key handle invalid" }, { 0x114, "wrapping key size range" }, { 0x115, "wrapping key type inconsistent" }, { 0x120, "random seed not supported" }, { 0x121, "random no rng" }, { 0x130, "domain params invalid" }, { 0x150, "buffer too small" }, { 0x160, "saved state invalid" }, { 0x170, "information sensitive" }, { 0x180, "state unsaveable" }, { 0x190, "cryptoki not initialized" }, { 0x191, "cryptoki already initialized" }, { 0x1a0, "mutex bad" }, { 0x1a1, "mutex not locked" }, { 0x200, "function rejected" }, { -1, NULL } }; /* DH parameters */ static uint8_t oakley_1024[128] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34, 0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1, 0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74, 0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22, 0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD, 0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, 0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37, 0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45, 0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6, 0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x37, 0xED, 0x6B, 0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED, 0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5, 0xAE, 0x9F, 0x24, 0x11, 0x7C, 0x4B, 0x1F, 0xE6, 0x49, 0x28, 0x66, 0x51, 0xEC, 0xE6, 0x53, 0x81, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; static uint8_t oakley_2048[2048/8] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34, 0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1, 0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74, 0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22, 0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD, 0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, 0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37, 0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45, 0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6, 0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x37, 0xED, 0x6B, 0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED, 0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5, 0xAE, 0x9F, 0x24, 0x11, 0x7C, 0x4B, 0x1F, 0xE6, 0x49, 0x28, 0x66, 0x51, 0xEC, 0xE4, 0x5B, 0x3D, 0xC2, 0x00, 0x7C, 0xB8, 0xA1, 0x63, 0xBF, 0x05, 0x98, 0xDA, 0x48, 0x36, 0x1C, 0x55, 0xD3, 0x9A, 0x69, 0x16, 0x3F, 0xA8, 0xFD, 0x24, 0xCF, 0x5F, 0x83, 0x65, 0x5D, 0x23, 0xDC, 0xA3, 0xAD, 0x96, 0x1C, 0x62, 0xF3, 0x56, 0x20, 0x85, 0x52, 0xBB, 0x9E, 0xD5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6D, 0x67, 0x0C, 0x35, 0x4E, 0x4A, 0xBC, 0x98, 0x04, 0xF1, 0x74, 0x6C, 0x08, 0xCA, 0x18, 0x21, 0x7C, 0x32, 0x90, 0x5E, 0x46, 0x2E, 0x36, 0xCE, 0x3B, 0xE3, 0x9E, 0x77, 0x2C, 0x18, 0x0E, 0x86, 0x03, 0x9B, 0x27, 0x83, 0xA2, 0xEC, 0x07, 0xA2, 0x8F, 0xB5, 0xC5, 0x5D, 0xF0, 0x6F, 0x4C, 0x52, 0xC9, 0xDE, 0x2B, 0xCB, 0xF6, 0x95, 0x58, 0x17, 0x18, 0x39, 0x95, 0x49, 0x7C, 0xEA, 0x95, 0x6A, 0xE5, 0x15, 0xD2, 0x26, 0x18, 0x98, 0xFA, 0x05, 0x10, 0x15, 0x72, 0x8E, 0x5A, 0x8A, 0xAC, 0xAA, 0x68, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; static uint8_t oakley_4096[4096/8] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34, 0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1, 0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74, 0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22, 0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD, 0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, 0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37, 0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45, 0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6, 0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x37, 0xED, 0x6B, 0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED, 0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5, 0xAE, 0x9F, 0x24, 0x11, 0x7C, 0x4B, 0x1F, 0xE6, 0x49, 0x28, 0x66, 0x51, 0xEC, 0xE4, 0x5B, 0x3D, 0xC2, 0x00, 0x7C, 0xB8, 0xA1, 0x63, 0xBF, 0x05, 0x98, 0xDA, 0x48, 0x36, 0x1C, 0x55, 0xD3, 0x9A, 0x69, 0x16, 0x3F, 0xA8, 0xFD, 0x24, 0xCF, 0x5F, 0x83, 0x65, 0x5D, 0x23, 0xDC, 0xA3, 0xAD, 0x96, 0x1C, 0x62, 0xF3, 0x56, 0x20, 0x85, 0x52, 0xBB, 0x9E, 0xD5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6D, 0x67, 0x0C, 0x35, 0x4E, 0x4A, 0xBC, 0x98, 0x04, 0xF1, 0x74, 0x6C, 0x08, 0xCA, 0x18, 0x21, 0x7C, 0x32, 0x90, 0x5E, 0x46, 0x2E, 0x36, 0xCE, 0x3B, 0xE3, 0x9E, 0x77, 0x2C, 0x18, 0x0E, 0x86, 0x03, 0x9B, 0x27, 0x83, 0xA2, 0xEC, 0x07, 0xA2, 0x8F, 0xB5, 0xC5, 0x5D, 0xF0, 0x6F, 0x4C, 0x52, 0xC9, 0xDE, 0x2B, 0xCB, 0xF6, 0x95, 0x58, 0x17, 0x18, 0x39, 0x95, 0x49, 0x7C, 0xEA, 0x95, 0x6A, 0xE5, 0x15, 0xD2, 0x26, 0x18, 0x98, 0xFA, 0x05, 0x10, 0x15, 0x72, 0x8E, 0x5A, 0x8A, 0xAA, 0xC4, 0x2D, 0xAD, 0x33, 0x17, 0x0D, 0x04, 0x50, 0x7A, 0x33, 0xA8, 0x55, 0x21, 0xAB, 0xDF, 0x1C, 0xBA, 0x64, 0xEC, 0xFB, 0x85, 0x04, 0x58, 0xDB, 0xEF, 0x0A, 0x8A, 0xEA, 0x71, 0x57, 0x5D, 0x06, 0x0C, 0x7D, 0xB3, 0x97, 0x0F, 0x85, 0xA6, 0xE1, 0xE4, 0xC7, 0xAB, 0xF5, 0xAE, 0x8C, 0xDB, 0x09, 0x33, 0xD7, 0x1E, 0x8C, 0x94, 0xE0, 0x4A, 0x25, 0x61, 0x9D, 0xCE, 0xE3, 0xD2, 0x26, 0x1A, 0xD2, 0xEE, 0x6B, 0xF1, 0x2F, 0xFA, 0x06, 0xD9, 0x8A, 0x08, 0x64, 0xD8, 0x76, 0x02, 0x73, 0x3E, 0xC8, 0x6A, 0x64, 0x52, 0x1F, 0x2B, 0x18, 0x17, 0x7B, 0x20, 0x0C, 0xBB, 0xE1, 0x17, 0x57, 0x7A, 0x61, 0x5D, 0x6C, 0x77, 0x09, 0x88, 0xC0, 0xBA, 0xD9, 0x46, 0xE2, 0x08, 0xE2, 0x4F, 0xA0, 0x74, 0xE5, 0xAB, 0x31, 0x43, 0xDB, 0x5B, 0xFC, 0xE0, 0xFD, 0x10, 0x8E, 0x4B, 0x82, 0xD1, 0x20, 0xA9, 0x21, 0x08, 0x01, 0x1A, 0x72, 0x3C, 0x12, 0xA7, 0x87, 0xE6, 0xD7, 0x88, 0x71, 0x9A, 0x10, 0xBD, 0xBA, 0x5B, 0x26, 0x99, 0xC3, 0x27, 0x18, 0x6A, 0xF4, 0xE2, 0x3C, 0x1A, 0x94, 0x68, 0x34, 0xB6, 0x15, 0x0B, 0xDA, 0x25, 0x83, 0xE9, 0xCA, 0x2A, 0xD4, 0x4C, 0xE8, 0xDB, 0xBB, 0xC2, 0xDB, 0x04, 0xDE, 0x8E, 0xF9, 0x2E, 0x8E, 0xFC, 0x14, 0x1F, 0xBE, 0xCA, 0xA6, 0x28, 0x7C, 0x59, 0x47, 0x4E, 0x6B, 0xC0, 0x5D, 0x99, 0xB2, 0x96, 0x4F, 0xA0, 0x90, 0xC3, 0xA2, 0x23, 0x3B, 0xA1, 0x86, 0x51, 0x5B, 0xE7, 0xED, 0x1F, 0x61, 0x29, 0x70, 0xCE, 0xE2, 0xD7, 0xAF, 0xB8, 0x1B, 0xDD, 0x76, 0x21, 0x70, 0x48, 0x1C, 0xD0, 0x06, 0x91, 0x27, 0xD5, 0xB0, 0x5A, 0xA9, 0x93, 0xB4, 0xEA, 0x98, 0x8D, 0x8F, 0xDD, 0xC1, 0x86, 0xFF, 0xB7, 0xDC, 0x90, 0xA6, 0xC0, 0x8F, 0x4D, 0xF4, 0x35, 0xC9, 0x34, 0x06, 0x31, 0x99, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; MAKE_INIT_FUNCTION(pkinit_openssl_init); static krb5_error_code oerr(krb5_context context, krb5_error_code code, const char *fmt, ...) #if !defined(__cplusplus) && (__GNUC__ > 2) __attribute__((__format__(__printf__, 3, 4))) #endif ; /* * Set an error string containing the formatted arguments and the first pending * OpenSSL error. Write the formatted arguments and all pending OpenSSL error * messages to the trace log. Return code, or KRB5KDC_ERR_PREAUTH_FAILED if * code is 0. */ static krb5_error_code oerr(krb5_context context, krb5_error_code code, const char *fmt, ...) { unsigned long err; va_list ap; char *str, buf[128]; int r; if (!code) code = KRB5KDC_ERR_PREAUTH_FAILED; va_start(ap, fmt); r = vasprintf(&str, fmt, ap); va_end(ap); if (r < 0) return code; err = ERR_peek_error(); if (err) { krb5_set_error_message(context, code, _("%s: %s"), str, ERR_reason_error_string(err)); } else { krb5_set_error_message(context, code, "%s", str); } TRACE_PKINIT_OPENSSL_ERROR(context, str); while ((err = ERR_get_error()) != 0) { ERR_error_string_n(err, buf, sizeof(buf)); TRACE_PKINIT_OPENSSL_ERROR(context, buf); } free(str); return code; } /* * Set an appropriate error string containing msg for a certificate * verification failure from certctx. Write the message and all pending * OpenSSL error messages to the trace log. Return code, or * KRB5KDC_ERR_PREAUTH_FAILED if code is 0. */ static krb5_error_code oerr_cert(krb5_context context, krb5_error_code code, X509_STORE_CTX *certctx, const char *msg) { int depth = X509_STORE_CTX_get_error_depth(certctx); int err = X509_STORE_CTX_get_error(certctx); const char *errstr = X509_verify_cert_error_string(err); return oerr(context, code, _("%s (depth %d): %s"), msg, depth, errstr); } krb5_error_code pkinit_init_plg_crypto(pkinit_plg_crypto_context *cryptoctx) { krb5_error_code retval = ENOMEM; pkinit_plg_crypto_context ctx = NULL; (void)CALL_INIT_FUNCTION(pkinit_openssl_init); ctx = malloc(sizeof(*ctx)); if (ctx == NULL) goto out; memset(ctx, 0, sizeof(*ctx)); pkiDebug("%s: initializing openssl crypto context at %p\n", __FUNCTION__, ctx); retval = pkinit_init_pkinit_oids(ctx); if (retval) goto out; retval = pkinit_init_dh_params(ctx); if (retval) goto out; *cryptoctx = ctx; out: if (retval && ctx != NULL) pkinit_fini_plg_crypto(ctx); return retval; } void pkinit_fini_plg_crypto(pkinit_plg_crypto_context cryptoctx) { pkiDebug("%s: freeing context at %p\n", __FUNCTION__, cryptoctx); if (cryptoctx == NULL) return; pkinit_fini_pkinit_oids(cryptoctx); pkinit_fini_dh_params(cryptoctx); free(cryptoctx); } krb5_error_code pkinit_init_identity_crypto(pkinit_identity_crypto_context *idctx) { krb5_error_code retval = ENOMEM; pkinit_identity_crypto_context ctx = NULL; ctx = malloc(sizeof(*ctx)); if (ctx == NULL) goto out; memset(ctx, 0, sizeof(*ctx)); ctx->identity = NULL; retval = pkinit_init_certs(ctx); if (retval) goto out; retval = pkinit_init_pkcs11(ctx); if (retval) goto out; pkiDebug("%s: returning ctx at %p\n", __FUNCTION__, ctx); *idctx = ctx; out: if (retval) { if (ctx) pkinit_fini_identity_crypto(ctx); } return retval; } void pkinit_fini_identity_crypto(pkinit_identity_crypto_context idctx) { if (idctx == NULL) return; pkiDebug("%s: freeing ctx at %p\n", __FUNCTION__, idctx); if (idctx->deferred_ids != NULL) pkinit_free_deferred_ids(idctx->deferred_ids); free(idctx->identity); pkinit_fini_certs(idctx); pkinit_fini_pkcs11(idctx); free(idctx); } krb5_error_code pkinit_init_req_crypto(pkinit_req_crypto_context *cryptoctx) { krb5_error_code retval = ENOMEM; pkinit_req_crypto_context ctx = NULL; ctx = malloc(sizeof(*ctx)); if (ctx == NULL) goto out; memset(ctx, 0, sizeof(*ctx)); ctx->dh = NULL; ctx->received_cert = NULL; *cryptoctx = ctx; pkiDebug("%s: returning ctx at %p\n", __FUNCTION__, ctx); retval = 0; out: if (retval) free(ctx); return retval; } void pkinit_fini_req_crypto(pkinit_req_crypto_context req_cryptoctx) { if (req_cryptoctx == NULL) return; pkiDebug("%s: freeing ctx at %p\n", __FUNCTION__, req_cryptoctx); if (req_cryptoctx->dh != NULL) DH_free(req_cryptoctx->dh); if (req_cryptoctx->received_cert != NULL) X509_free(req_cryptoctx->received_cert); free(req_cryptoctx); } static krb5_error_code pkinit_init_pkinit_oids(pkinit_plg_crypto_context ctx) { ctx->id_pkinit_san = OBJ_txt2obj("1.3.6.1.5.2.2", 1); if (ctx->id_pkinit_san == NULL) return ENOMEM; ctx->id_pkinit_authData = OBJ_txt2obj("1.3.6.1.5.2.3.1", 1); if (ctx->id_pkinit_authData == NULL) return ENOMEM; ctx->id_pkinit_DHKeyData = OBJ_txt2obj("1.3.6.1.5.2.3.2", 1); if (ctx->id_pkinit_DHKeyData == NULL) return ENOMEM; ctx->id_pkinit_rkeyData = OBJ_txt2obj("1.3.6.1.5.2.3.3", 1); if (ctx->id_pkinit_rkeyData == NULL) return ENOMEM; ctx->id_pkinit_KPClientAuth = OBJ_txt2obj("1.3.6.1.5.2.3.4", 1); if (ctx->id_pkinit_KPClientAuth == NULL) return ENOMEM; ctx->id_pkinit_KPKdc = OBJ_txt2obj("1.3.6.1.5.2.3.5", 1); if (ctx->id_pkinit_KPKdc == NULL) return ENOMEM; ctx->id_ms_kp_sc_logon = OBJ_txt2obj("1.3.6.1.4.1.311.20.2.2", 1); if (ctx->id_ms_kp_sc_logon == NULL) return ENOMEM; ctx->id_ms_san_upn = OBJ_txt2obj("1.3.6.1.4.1.311.20.2.3", 1); if (ctx->id_ms_san_upn == NULL) return ENOMEM; ctx->id_kp_serverAuth = OBJ_txt2obj("1.3.6.1.5.5.7.3.1", 1); if (ctx->id_kp_serverAuth == NULL) return ENOMEM; return 0; } static krb5_error_code get_cert(char *filename, X509 **retcert) { X509 *cert = NULL; BIO *tmp = NULL; int code; krb5_error_code retval; if (filename == NULL || retcert == NULL) return EINVAL; *retcert = NULL; tmp = BIO_new(BIO_s_file()); if (tmp == NULL) return ENOMEM; code = BIO_read_filename(tmp, filename); if (code == 0) { retval = errno; goto cleanup; } cert = (X509 *) PEM_read_bio_X509(tmp, NULL, NULL, NULL); if (cert == NULL) { retval = EIO; pkiDebug("failed to read certificate from %s\n", filename); goto cleanup; } *retcert = cert; retval = 0; cleanup: if (tmp != NULL) BIO_free(tmp); return retval; } struct get_key_cb_data { krb5_context context; pkinit_identity_crypto_context id_cryptoctx; const char *fsname; char *filename; const char *password; }; static int get_key_cb(char *buf, int size, int rwflag, void *userdata) { struct get_key_cb_data *data = userdata; pkinit_identity_crypto_context id_cryptoctx; krb5_data rdat; krb5_prompt kprompt; krb5_prompt_type prompt_type; krb5_error_code retval; char *prompt; if (data->id_cryptoctx->defer_id_prompt) { /* Supply the identity name to be passed to a responder callback. */ pkinit_set_deferred_id(&data->id_cryptoctx->deferred_ids, data->fsname, 0, NULL); return -1; } if (data->password == NULL) { /* We don't already have a password to use, so prompt for one. */ if (data->id_cryptoctx->prompter == NULL) return -1; if (asprintf(&prompt, "%s %s", _("Pass phrase for"), data->filename) < 0) return -1; rdat.data = buf; rdat.length = size; kprompt.prompt = prompt; kprompt.hidden = 1; kprompt.reply = &rdat; prompt_type = KRB5_PROMPT_TYPE_PREAUTH; /* PROMPTER_INVOCATION */ k5int_set_prompt_types(data->context, &prompt_type); id_cryptoctx = data->id_cryptoctx; retval = (data->id_cryptoctx->prompter)(data->context, id_cryptoctx->prompter_data, NULL, NULL, 1, &kprompt); k5int_set_prompt_types(data->context, 0); free(prompt); if (retval != 0) return -1; } else { /* Just use the already-supplied password. */ rdat.length = strlen(data->password); if ((int)rdat.length >= size) return -1; snprintf(buf, size, "%s", data->password); } return (int)rdat.length; } static krb5_error_code get_key(krb5_context context, pkinit_identity_crypto_context id_cryptoctx, char *filename, const char *fsname, EVP_PKEY **retkey, const char *password) { EVP_PKEY *pkey = NULL; BIO *tmp = NULL; struct get_key_cb_data cb_data; int code; krb5_error_code retval; if (filename == NULL || retkey == NULL) return EINVAL; tmp = BIO_new(BIO_s_file()); if (tmp == NULL) return ENOMEM; code = BIO_read_filename(tmp, filename); if (code == 0) { retval = errno; goto cleanup; } cb_data.context = context; cb_data.id_cryptoctx = id_cryptoctx; cb_data.filename = filename; cb_data.fsname = fsname; cb_data.password = password; pkey = PEM_read_bio_PrivateKey(tmp, NULL, get_key_cb, &cb_data); if (pkey == NULL && !id_cryptoctx->defer_id_prompt) { retval = EIO; pkiDebug("failed to read private key from %s\n", filename); goto cleanup; } *retkey = pkey; retval = 0; cleanup: if (tmp != NULL) BIO_free(tmp); return retval; } static void pkinit_fini_pkinit_oids(pkinit_plg_crypto_context ctx) { if (ctx == NULL) return; ASN1_OBJECT_free(ctx->id_pkinit_san); ASN1_OBJECT_free(ctx->id_pkinit_authData); ASN1_OBJECT_free(ctx->id_pkinit_DHKeyData); ASN1_OBJECT_free(ctx->id_pkinit_rkeyData); ASN1_OBJECT_free(ctx->id_pkinit_KPClientAuth); ASN1_OBJECT_free(ctx->id_pkinit_KPKdc); ASN1_OBJECT_free(ctx->id_ms_kp_sc_logon); ASN1_OBJECT_free(ctx->id_ms_san_upn); ASN1_OBJECT_free(ctx->id_kp_serverAuth); } /* Construct an OpenSSL DH object for an Oakley group. */ static DH * make_oakley_dh(uint8_t *prime, size_t len) { DH *dh = NULL; BIGNUM *p = NULL, *q = NULL, *g = NULL; p = BN_bin2bn(prime, len, NULL); if (p == NULL) goto cleanup; q = BN_new(); if (q == NULL) goto cleanup; if (!BN_rshift1(q, p)) goto cleanup; g = BN_new(); if (g == NULL) goto cleanup; if (!BN_set_word(g, DH_GENERATOR_2)) goto cleanup; dh = DH_new(); if (dh == NULL) goto cleanup; DH_set0_pqg(dh, p, q, g); p = g = q = NULL; cleanup: BN_free(p); BN_free(q); BN_free(g); return dh; } static krb5_error_code pkinit_init_dh_params(pkinit_plg_crypto_context plgctx) { krb5_error_code retval = ENOMEM; plgctx->dh_1024 = make_oakley_dh(oakley_1024, sizeof(oakley_1024)); if (plgctx->dh_1024 == NULL) goto cleanup; plgctx->dh_2048 = make_oakley_dh(oakley_2048, sizeof(oakley_2048)); if (plgctx->dh_2048 == NULL) goto cleanup; plgctx->dh_4096 = make_oakley_dh(oakley_4096, sizeof(oakley_4096)); if (plgctx->dh_4096 == NULL) goto cleanup; retval = 0; cleanup: if (retval) pkinit_fini_dh_params(plgctx); return retval; } static void pkinit_fini_dh_params(pkinit_plg_crypto_context plgctx) { if (plgctx->dh_1024 != NULL) DH_free(plgctx->dh_1024); if (plgctx->dh_2048 != NULL) DH_free(plgctx->dh_2048); if (plgctx->dh_4096 != NULL) DH_free(plgctx->dh_4096); plgctx->dh_1024 = plgctx->dh_2048 = plgctx->dh_4096 = NULL; } static krb5_error_code pkinit_init_certs(pkinit_identity_crypto_context ctx) { krb5_error_code retval = ENOMEM; int i; for (i = 0; i < MAX_CREDS_ALLOWED; i++) ctx->creds[i] = NULL; ctx->my_certs = NULL; ctx->cert_index = 0; ctx->my_key = NULL; ctx->trustedCAs = NULL; ctx->intermediateCAs = NULL; ctx->revoked = NULL; retval = 0; return retval; } static void pkinit_fini_certs(pkinit_identity_crypto_context ctx) { if (ctx == NULL) return; if (ctx->my_certs != NULL) sk_X509_pop_free(ctx->my_certs, X509_free); if (ctx->my_key != NULL) EVP_PKEY_free(ctx->my_key); if (ctx->trustedCAs != NULL) sk_X509_pop_free(ctx->trustedCAs, X509_free); if (ctx->intermediateCAs != NULL) sk_X509_pop_free(ctx->intermediateCAs, X509_free); if (ctx->revoked != NULL) sk_X509_CRL_pop_free(ctx->revoked, X509_CRL_free); } static krb5_error_code pkinit_init_pkcs11(pkinit_identity_crypto_context ctx) { krb5_error_code retval = ENOMEM; #ifndef WITHOUT_PKCS11 ctx->p11_module_name = strdup(PKCS11_MODNAME); if (ctx->p11_module_name == NULL) return retval; ctx->p11_module = NULL; ctx->slotid = PK_NOSLOT; ctx->token_label = NULL; ctx->cert_label = NULL; ctx->session = CK_INVALID_HANDLE; ctx->p11 = NULL; #endif ctx->pkcs11_method = 0; retval = 0; return retval; } static void pkinit_fini_pkcs11(pkinit_identity_crypto_context ctx) { #ifndef WITHOUT_PKCS11 if (ctx == NULL) return; if (ctx->p11 != NULL) { if (ctx->session != CK_INVALID_HANDLE) { ctx->p11->C_CloseSession(ctx->session); ctx->session = CK_INVALID_HANDLE; } ctx->p11->C_Finalize(NULL_PTR); ctx->p11 = NULL; } if (ctx->p11_module != NULL) { pkinit_C_UnloadModule(ctx->p11_module); ctx->p11_module = NULL; } free(ctx->p11_module_name); free(ctx->token_label); free(ctx->cert_id); free(ctx->cert_label); #endif } krb5_error_code pkinit_identity_set_prompter(pkinit_identity_crypto_context id_cryptoctx, krb5_prompter_fct prompter, void *prompter_data) { id_cryptoctx->prompter = prompter; id_cryptoctx->prompter_data = prompter_data; return 0; } /* Create a CMS ContentInfo of type oid containing the octet string in data. */ static krb5_error_code create_contentinfo(krb5_context context, ASN1_OBJECT *oid, unsigned char *data, size_t data_len, PKCS7 **p7_out) { PKCS7 *p7 = NULL; ASN1_OCTET_STRING *ostr = NULL; *p7_out = NULL; ostr = ASN1_OCTET_STRING_new(); if (ostr == NULL) goto oom; if (!ASN1_OCTET_STRING_set(ostr, (unsigned char *)data, data_len)) goto oom; p7 = PKCS7_new(); if (p7 == NULL) goto oom; p7->type = OBJ_dup(oid); if (p7->type == NULL) goto oom; if (OBJ_obj2nid(oid) == NID_pkcs7_data) { /* Draft 9 uses id-pkcs7-data for signed data. For this type OpenSSL * expects an octet string in d.data. */ p7->d.data = ostr; } else { p7->d.other = ASN1_TYPE_new(); if (p7->d.other == NULL) goto oom; p7->d.other->type = V_ASN1_OCTET_STRING; p7->d.other->value.octet_string = ostr; } *p7_out = p7; return 0; oom: if (ostr != NULL) ASN1_OCTET_STRING_free(ostr); if (p7 != NULL) PKCS7_free(p7); return ENOMEM; } krb5_error_code cms_contentinfo_create(krb5_context context, /* IN */ pkinit_plg_crypto_context plg_cryptoctx, /* IN */ pkinit_req_crypto_context req_cryptoctx, /* IN */ pkinit_identity_crypto_context id_cryptoctx, /* IN */ int cms_msg_type, unsigned char *data, unsigned int data_len, unsigned char **out_data, unsigned int *out_data_len) { krb5_error_code retval = ENOMEM; ASN1_OBJECT *oid; PKCS7 *p7 = NULL; unsigned char *p; /* Pick the correct oid for the eContentInfo. */ oid = pkinit_pkcs7type2oid(plg_cryptoctx, cms_msg_type); if (oid == NULL) goto cleanup; retval = create_contentinfo(context, oid, data, data_len, &p7); if (retval != 0) goto cleanup; *out_data_len = i2d_PKCS7(p7, NULL); if (!(*out_data_len)) { retval = oerr(context, 0, _("Failed to DER encode PKCS7")); goto cleanup; } retval = ENOMEM; if ((p = *out_data = malloc(*out_data_len)) == NULL) goto cleanup; /* DER encode PKCS7 data */ retval = i2d_PKCS7(p7, &p); if (!retval) { retval = oerr(context, 0, _("Failed to DER encode PKCS7")); goto cleanup; } retval = 0; cleanup: if (p7) PKCS7_free(p7); return retval; } krb5_error_code cms_signeddata_create(krb5_context context, pkinit_plg_crypto_context plg_cryptoctx, pkinit_req_crypto_context req_cryptoctx, pkinit_identity_crypto_context id_cryptoctx, int cms_msg_type, int include_certchain, unsigned char *data, unsigned int data_len, unsigned char **signed_data, unsigned int *signed_data_len) { krb5_error_code retval = ENOMEM; PKCS7 *p7 = NULL, *inner_p7 = NULL; PKCS7_SIGNED *p7s = NULL; PKCS7_SIGNER_INFO *p7si = NULL; unsigned char *p; STACK_OF(X509) * cert_stack = NULL; ASN1_OCTET_STRING *digest_attr = NULL; EVP_MD_CTX *ctx; const EVP_MD *md_tmp = NULL; unsigned char md_data[EVP_MAX_MD_SIZE], md_data2[EVP_MAX_MD_SIZE]; unsigned char *digestInfo_buf = NULL, *abuf = NULL; unsigned int md_len, md_len2, alen, digestInfo_len; STACK_OF(X509_ATTRIBUTE) * sk; unsigned char *sig = NULL; unsigned int sig_len = 0; X509_ALGOR *alg = NULL; ASN1_OCTET_STRING *digest = NULL; unsigned int alg_len = 0, digest_len = 0; unsigned char *y = NULL; X509 *cert = NULL; ASN1_OBJECT *oid = NULL, *oid_copy; /* Start creating PKCS7 data. */ if ((p7 = PKCS7_new()) == NULL) goto cleanup; p7->type = OBJ_nid2obj(NID_pkcs7_signed); if ((p7s = PKCS7_SIGNED_new()) == NULL) goto cleanup; p7->d.sign = p7s; if (!ASN1_INTEGER_set(p7s->version, 3)) goto cleanup; /* pick the correct oid for the eContentInfo */ oid = pkinit_pkcs7type2oid(plg_cryptoctx, cms_msg_type); if (oid == NULL) goto cleanup; if (id_cryptoctx->my_certs != NULL) { /* create a cert chain that has at least the signer's certificate */ if ((cert_stack = sk_X509_new_null()) == NULL) goto cleanup; cert = sk_X509_value(id_cryptoctx->my_certs, id_cryptoctx->cert_index); if (!include_certchain) { pkiDebug("only including signer's certificate\n"); sk_X509_push(cert_stack, X509_dup(cert)); } else { /* create a cert chain */ X509_STORE *certstore = NULL; X509_STORE_CTX *certctx; STACK_OF(X509) *certstack = NULL; char buf[DN_BUF_LEN]; unsigned int i = 0, size = 0; if ((certstore = X509_STORE_new()) == NULL) goto cleanup; pkiDebug("building certificate chain\n"); X509_STORE_set_verify_cb(certstore, openssl_callback); certctx = X509_STORE_CTX_new(); if (certctx == NULL) goto cleanup; X509_STORE_CTX_init(certctx, certstore, cert, id_cryptoctx->intermediateCAs); X509_STORE_CTX_trusted_stack(certctx, id_cryptoctx->trustedCAs); if (!X509_verify_cert(certctx)) { retval = oerr_cert(context, 0, certctx, _("Failed to verify own certificate")); goto cleanup; } certstack = X509_STORE_CTX_get1_chain(certctx); size = sk_X509_num(certstack); pkiDebug("size of certificate chain = %d\n", size); for(i = 0; i < size - 1; i++) { X509 *x = sk_X509_value(certstack, i); X509_NAME_oneline(X509_get_subject_name(x), buf, sizeof(buf)); pkiDebug("cert #%d: %s\n", i, buf); sk_X509_push(cert_stack, X509_dup(x)); } X509_STORE_CTX_free(certctx); X509_STORE_free(certstore); sk_X509_pop_free(certstack, X509_free); } p7s->cert = cert_stack; /* fill-in PKCS7_SIGNER_INFO */ if ((p7si = PKCS7_SIGNER_INFO_new()) == NULL) goto cleanup; if (!ASN1_INTEGER_set(p7si->version, 1)) goto cleanup; if (!X509_NAME_set(&p7si->issuer_and_serial->issuer, X509_get_issuer_name(cert))) goto cleanup; /* because ASN1_INTEGER_set is used to set a 'long' we will do * things the ugly way. */ ASN1_INTEGER_free(p7si->issuer_and_serial->serial); if (!(p7si->issuer_and_serial->serial = ASN1_INTEGER_dup(X509_get_serialNumber(cert)))) goto cleanup; /* will not fill-out EVP_PKEY because it's on the smartcard */ /* Set digest algs */ p7si->digest_alg->algorithm = OBJ_nid2obj(NID_sha1); if (p7si->digest_alg->parameter != NULL) ASN1_TYPE_free(p7si->digest_alg->parameter); if ((p7si->digest_alg->parameter = ASN1_TYPE_new()) == NULL) goto cleanup; p7si->digest_alg->parameter->type = V_ASN1_NULL; /* Set sig algs */ if (p7si->digest_enc_alg->parameter != NULL) ASN1_TYPE_free(p7si->digest_enc_alg->parameter); p7si->digest_enc_alg->algorithm = OBJ_nid2obj(NID_sha1WithRSAEncryption); if (!(p7si->digest_enc_alg->parameter = ASN1_TYPE_new())) goto cleanup; p7si->digest_enc_alg->parameter->type = V_ASN1_NULL; if (cms_msg_type == CMS_SIGN_DRAFT9){ /* don't include signed attributes for pa-type 15 request */ abuf = data; alen = data_len; } else { /* add signed attributes */ /* compute sha1 digest over the EncapsulatedContentInfo */ ctx = EVP_MD_CTX_new(); if (ctx == NULL) goto cleanup; EVP_DigestInit_ex(ctx, EVP_sha1(), NULL); EVP_DigestUpdate(ctx, data, data_len); md_tmp = EVP_MD_CTX_md(ctx); EVP_DigestFinal_ex(ctx, md_data, &md_len); EVP_MD_CTX_free(ctx); /* create a message digest attr */ digest_attr = ASN1_OCTET_STRING_new(); ASN1_OCTET_STRING_set(digest_attr, md_data, (int)md_len); PKCS7_add_signed_attribute(p7si, NID_pkcs9_messageDigest, V_ASN1_OCTET_STRING, (char *) digest_attr); /* create a content-type attr */ oid_copy = OBJ_dup(oid); if (oid_copy == NULL) goto cleanup2; PKCS7_add_signed_attribute(p7si, NID_pkcs9_contentType, V_ASN1_OBJECT, oid_copy); /* create the signature over signed attributes. get DER encoded value */ /* This is the place where smartcard signature needs to be calculated */ sk = p7si->auth_attr; alen = ASN1_item_i2d((ASN1_VALUE *) sk, &abuf, ASN1_ITEM_rptr(PKCS7_ATTR_SIGN)); if (abuf == NULL) goto cleanup2; } /* signed attributes */ #ifndef WITHOUT_PKCS11 /* Some tokens can only do RSAEncryption without sha1 hash */ /* to compute sha1WithRSAEncryption, encode the algorithm ID for the hash * function and the hash value into an ASN.1 value of type DigestInfo * DigestInfo::=SEQUENCE { * digestAlgorithm AlgorithmIdentifier, * digest OCTET STRING } */ if (id_cryptoctx->pkcs11_method == 1 && id_cryptoctx->mech == CKM_RSA_PKCS) { pkiDebug("mech = CKM_RSA_PKCS\n"); ctx = EVP_MD_CTX_new(); if (ctx == NULL) goto cleanup; /* if this is not draft9 request, include digest signed attribute */ if (cms_msg_type != CMS_SIGN_DRAFT9) EVP_DigestInit_ex(ctx, md_tmp, NULL); else EVP_DigestInit_ex(ctx, EVP_sha1(), NULL); EVP_DigestUpdate(ctx, abuf, alen); EVP_DigestFinal_ex(ctx, md_data2, &md_len2); EVP_MD_CTX_free(ctx); alg = X509_ALGOR_new(); if (alg == NULL) goto cleanup2; X509_ALGOR_set0(alg, OBJ_nid2obj(NID_sha1), V_ASN1_NULL, NULL); alg_len = i2d_X509_ALGOR(alg, NULL); digest = ASN1_OCTET_STRING_new(); if (digest == NULL) goto cleanup2; ASN1_OCTET_STRING_set(digest, md_data2, (int)md_len2); digest_len = i2d_ASN1_OCTET_STRING(digest, NULL); digestInfo_len = ASN1_object_size(1, (int)(alg_len + digest_len), V_ASN1_SEQUENCE); y = digestInfo_buf = malloc(digestInfo_len); if (digestInfo_buf == NULL) goto cleanup2; ASN1_put_object(&y, 1, (int)(alg_len + digest_len), V_ASN1_SEQUENCE, V_ASN1_UNIVERSAL); i2d_X509_ALGOR(alg, &y); i2d_ASN1_OCTET_STRING(digest, &y); #ifdef DEBUG_SIG pkiDebug("signing buffer\n"); print_buffer(digestInfo_buf, digestInfo_len); print_buffer_bin(digestInfo_buf, digestInfo_len, "/tmp/pkcs7_tosign"); #endif retval = pkinit_sign_data(context, id_cryptoctx, digestInfo_buf, digestInfo_len, &sig, &sig_len); } else #endif { pkiDebug("mech = %s\n", id_cryptoctx->pkcs11_method == 1 ? "CKM_SHA1_RSA_PKCS" : "FS"); retval = pkinit_sign_data(context, id_cryptoctx, abuf, alen, &sig, &sig_len); } #ifdef DEBUG_SIG print_buffer(sig, sig_len); #endif if (cms_msg_type != CMS_SIGN_DRAFT9 ) free(abuf); if (retval) goto cleanup2; /* Add signature */ if (!ASN1_STRING_set(p7si->enc_digest, (unsigned char *) sig, (int)sig_len)) { retval = oerr(context, 0, _("Failed to add digest attribute")); goto cleanup2; } /* adder signer_info to pkcs7 signed */ if (!PKCS7_add_signer(p7, p7si)) goto cleanup2; } /* we have a certificate */ /* start on adding data to the pkcs7 signed */ retval = create_contentinfo(context, oid, data, data_len, &inner_p7); if (p7s->contents != NULL) PKCS7_free(p7s->contents); p7s->contents = inner_p7; *signed_data_len = i2d_PKCS7(p7, NULL); if (!(*signed_data_len)) { retval = oerr(context, 0, _("Failed to DER encode PKCS7")); goto cleanup2; } retval = ENOMEM; if ((p = *signed_data = malloc(*signed_data_len)) == NULL) goto cleanup2; /* DER encode PKCS7 data */ retval = i2d_PKCS7(p7, &p); if (!retval) { retval = oerr(context, 0, _("Failed to DER encode PKCS7")); goto cleanup2; } retval = 0; #ifdef DEBUG_ASN1 if (cms_msg_type == CMS_SIGN_CLIENT) { print_buffer_bin(*signed_data, *signed_data_len, "/tmp/client_pkcs7_signeddata"); } else { if (cms_msg_type == CMS_SIGN_SERVER) { print_buffer_bin(*signed_data, *signed_data_len, "/tmp/kdc_pkcs7_signeddata"); } else { print_buffer_bin(*signed_data, *signed_data_len, "/tmp/draft9_pkcs7_signeddata"); } } #endif cleanup2: if (p7si) { if (cms_msg_type != CMS_SIGN_DRAFT9) #ifndef WITHOUT_PKCS11 if (id_cryptoctx->pkcs11_method == 1 && id_cryptoctx->mech == CKM_RSA_PKCS) { free(digestInfo_buf); if (digest != NULL) ASN1_OCTET_STRING_free(digest); } #endif if (alg != NULL) X509_ALGOR_free(alg); } cleanup: if (p7 != NULL) PKCS7_free(p7); free(sig); return retval; } krb5_error_code cms_signeddata_verify(krb5_context context, pkinit_plg_crypto_context plgctx, pkinit_req_crypto_context reqctx, pkinit_identity_crypto_context idctx, int cms_msg_type, int require_crl_checking, unsigned char *signed_data, unsigned int signed_data_len, unsigned char **data, unsigned int *data_len, unsigned char **authz_data, unsigned int *authz_data_len, int *is_signed) { /* * Warning: Since most openssl functions do not set retval, large chunks of * this function assume that retval is always a failure and may go to * cleanup without setting retval explicitly. Make sure retval is not set * to 0 or errors such as signature verification failure may be converted * to success with significant security consequences. */ krb5_error_code retval = KRB5KDC_ERR_PREAUTH_FAILED; CMS_ContentInfo *cms = NULL; BIO *out = NULL; int flags = CMS_NO_SIGNER_CERT_VERIFY; int valid_oid = 0; unsigned int i = 0; unsigned int vflags = 0, size = 0; const unsigned char *p = signed_data; STACK_OF(CMS_SignerInfo) *si_sk = NULL; CMS_SignerInfo *si = NULL; X509 *x = NULL; X509_STORE *store = NULL; X509_STORE_CTX *cert_ctx; STACK_OF(X509) *signerCerts = NULL; STACK_OF(X509) *intermediateCAs = NULL; STACK_OF(X509_CRL) *signerRevoked = NULL; STACK_OF(X509_CRL) *revoked = NULL; STACK_OF(X509) *verified_chain = NULL; ASN1_OBJECT *oid = NULL; const ASN1_OBJECT *type = NULL, *etype = NULL; ASN1_OCTET_STRING **octets; krb5_external_principal_identifier **krb5_verified_chain = NULL; krb5_data *authz = NULL; char buf[DN_BUF_LEN]; #ifdef DEBUG_ASN1 print_buffer_bin(signed_data, signed_data_len, "/tmp/client_received_pkcs7_signeddata"); #endif if (is_signed) *is_signed = 1; oid = pkinit_pkcs7type2oid(plgctx, cms_msg_type); if (oid == NULL) goto cleanup; /* decode received CMS message */ if ((cms = d2i_CMS_ContentInfo(NULL, &p, (int)signed_data_len)) == NULL) { retval = oerr(context, 0, _("Failed to decode CMS message")); goto cleanup; } etype = CMS_get0_eContentType(cms); /* * Prior to 1.10 the MIT client incorrectly emitted the pkinit structure * directly in a CMS ContentInfo rather than using SignedData with no * signers. Handle that case. */ type = CMS_get0_type(cms); if (is_signed && !OBJ_cmp(type, oid)) { unsigned char *d; *is_signed = 0; octets = pkinit_CMS_get0_content_data(cms); if (!octets || ((*octets)->type != V_ASN1_OCTET_STRING)) { retval = KRB5KDC_ERR_PREAUTH_FAILED; krb5_set_error_message(context, retval, _("Invalid pkinit packet: octet string " "expected")); goto cleanup; } *data_len = ASN1_STRING_length(*octets); d = malloc(*data_len); if (d == NULL) { retval = ENOMEM; goto cleanup; } memcpy(d, ASN1_STRING_get0_data(*octets), *data_len); *data = d; goto out; } else { /* Verify that the received message is CMS SignedData message. */ if (OBJ_obj2nid(type) != NID_pkcs7_signed) { pkiDebug("Expected id-signedData CMS msg (received type = %d)\n", OBJ_obj2nid(type)); krb5_set_error_message(context, retval, _("wrong oid\n")); goto cleanup; } } /* setup to verify X509 certificate used to sign CMS message */ if (!(store = X509_STORE_new())) goto cleanup; /* check if we are inforcing CRL checking */ vflags = X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL; if (require_crl_checking) X509_STORE_set_verify_cb(store, openssl_callback); else X509_STORE_set_verify_cb(store, openssl_callback_ignore_crls); X509_STORE_set_flags(store, vflags); /* * Get the signer's information from the CMS message. Match signer ID * against anchors and intermediate CAs in case no certs are present in the * SignedData. If we start sending kdcPkId values in requests, we'll need * to match against the source of that information too. */ CMS_set1_signers_certs(cms, NULL, 0); CMS_set1_signers_certs(cms, idctx->trustedCAs, CMS_NOINTERN); CMS_set1_signers_certs(cms, idctx->intermediateCAs, CMS_NOINTERN); if (((si_sk = CMS_get0_SignerInfos(cms)) == NULL) || ((si = sk_CMS_SignerInfo_value(si_sk, 0)) == NULL)) { /* Not actually signed; anonymous case */ if (!is_signed) goto cleanup; *is_signed = 0; /* We cannot use CMS_dataInit because there may be no digest */ octets = pkinit_CMS_get0_content_signed(cms); if (octets) out = BIO_new_mem_buf((*octets)->data, (*octets)->length); if (out == NULL) goto cleanup; } else { pkinit_CMS_SignerInfo_get_cert(cms, si, &x); if (x == NULL) goto cleanup; /* create available CRL information (get local CRLs and include CRLs * received in the CMS message */ signerRevoked = CMS_get1_crls(cms); if (idctx->revoked == NULL) revoked = signerRevoked; else if (signerRevoked == NULL) revoked = idctx->revoked; else { size = sk_X509_CRL_num(idctx->revoked); revoked = sk_X509_CRL_new_null(); for (i = 0; i < size; i++) sk_X509_CRL_push(revoked, sk_X509_CRL_value(idctx->revoked, i)); size = sk_X509_CRL_num(signerRevoked); for (i = 0; i < size; i++) sk_X509_CRL_push(revoked, sk_X509_CRL_value(signerRevoked, i)); } /* create available intermediate CAs chains (get local intermediateCAs and * include the CA chain received in the CMS message */ signerCerts = CMS_get1_certs(cms); if (idctx->intermediateCAs == NULL) intermediateCAs = signerCerts; else if (signerCerts == NULL) intermediateCAs = idctx->intermediateCAs; else { size = sk_X509_num(idctx->intermediateCAs); intermediateCAs = sk_X509_new_null(); for (i = 0; i < size; i++) { sk_X509_push(intermediateCAs, sk_X509_value(idctx->intermediateCAs, i)); } size = sk_X509_num(signerCerts); for (i = 0; i < size; i++) { sk_X509_push(intermediateCAs, sk_X509_value(signerCerts, i)); } } /* initialize x509 context with the received certificate and * trusted and intermediate CA chains and CRLs */ cert_ctx = X509_STORE_CTX_new(); if (cert_ctx == NULL) goto cleanup; if (!X509_STORE_CTX_init(cert_ctx, store, x, intermediateCAs)) goto cleanup; X509_STORE_CTX_set0_crls(cert_ctx, revoked); /* add trusted CAs certificates for cert verification */ if (idctx->trustedCAs != NULL) X509_STORE_CTX_trusted_stack(cert_ctx, idctx->trustedCAs); else { pkiDebug("unable to find any trusted CAs\n"); goto cleanup; } #ifdef DEBUG_CERTCHAIN if (intermediateCAs != NULL) { size = sk_X509_num(intermediateCAs); pkiDebug("untrusted cert chain of size %d\n", size); for (i = 0; i < size; i++) { X509_NAME_oneline(X509_get_subject_name( sk_X509_value(intermediateCAs, i)), buf, sizeof(buf)); pkiDebug("cert #%d: %s\n", i, buf); } } if (idctx->trustedCAs != NULL) { size = sk_X509_num(idctx->trustedCAs); pkiDebug("trusted cert chain of size %d\n", size); for (i = 0; i < size; i++) { X509_NAME_oneline(X509_get_subject_name( sk_X509_value(idctx->trustedCAs, i)), buf, sizeof(buf)); pkiDebug("cert #%d: %s\n", i, buf); } } if (revoked != NULL) { size = sk_X509_CRL_num(revoked); pkiDebug("CRL chain of size %d\n", size); for (i = 0; i < size; i++) { X509_CRL *crl = sk_X509_CRL_value(revoked, i); X509_NAME_oneline(X509_CRL_get_issuer(crl), buf, sizeof(buf)); pkiDebug("crls by CA #%d: %s\n", i , buf); } } #endif i = X509_verify_cert(cert_ctx); if (i <= 0) { int j = X509_STORE_CTX_get_error(cert_ctx); X509 *cert; cert = X509_STORE_CTX_get_current_cert(cert_ctx); reqctx->received_cert = X509_dup(cert); switch(j) { case X509_V_ERR_CERT_REVOKED: retval = KRB5KDC_ERR_REVOKED_CERTIFICATE; break; case X509_V_ERR_UNABLE_TO_GET_CRL: retval = KRB5KDC_ERR_REVOCATION_STATUS_UNKNOWN; break; case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT: case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY: retval = KRB5KDC_ERR_CANT_VERIFY_CERTIFICATE; break; default: retval = KRB5KDC_ERR_INVALID_CERTIFICATE; } (void)oerr_cert(context, retval, cert_ctx, _("Failed to verify received certificate")); if (reqctx->received_cert == NULL) strlcpy(buf, "(none)", sizeof(buf)); else X509_NAME_oneline(X509_get_subject_name(reqctx->received_cert), buf, sizeof(buf)); pkiDebug("problem with cert DN = %s (error=%d) %s\n", buf, j, X509_verify_cert_error_string(j)); #ifdef DEBUG_CERTCHAIN size = sk_X509_num(signerCerts); pkiDebug("received cert chain of size %d\n", size); for (j = 0; j < size; j++) { X509 *tmp_cert = sk_X509_value(signerCerts, j); X509_NAME_oneline(X509_get_subject_name(tmp_cert), buf, sizeof(buf)); pkiDebug("cert #%d: %s\n", j, buf); } #endif } else { /* retrieve verified certificate chain */ if (cms_msg_type == CMS_SIGN_CLIENT || cms_msg_type == CMS_SIGN_DRAFT9) verified_chain = X509_STORE_CTX_get1_chain(cert_ctx); } X509_STORE_CTX_free(cert_ctx); if (i <= 0) goto cleanup; out = BIO_new(BIO_s_mem()); if (cms_msg_type == CMS_SIGN_DRAFT9) flags |= CMS_NOATTR; if (CMS_verify(cms, NULL, store, NULL, out, flags) == 0) { unsigned long err = ERR_peek_error(); switch(ERR_GET_REASON(err)) { case PKCS7_R_DIGEST_FAILURE: retval = KRB5KDC_ERR_DIGEST_IN_SIGNED_DATA_NOT_ACCEPTED; break; case PKCS7_R_SIGNATURE_FAILURE: default: retval = KRB5KDC_ERR_INVALID_SIG; } (void)oerr(context, retval, _("Failed to verify CMS message")); goto cleanup; } } /* message was signed */ if (!OBJ_cmp(etype, oid)) valid_oid = 1; else if (cms_msg_type == CMS_SIGN_DRAFT9) { /* * Various implementations of the pa-type 15 request use * different OIDS. We check that the returned object * has any of the acceptable OIDs */ ASN1_OBJECT *client_oid = NULL, *server_oid = NULL, *rsa_oid = NULL; client_oid = pkinit_pkcs7type2oid(plgctx, CMS_SIGN_CLIENT); server_oid = pkinit_pkcs7type2oid(plgctx, CMS_SIGN_SERVER); rsa_oid = pkinit_pkcs7type2oid(plgctx, CMS_ENVEL_SERVER); if (!OBJ_cmp(etype, client_oid) || !OBJ_cmp(etype, server_oid) || !OBJ_cmp(etype, rsa_oid)) valid_oid = 1; } if (valid_oid) pkiDebug("CMS Verification successful\n"); else { pkiDebug("wrong oid in eContentType\n"); print_buffer(OBJ_get0_data(etype), OBJ_length(etype)); retval = KRB5KDC_ERR_PREAUTH_FAILED; krb5_set_error_message(context, retval, "wrong oid\n"); goto cleanup; } /* transfer the data from CMS message into return buffer */ for (size = 0;;) { int remain; retval = ENOMEM; if ((*data = realloc(*data, size + 1024 * 10)) == NULL) goto cleanup; remain = BIO_read(out, &((*data)[size]), 1024 * 10); if (remain <= 0) break; else size += remain; } *data_len = size; if (x) { reqctx->received_cert = X509_dup(x); /* generate authorization data */ if (cms_msg_type == CMS_SIGN_CLIENT || cms_msg_type == CMS_SIGN_DRAFT9) { if (authz_data == NULL || authz_data_len == NULL) goto out; *authz_data = NULL; retval = create_identifiers_from_stack(verified_chain, &krb5_verified_chain); if (retval) { pkiDebug("create_identifiers_from_stack failed\n"); goto cleanup; } retval = k5int_encode_krb5_td_trusted_certifiers((krb5_external_principal_identifier *const *)krb5_verified_chain, &authz); if (retval) { pkiDebug("encode_krb5_td_trusted_certifiers failed\n"); goto cleanup; } #ifdef DEBUG_ASN1 print_buffer_bin((unsigned char *)authz->data, authz->length, "/tmp/kdc_ad_initial_verified_cas"); #endif *authz_data = malloc(authz->length); if (*authz_data == NULL) { retval = ENOMEM; goto cleanup; } memcpy(*authz_data, authz->data, authz->length); *authz_data_len = authz->length; } } out: retval = 0; cleanup: if (out != NULL) BIO_free(out); if (store != NULL) X509_STORE_free(store); if (cms != NULL) { if (signerCerts != NULL) pkinit_CMS_free1_certs(signerCerts); if (idctx->intermediateCAs != NULL && signerCerts) sk_X509_free(intermediateCAs); if (signerRevoked != NULL) pkinit_CMS_free1_crls(signerRevoked); if (idctx->revoked != NULL && signerRevoked) sk_X509_CRL_free(revoked); CMS_ContentInfo_free(cms); } if (verified_chain != NULL) sk_X509_pop_free(verified_chain, X509_free); if (krb5_verified_chain != NULL) free_krb5_external_principal_identifier(&krb5_verified_chain); if (authz != NULL) krb5_free_data(context, authz); return retval; } krb5_error_code cms_envelopeddata_create(krb5_context context, pkinit_plg_crypto_context plgctx, pkinit_req_crypto_context reqctx, pkinit_identity_crypto_context idctx, krb5_preauthtype pa_type, int include_certchain, unsigned char *key_pack, unsigned int key_pack_len, unsigned char **out, unsigned int *out_len) { krb5_error_code retval = ENOMEM; PKCS7 *p7 = NULL; BIO *in = NULL; unsigned char *p = NULL, *signed_data = NULL, *enc_data = NULL; int signed_data_len = 0, enc_data_len = 0, flags = PKCS7_BINARY; STACK_OF(X509) *encerts = NULL; const EVP_CIPHER *cipher = NULL; int cms_msg_type; /* create the PKCS7 SignedData portion of the PKCS7 EnvelopedData */ switch ((int)pa_type) { case KRB5_PADATA_PK_AS_REQ_OLD: case KRB5_PADATA_PK_AS_REP_OLD: cms_msg_type = CMS_SIGN_DRAFT9; break; case KRB5_PADATA_PK_AS_REQ: cms_msg_type = CMS_ENVEL_SERVER; break; default: goto cleanup; } retval = cms_signeddata_create(context, plgctx, reqctx, idctx, cms_msg_type, include_certchain, key_pack, key_pack_len, &signed_data, (unsigned int *)&signed_data_len); if (retval) { pkiDebug("failed to create pkcs7 signed data\n"); goto cleanup; } /* check we have client's certificate */ if (reqctx->received_cert == NULL) { retval = KRB5KDC_ERR_PREAUTH_FAILED; goto cleanup; } encerts = sk_X509_new_null(); sk_X509_push(encerts, reqctx->received_cert); cipher = EVP_des_ede3_cbc(); in = BIO_new(BIO_s_mem()); switch (pa_type) { case KRB5_PADATA_PK_AS_REQ: prepare_enc_data(signed_data, signed_data_len, &enc_data, &enc_data_len); retval = BIO_write(in, enc_data, enc_data_len); if (retval != enc_data_len) { pkiDebug("BIO_write only wrote %d\n", retval); goto cleanup; } break; case KRB5_PADATA_PK_AS_REP_OLD: case KRB5_PADATA_PK_AS_REQ_OLD: retval = BIO_write(in, signed_data, signed_data_len); if (retval != signed_data_len) { pkiDebug("BIO_write only wrote %d\n", retval); goto cleanup; } break; default: retval = -1; goto cleanup; } p7 = PKCS7_encrypt(encerts, in, cipher, flags); if (p7 == NULL) { retval = oerr(context, 0, _("Failed to encrypt PKCS7 object")); goto cleanup; } switch (pa_type) { case KRB5_PADATA_PK_AS_REQ: p7->d.enveloped->enc_data->content_type = OBJ_nid2obj(NID_pkcs7_signed); break; case KRB5_PADATA_PK_AS_REP_OLD: case KRB5_PADATA_PK_AS_REQ_OLD: p7->d.enveloped->enc_data->content_type = OBJ_nid2obj(NID_pkcs7_data); break; break; break; break; } *out_len = i2d_PKCS7(p7, NULL); if (!*out_len || (p = *out = malloc(*out_len)) == NULL) { retval = ENOMEM; goto cleanup; } retval = i2d_PKCS7(p7, &p); if (!retval) { retval = oerr(context, 0, _("Failed to DER encode PKCS7")); goto cleanup; } retval = 0; #ifdef DEBUG_ASN1 print_buffer_bin(*out, *out_len, "/tmp/kdc_enveloped_data"); #endif cleanup: if (p7 != NULL) PKCS7_free(p7); if (in != NULL) BIO_free(in); free(signed_data); free(enc_data); if (encerts != NULL) sk_X509_free(encerts); return retval; } krb5_error_code cms_envelopeddata_verify(krb5_context context, pkinit_plg_crypto_context plg_cryptoctx, pkinit_req_crypto_context req_cryptoctx, pkinit_identity_crypto_context id_cryptoctx, krb5_preauthtype pa_type, int require_crl_checking, unsigned char *enveloped_data, unsigned int enveloped_data_len, unsigned char **data, unsigned int *data_len) { krb5_error_code retval = KRB5KDC_ERR_PREAUTH_FAILED; PKCS7 *p7 = NULL; BIO *out = NULL; int i = 0; unsigned int size = 0; const unsigned char *p = enveloped_data; unsigned int tmp_buf_len = 0, tmp_buf2_len = 0, vfy_buf_len = 0; unsigned char *tmp_buf = NULL, *tmp_buf2 = NULL, *vfy_buf = NULL; int msg_type = 0; #ifdef DEBUG_ASN1 print_buffer_bin(enveloped_data, enveloped_data_len, "/tmp/client_envelopeddata"); #endif /* decode received PKCS7 message */ if ((p7 = d2i_PKCS7(NULL, &p, (int)enveloped_data_len)) == NULL) { retval = oerr(context, 0, _("Failed to decode PKCS7")); goto cleanup; } /* verify that the received message is PKCS7 EnvelopedData message */ if (OBJ_obj2nid(p7->type) != NID_pkcs7_enveloped) { pkiDebug("Expected id-enveloped PKCS7 msg (received type = %d)\n", OBJ_obj2nid(p7->type)); krb5_set_error_message(context, retval, "wrong oid\n"); goto cleanup; } /* decrypt received PKCS7 message */ out = BIO_new(BIO_s_mem()); if (pkcs7_decrypt(context, id_cryptoctx, p7, out)) { pkiDebug("PKCS7 decryption successful\n"); } else { retval = oerr(context, 0, _("Failed to decrypt PKCS7 message")); goto cleanup; } /* transfer the decoded PKCS7 SignedData message into a separate buffer */ for (;;) { if ((tmp_buf = realloc(tmp_buf, size + 1024 * 10)) == NULL) goto cleanup; i = BIO_read(out, &(tmp_buf[size]), 1024 * 10); if (i <= 0) break; else size += i; } tmp_buf_len = size; #ifdef DEBUG_ASN1 print_buffer_bin(tmp_buf, tmp_buf_len, "/tmp/client_enc_keypack"); #endif /* verify PKCS7 SignedData message */ switch (pa_type) { case KRB5_PADATA_PK_AS_REP: msg_type = CMS_ENVEL_SERVER; break; case KRB5_PADATA_PK_AS_REP_OLD: msg_type = CMS_SIGN_DRAFT9; break; default: pkiDebug("%s: unrecognized pa_type = %d\n", __FUNCTION__, pa_type); retval = KRB5KDC_ERR_PREAUTH_FAILED; goto cleanup; } /* * If this is the RFC style, wrap the signed data to make * decoding easier in the verify routine. * For draft9-compatible, we don't do anything because it * is already wrapped. */ if (msg_type == CMS_ENVEL_SERVER) { retval = wrap_signeddata(tmp_buf, tmp_buf_len, &tmp_buf2, &tmp_buf2_len); if (retval) { pkiDebug("failed to encode signeddata\n"); goto cleanup; } vfy_buf = tmp_buf2; vfy_buf_len = tmp_buf2_len; } else { vfy_buf = tmp_buf; vfy_buf_len = tmp_buf_len; } #ifdef DEBUG_ASN1 print_buffer_bin(vfy_buf, vfy_buf_len, "/tmp/client_enc_keypack2"); #endif retval = cms_signeddata_verify(context, plg_cryptoctx, req_cryptoctx, id_cryptoctx, msg_type, require_crl_checking, vfy_buf, vfy_buf_len, data, data_len, NULL, NULL, NULL); if (!retval) pkiDebug("PKCS7 Verification Success\n"); else { pkiDebug("PKCS7 Verification Failure\n"); goto cleanup; } retval = 0; cleanup: if (p7 != NULL) PKCS7_free(p7); if (out != NULL) BIO_free(out); free(tmp_buf); free(tmp_buf2); return retval; } static krb5_error_code crypto_retrieve_X509_sans(krb5_context context, pkinit_plg_crypto_context plgctx, pkinit_req_crypto_context reqctx, X509 *cert, krb5_principal **princs_ret, krb5_principal **upn_ret, unsigned char ***dns_ret) { krb5_error_code retval = EINVAL; char buf[DN_BUF_LEN]; int p = 0, u = 0, d = 0, ret = 0, l; krb5_principal *princs = NULL; krb5_principal *upns = NULL; unsigned char **dnss = NULL; unsigned int i, num_found = 0, num_sans = 0; X509_EXTENSION *ext = NULL; GENERAL_NAMES *ialt = NULL; GENERAL_NAME *gen = NULL; if (princs_ret != NULL) *princs_ret = NULL; if (upn_ret != NULL) *upn_ret = NULL; if (dns_ret != NULL) *dns_ret = NULL; if (princs_ret == NULL && upn_ret == NULL && dns_ret == NULL) { pkiDebug("%s: nowhere to return any values!\n", __FUNCTION__); return retval; } if (cert == NULL) { pkiDebug("%s: no certificate!\n", __FUNCTION__); return retval; } X509_NAME_oneline(X509_get_subject_name(cert), buf, sizeof(buf)); pkiDebug("%s: looking for SANs in cert = %s\n", __FUNCTION__, buf); l = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1); if (l < 0) return 0; if (!(ext = X509_get_ext(cert, l)) || !(ialt = X509V3_EXT_d2i(ext))) { pkiDebug("%s: found no subject alt name extensions\n", __FUNCTION__); goto cleanup; } num_sans = sk_GENERAL_NAME_num(ialt); pkiDebug("%s: found %d subject alt name extension(s)\n", __FUNCTION__, num_sans); /* OK, we're likely returning something. Allocate return values */ if (princs_ret != NULL) { princs = calloc(num_sans + 1, sizeof(krb5_principal)); if (princs == NULL) { retval = ENOMEM; goto cleanup; } } if (upn_ret != NULL) { upns = calloc(num_sans + 1, sizeof(krb5_principal)); if (upns == NULL) { retval = ENOMEM; goto cleanup; } } if (dns_ret != NULL) { dnss = calloc(num_sans + 1, sizeof(*dnss)); if (dnss == NULL) { retval = ENOMEM; goto cleanup; } } for (i = 0; i < num_sans; i++) { krb5_data name = { 0, 0, NULL }; gen = sk_GENERAL_NAME_value(ialt, i); switch (gen->type) { case GEN_OTHERNAME: name.length = gen->d.otherName->value->value.sequence->length; name.data = (char *)gen->d.otherName->value->value.sequence->data; if (princs != NULL && OBJ_cmp(plgctx->id_pkinit_san, gen->d.otherName->type_id) == 0) { #ifdef DEBUG_ASN1 print_buffer_bin((unsigned char *)name.data, name.length, "/tmp/pkinit_san"); #endif ret = k5int_decode_krb5_principal_name(&name, &princs[p]); if (ret) { pkiDebug("%s: failed decoding pkinit san value\n", __FUNCTION__); } else { p++; num_found++; } } else if (upns != NULL && OBJ_cmp(plgctx->id_ms_san_upn, gen->d.otherName->type_id) == 0) { /* Prevent abuse of embedded null characters. */ if (memchr(name.data, '\0', name.length)) break; ret = krb5_parse_name_flags(context, name.data, KRB5_PRINCIPAL_PARSE_ENTERPRISE, &upns[u]); if (ret) { pkiDebug("%s: failed parsing ms-upn san value\n", __FUNCTION__); } else { u++; num_found++; } } else { pkiDebug("%s: unrecognized othername oid in SAN\n", __FUNCTION__); continue; } break; case GEN_DNS: if (dnss != NULL) { /* Prevent abuse of embedded null characters. */ if (memchr(gen->d.dNSName->data, '\0', gen->d.dNSName->length)) break; pkiDebug("%s: found dns name = %s\n", __FUNCTION__, gen->d.dNSName->data); dnss[d] = (unsigned char *) strdup((char *)gen->d.dNSName->data); if (dnss[d] == NULL) { pkiDebug("%s: failed to duplicate dns name\n", __FUNCTION__); } else { d++; num_found++; } } break; default: pkiDebug("%s: SAN type = %d expecting %d\n", __FUNCTION__, gen->type, GEN_OTHERNAME); } } sk_GENERAL_NAME_pop_free(ialt, GENERAL_NAME_free); retval = 0; if (princs != NULL && *princs != NULL) { *princs_ret = princs; princs = NULL; } if (upns != NULL && *upns != NULL) { *upn_ret = upns; upns = NULL; } if (dnss != NULL && *dnss != NULL) { *dns_ret = dnss; dnss = NULL; } cleanup: for (i = 0; princs != NULL && princs[i] != NULL; i++) krb5_free_principal(context, princs[i]); free(princs); for (i = 0; upns != NULL && upns[i] != NULL; i++) krb5_free_principal(context, upns[i]); free(upns); for (i = 0; dnss != NULL && dnss[i] != NULL; i++) free(dnss[i]); free(dnss); return retval; } krb5_error_code crypto_retrieve_signer_identity(krb5_context context, pkinit_identity_crypto_context id_cryptoctx, const char **identity) { *identity = id_cryptoctx->identity; if (*identity == NULL) return ENOENT; return 0; } krb5_error_code crypto_retrieve_cert_sans(krb5_context context, pkinit_plg_crypto_context plgctx, pkinit_req_crypto_context reqctx, pkinit_identity_crypto_context idctx, krb5_principal **princs_ret, krb5_principal **upn_ret, unsigned char ***dns_ret) { krb5_error_code retval = EINVAL; if (reqctx->received_cert == NULL) { pkiDebug("%s: No certificate!\n", __FUNCTION__); return retval; } return crypto_retrieve_X509_sans(context, plgctx, reqctx, reqctx->received_cert, princs_ret, upn_ret, dns_ret); } krb5_error_code crypto_check_cert_eku(krb5_context context, pkinit_plg_crypto_context plgctx, pkinit_req_crypto_context reqctx, pkinit_identity_crypto_context idctx, int checking_kdc_cert, int allow_secondary_usage, int *valid_eku) { char buf[DN_BUF_LEN]; int found_eku = 0; krb5_error_code retval = EINVAL; int i; *valid_eku = 0; if (reqctx->received_cert == NULL) goto cleanup; X509_NAME_oneline(X509_get_subject_name(reqctx->received_cert), buf, sizeof(buf)); if ((i = X509_get_ext_by_NID(reqctx->received_cert, NID_ext_key_usage, -1)) >= 0) { EXTENDED_KEY_USAGE *extusage; extusage = X509_get_ext_d2i(reqctx->received_cert, NID_ext_key_usage, NULL, NULL); if (extusage) { pkiDebug("%s: found eku info in the cert\n", __FUNCTION__); for (i = 0; found_eku == 0 && i < sk_ASN1_OBJECT_num(extusage); i++) { ASN1_OBJECT *tmp_oid; tmp_oid = sk_ASN1_OBJECT_value(extusage, i); pkiDebug("%s: checking eku %d of %d, allow_secondary = %d\n", __FUNCTION__, i+1, sk_ASN1_OBJECT_num(extusage), allow_secondary_usage); if (checking_kdc_cert) { if ((OBJ_cmp(tmp_oid, plgctx->id_pkinit_KPKdc) == 0) || (allow_secondary_usage && OBJ_cmp(tmp_oid, plgctx->id_kp_serverAuth) == 0)) found_eku = 1; } else { if ((OBJ_cmp(tmp_oid, plgctx->id_pkinit_KPClientAuth) == 0) || (allow_secondary_usage && OBJ_cmp(tmp_oid, plgctx->id_ms_kp_sc_logon) == 0)) found_eku = 1; } } } EXTENDED_KEY_USAGE_free(extusage); if (found_eku) { ASN1_BIT_STRING *usage = NULL; /* check that digitalSignature KeyUsage is present */ X509_check_ca(reqctx->received_cert); if ((usage = X509_get_ext_d2i(reqctx->received_cert, NID_key_usage, NULL, NULL))) { if (!ku_reject(reqctx->received_cert, X509v3_KU_DIGITAL_SIGNATURE)) { TRACE_PKINIT_EKU(context); *valid_eku = 1; } else TRACE_PKINIT_EKU_NO_KU(context); } ASN1_BIT_STRING_free(usage); } } retval = 0; cleanup: pkiDebug("%s: returning retval %d, valid_eku %d\n", __FUNCTION__, retval, *valid_eku); return retval; } krb5_error_code pkinit_octetstring2key(krb5_context context, krb5_enctype etype, unsigned char *key, unsigned int dh_key_len, krb5_keyblock *key_block) { krb5_error_code retval; unsigned char *buf = NULL; unsigned char md[SHA_DIGEST_LENGTH]; unsigned char counter; size_t keybytes, keylength, offset; krb5_data random_data; if ((buf = malloc(dh_key_len)) == NULL) { retval = ENOMEM; goto cleanup; } memset(buf, 0, dh_key_len); counter = 0; offset = 0; do { SHA_CTX c; SHA1_Init(&c); SHA1_Update(&c, &counter, 1); SHA1_Update(&c, key, dh_key_len); SHA1_Final(md, &c); if (dh_key_len - offset < sizeof(md)) memcpy(buf + offset, md, dh_key_len - offset); else memcpy(buf + offset, md, sizeof(md)); offset += sizeof(md); counter++; } while (offset < dh_key_len); key_block->magic = 0; key_block->enctype = etype; retval = krb5_c_keylengths(context, etype, &keybytes, &keylength); if (retval) goto cleanup; key_block->length = keylength; key_block->contents = malloc(keylength); if (key_block->contents == NULL) { retval = ENOMEM; goto cleanup; } random_data.length = keybytes; random_data.data = (char *)buf; retval = krb5_c_random_to_key(context, etype, &random_data, key_block); cleanup: free(buf); /* If this is an error return, free the allocated keyblock, if any */ if (retval) { krb5_free_keyblock_contents(context, key_block); } return retval; } /** * Given an algorithm_identifier, this function returns the hash length * and EVP function associated with that algorithm. */ static krb5_error_code pkinit_alg_values(krb5_context context, const krb5_data *alg_id, size_t *hash_bytes, const EVP_MD *(**func)(void)) { *hash_bytes = 0; *func = NULL; if ((alg_id->length == krb5_pkinit_sha1_oid_len) && (0 == memcmp(alg_id->data, &krb5_pkinit_sha1_oid, krb5_pkinit_sha1_oid_len))) { *hash_bytes = 20; *func = &EVP_sha1; return 0; } else if ((alg_id->length == krb5_pkinit_sha256_oid_len) && (0 == memcmp(alg_id->data, krb5_pkinit_sha256_oid, krb5_pkinit_sha256_oid_len))) { *hash_bytes = 32; *func = &EVP_sha256; return 0; } else if ((alg_id->length == krb5_pkinit_sha512_oid_len) && (0 == memcmp(alg_id->data, krb5_pkinit_sha512_oid, krb5_pkinit_sha512_oid_len))) { *hash_bytes = 64; *func = &EVP_sha512; return 0; } else { krb5_set_error_message(context, KRB5_ERR_BAD_S2K_PARAMS, "Bad algorithm ID passed to PK-INIT KDF."); return KRB5_ERR_BAD_S2K_PARAMS; } } /* pkinit_alg_values() */ /* pkinit_alg_agility_kdf() -- * This function generates a key using the KDF described in * draft_ietf_krb_wg_pkinit_alg_agility-04.txt. The algorithm is * described as follows: * * 1. reps = keydatalen (K) / hash length (H) * * 2. Initialize a 32-bit, big-endian bit string counter as 1. * * 3. For i = 1 to reps by 1, do the following: * * - Compute Hashi = H(counter || Z || OtherInfo). * * - Increment counter (modulo 2^32) * * 4. Set key = Hash1 || Hash2 || ... so that length of key is K bytes. */ krb5_error_code pkinit_alg_agility_kdf(krb5_context context, krb5_data *secret, krb5_data *alg_oid, krb5_const_principal party_u_info, krb5_const_principal party_v_info, krb5_enctype enctype, krb5_data *as_req, krb5_data *pk_as_rep, krb5_keyblock *key_block) { krb5_error_code retval = 0; unsigned int reps = 0; uint32_t counter = 1; /* Does this type work on Windows? */ size_t offset = 0; size_t hash_len = 0; size_t rand_len = 0; size_t key_len = 0; krb5_data random_data; krb5_sp80056a_other_info other_info_fields; krb5_pkinit_supp_pub_info supp_pub_info_fields; krb5_data *other_info = NULL; krb5_data *supp_pub_info = NULL; krb5_algorithm_identifier alg_id; EVP_MD_CTX *ctx = NULL; const EVP_MD *(*EVP_func)(void); /* initialize random_data here to make clean-up safe */ random_data.length = 0; random_data.data = NULL; /* allocate and initialize the key block */ key_block->magic = 0; key_block->enctype = enctype; if (0 != (retval = krb5_c_keylengths(context, enctype, &rand_len, &key_len))) goto cleanup; random_data.length = rand_len; key_block->length = key_len; if (NULL == (key_block->contents = malloc(key_block->length))) { retval = ENOMEM; goto cleanup; } memset (key_block->contents, 0, key_block->length); /* If this is anonymous pkinit, use the anonymous principle for party_u_info */ if (party_u_info && krb5_principal_compare_any_realm(context, party_u_info, krb5_anonymous_principal())) party_u_info = (krb5_principal)krb5_anonymous_principal(); if (0 != (retval = pkinit_alg_values(context, alg_oid, &hash_len, &EVP_func))) goto cleanup; /* 1. reps = keydatalen (K) / hash length (H) */ reps = key_block->length/hash_len; /* ... and round up, if necessary */ if (key_block->length > (reps * hash_len)) reps++; /* Allocate enough space in the random data buffer to hash directly into * it, even if the last hash will make it bigger than the key length. */ if (NULL == (random_data.data = malloc(reps * hash_len))) { retval = ENOMEM; goto cleanup; } /* Encode the ASN.1 octet string for "SuppPubInfo" */ supp_pub_info_fields.enctype = enctype; supp_pub_info_fields.as_req = *as_req; supp_pub_info_fields.pk_as_rep = *pk_as_rep; if (0 != ((retval = encode_krb5_pkinit_supp_pub_info(&supp_pub_info_fields, &supp_pub_info)))) goto cleanup; /* Now encode the ASN.1 octet string for "OtherInfo" */ memset(&alg_id, 0, sizeof alg_id); alg_id.algorithm = *alg_oid; /*alias*/ other_info_fields.algorithm_identifier = alg_id; other_info_fields.party_u_info = (krb5_principal) party_u_info; other_info_fields.party_v_info = (krb5_principal) party_v_info; other_info_fields.supp_pub_info = *supp_pub_info; if (0 != (retval = encode_krb5_sp80056a_other_info(&other_info_fields, &other_info))) goto cleanup; /* 2. Initialize a 32-bit, big-endian bit string counter as 1. * 3. For i = 1 to reps by 1, do the following: * - Compute Hashi = H(counter || Z || OtherInfo). * - Increment counter (modulo 2^32) */ for (counter = 1; counter <= reps; counter++) { uint s = 0; uint32_t be_counter = htonl(counter); ctx = EVP_MD_CTX_new(); if (ctx == NULL) { retval = KRB5_CRYPTO_INTERNAL; goto cleanup; } /* - Compute Hashi = H(counter || Z || OtherInfo). */ if (!EVP_DigestInit(ctx, EVP_func())) { krb5_set_error_message(context, KRB5_CRYPTO_INTERNAL, "Call to OpenSSL EVP_DigestInit() returned an error."); retval = KRB5_CRYPTO_INTERNAL; goto cleanup; } if (!EVP_DigestUpdate(ctx, &be_counter, 4) || !EVP_DigestUpdate(ctx, secret->data, secret->length) || !EVP_DigestUpdate(ctx, other_info->data, other_info->length)) { krb5_set_error_message(context, KRB5_CRYPTO_INTERNAL, "Call to OpenSSL EVP_DigestUpdate() returned an error."); retval = KRB5_CRYPTO_INTERNAL; goto cleanup; } /* 4. Set key = Hash1 || Hash2 || ... so that length of key is K bytes. */ if (!EVP_DigestFinal(ctx, (uint8_t *)random_data.data + offset, &s)) { krb5_set_error_message(context, KRB5_CRYPTO_INTERNAL, "Call to OpenSSL EVP_DigestUpdate() returned an error."); retval = KRB5_CRYPTO_INTERNAL; goto cleanup; } offset += s; assert(s == hash_len); EVP_MD_CTX_free(ctx); ctx = NULL; } retval = krb5_c_random_to_key(context, enctype, &random_data, key_block); cleanup: EVP_MD_CTX_free(ctx); /* If this has been an error, free the allocated key_block, if any */ if (retval) { krb5_free_keyblock_contents(context, key_block); } /* free other allocated resources, either way */ if (random_data.data) free(random_data.data); krb5_free_data(context, other_info); krb5_free_data(context, supp_pub_info); return retval; } /*pkinit_alg_agility_kdf() */ /* Call DH_compute_key() and ensure that we left-pad short results instead of * leaving junk bytes at the end of the buffer. */ static void compute_dh(unsigned char *buf, int size, BIGNUM *server_pub_key, DH *dh) { int len, pad; len = DH_compute_key(buf, server_pub_key, dh); assert(len >= 0 && len <= size); if (len < size) { pad = size - len; memmove(buf + pad, buf, len); memset(buf, 0, pad); } } krb5_error_code client_create_dh(krb5_context context, pkinit_plg_crypto_context plg_cryptoctx, pkinit_req_crypto_context cryptoctx, pkinit_identity_crypto_context id_cryptoctx, int dh_size, unsigned char **dh_params, unsigned int *dh_params_len, unsigned char **dh_pubkey, unsigned int *dh_pubkey_len) { krb5_error_code retval = KRB5KDC_ERR_PREAUTH_FAILED; unsigned char *buf = NULL; int dh_err = 0; ASN1_INTEGER *pub_key = NULL; const BIGNUM *pubkey_bn, *p, *q, *g; if (cryptoctx->dh == NULL) { if (dh_size == 1024) cryptoctx->dh = make_oakley_dh(oakley_1024, sizeof(oakley_1024)); else if (dh_size == 2048) cryptoctx->dh = make_oakley_dh(oakley_2048, sizeof(oakley_2048)); else if (dh_size == 4096) cryptoctx->dh = make_oakley_dh(oakley_4096, sizeof(oakley_4096)); if (cryptoctx->dh == NULL) goto cleanup; } DH_generate_key(cryptoctx->dh); DH_get0_key(cryptoctx->dh, &pubkey_bn, NULL); DH_check(cryptoctx->dh, &dh_err); if (dh_err != 0) { pkiDebug("Warning: dh_check failed with %d\n", dh_err); if (dh_err & DH_CHECK_P_NOT_PRIME) pkiDebug("p value is not prime\n"); if (dh_err & DH_CHECK_P_NOT_SAFE_PRIME) pkiDebug("p value is not a safe prime\n"); if (dh_err & DH_UNABLE_TO_CHECK_GENERATOR) pkiDebug("unable to check the generator value\n"); if (dh_err & DH_NOT_SUITABLE_GENERATOR) pkiDebug("the g value is not a generator\n"); } #ifdef DEBUG_DH print_dh(cryptoctx->dh, "client's DH params\n"); print_pubkey(cryptoctx->dh->pub_key, "client's pub_key="); #endif DH_check_pub_key(cryptoctx->dh, pubkey_bn, &dh_err); if (dh_err != 0) { pkiDebug("dh_check_pub_key failed with %d\n", dh_err); goto cleanup; } /* pack DHparams */ /* aglo: usually we could just call i2d_DHparams to encode DH params * however, PKINIT requires RFC3279 encoding and openssl does pkcs#3. */ DH_get0_pqg(cryptoctx->dh, &p, &q, &g); retval = pkinit_encode_dh_params(p, g, q, dh_params, dh_params_len); if (retval) goto cleanup; /* pack DH public key */ /* Diffie-Hellman public key must be ASN1 encoded as an INTEGER; this * encoding shall be used as the contents (the value) of the * subjectPublicKey component (a BIT STRING) of the SubjectPublicKeyInfo * data element */ pub_key = BN_to_ASN1_INTEGER(pubkey_bn, NULL); if (pub_key == NULL) { retval = ENOMEM; goto cleanup; } *dh_pubkey_len = i2d_ASN1_INTEGER(pub_key, NULL); if ((buf = *dh_pubkey = malloc(*dh_pubkey_len)) == NULL) { retval = ENOMEM; goto cleanup; } i2d_ASN1_INTEGER(pub_key, &buf); if (pub_key != NULL) ASN1_INTEGER_free(pub_key); retval = 0; return retval; cleanup: if (cryptoctx->dh != NULL) DH_free(cryptoctx->dh); cryptoctx->dh = NULL; free(*dh_params); *dh_params = NULL; free(*dh_pubkey); *dh_pubkey = NULL; if (pub_key != NULL) ASN1_INTEGER_free(pub_key); return retval; } krb5_error_code client_process_dh(krb5_context context, pkinit_plg_crypto_context plg_cryptoctx, pkinit_req_crypto_context cryptoctx, pkinit_identity_crypto_context id_cryptoctx, unsigned char *subjectPublicKey_data, unsigned int subjectPublicKey_length, unsigned char **client_key, unsigned int *client_key_len) { krb5_error_code retval = KRB5KDC_ERR_PREAUTH_FAILED; BIGNUM *server_pub_key = NULL; ASN1_INTEGER *pub_key = NULL; const unsigned char *p = NULL; *client_key_len = DH_size(cryptoctx->dh); if ((*client_key = malloc(*client_key_len)) == NULL) { retval = ENOMEM; goto cleanup; } p = subjectPublicKey_data; pub_key = d2i_ASN1_INTEGER(NULL, &p, (long)subjectPublicKey_length); if (pub_key == NULL) goto cleanup; if ((server_pub_key = ASN1_INTEGER_to_BN(pub_key, NULL)) == NULL) goto cleanup; compute_dh(*client_key, *client_key_len, server_pub_key, cryptoctx->dh); #ifdef DEBUG_DH print_pubkey(server_pub_key, "server's pub_key="); pkiDebug("client computed key (%d)= ", *client_key_len); print_buffer(*client_key, *client_key_len); #endif retval = 0; if (server_pub_key != NULL) BN_free(server_pub_key); if (pub_key != NULL) ASN1_INTEGER_free(pub_key); return retval; cleanup: free(*client_key); *client_key = NULL; if (pub_key != NULL) ASN1_INTEGER_free(pub_key); return retval; } /* Return 1 if dh is a permitted well-known group, otherwise return 0. */ static int check_dh_wellknown(pkinit_plg_crypto_context cryptoctx, DH *dh, int nbits) { switch (nbits) { case 1024: /* Oakley MODP group 2 */ if (pkinit_check_dh_params(cryptoctx->dh_1024, dh) == 0) return 1; break; case 2048: /* Oakley MODP group 14 */ if (pkinit_check_dh_params(cryptoctx->dh_2048, dh) == 0) return 1; break; case 4096: /* Oakley MODP group 16 */ if (pkinit_check_dh_params(cryptoctx->dh_4096, dh) == 0) return 1; break; default: break; } return 0; } krb5_error_code server_check_dh(krb5_context context, pkinit_plg_crypto_context cryptoctx, pkinit_req_crypto_context req_cryptoctx, pkinit_identity_crypto_context id_cryptoctx, krb5_data *dh_params, int minbits) { DH *dh = NULL; const BIGNUM *p; int dh_prime_bits; krb5_error_code retval = KRB5KDC_ERR_DH_KEY_PARAMETERS_NOT_ACCEPTED; dh = decode_dh_params((uint8_t *)dh_params->data, dh_params->length); if (dh == NULL) { pkiDebug("failed to decode dhparams\n"); goto cleanup; } /* KDC SHOULD check to see if the key parameters satisfy its policy */ DH_get0_pqg(dh, &p, NULL, NULL); dh_prime_bits = BN_num_bits(p); if (minbits && dh_prime_bits < minbits) { pkiDebug("client sent dh params with %d bits, we require %d\n", dh_prime_bits, minbits); goto cleanup; } if (check_dh_wellknown(cryptoctx, dh, dh_prime_bits)) retval = 0; cleanup: if (retval == 0) req_cryptoctx->dh = dh; else DH_free(dh); return retval; } /* Duplicate a DH handle (parameters only, not public or private key). */ static DH * dup_dh_params(const DH *src) { const BIGNUM *oldp, *oldq, *oldg; BIGNUM *p = NULL, *q = NULL, *g = NULL; DH *dh; DH_get0_pqg(src, &oldp, &oldq, &oldg); p = BN_dup(oldp); q = BN_dup(oldq); g = BN_dup(oldg); dh = DH_new(); if (p == NULL || q == NULL || g == NULL || dh == NULL) { BN_free(p); BN_free(q); BN_free(g); DH_free(dh); return NULL; } DH_set0_pqg(dh, p, q, g); return dh; } /* kdc's dh function */ krb5_error_code server_process_dh(krb5_context context, pkinit_plg_crypto_context plg_cryptoctx, pkinit_req_crypto_context cryptoctx, pkinit_identity_crypto_context id_cryptoctx, unsigned char *data, unsigned int data_len, unsigned char **dh_pubkey, unsigned int *dh_pubkey_len, unsigned char **server_key, unsigned int *server_key_len) { krb5_error_code retval = ENOMEM; DH *dh = NULL, *dh_server = NULL; unsigned char *p = NULL; ASN1_INTEGER *pub_key = NULL; BIGNUM *client_pubkey = NULL; const BIGNUM *server_pubkey; *dh_pubkey = *server_key = NULL; *dh_pubkey_len = *server_key_len = 0; /* get client's received DH parameters that we saved in server_check_dh */ dh = cryptoctx->dh; dh_server = dup_dh_params(dh); if (dh_server == NULL) goto cleanup; /* decode client's public key */ p = data; pub_key = d2i_ASN1_INTEGER(NULL, (const unsigned char **)&p, (int)data_len); if (pub_key == NULL) goto cleanup; client_pubkey = ASN1_INTEGER_to_BN(pub_key, NULL); if (client_pubkey == NULL) goto cleanup; ASN1_INTEGER_free(pub_key); if (!DH_generate_key(dh_server)) goto cleanup; DH_get0_key(dh_server, &server_pubkey, NULL); /* generate DH session key */ *server_key_len = DH_size(dh_server); if ((*server_key = malloc(*server_key_len)) == NULL) goto cleanup; compute_dh(*server_key, *server_key_len, client_pubkey, dh_server); #ifdef DEBUG_DH print_dh(dh_server, "client&server's DH params\n"); print_pubkey(client_pubkey, "client's pub_key="); print_pubkey(server_pubkey, "server's pub_key="); pkiDebug("server computed key="); print_buffer(*server_key, *server_key_len); #endif /* KDC reply */ /* pack DH public key */ /* Diffie-Hellman public key must be ASN1 encoded as an INTEGER; this * encoding shall be used as the contents (the value) of the * subjectPublicKey component (a BIT STRING) of the SubjectPublicKeyInfo * data element */ pub_key = BN_to_ASN1_INTEGER(server_pubkey, NULL); if (pub_key == NULL) goto cleanup; *dh_pubkey_len = i2d_ASN1_INTEGER(pub_key, NULL); if ((p = *dh_pubkey = malloc(*dh_pubkey_len)) == NULL) goto cleanup; i2d_ASN1_INTEGER(pub_key, &p); if (pub_key != NULL) ASN1_INTEGER_free(pub_key); retval = 0; if (dh_server != NULL) DH_free(dh_server); return retval; cleanup: BN_free(client_pubkey); DH_free(dh_server); free(*dh_pubkey); free(*server_key); return retval; } int pkinit_openssl_init() { /* Initialize OpenSSL. */ ERR_load_crypto_strings(); OpenSSL_add_all_algorithms(); return 0; } static krb5_error_code pkinit_encode_dh_params(const BIGNUM *p, const BIGNUM *g, const BIGNUM *q, uint8_t **buf, unsigned int *buf_len) { krb5_error_code retval = ENOMEM; int bufsize = 0, r = 0; unsigned char *tmp = NULL; ASN1_INTEGER *ap = NULL, *ag = NULL, *aq = NULL; if ((ap = BN_to_ASN1_INTEGER(p, NULL)) == NULL) goto cleanup; if ((ag = BN_to_ASN1_INTEGER(g, NULL)) == NULL) goto cleanup; if ((aq = BN_to_ASN1_INTEGER(q, NULL)) == NULL) goto cleanup; bufsize = i2d_ASN1_INTEGER(ap, NULL); bufsize += i2d_ASN1_INTEGER(ag, NULL); bufsize += i2d_ASN1_INTEGER(aq, NULL); r = ASN1_object_size(1, bufsize, V_ASN1_SEQUENCE); tmp = *buf = malloc((size_t) r); if (tmp == NULL) goto cleanup; ASN1_put_object(&tmp, 1, bufsize, V_ASN1_SEQUENCE, V_ASN1_UNIVERSAL); i2d_ASN1_INTEGER(ap, &tmp); i2d_ASN1_INTEGER(ag, &tmp); i2d_ASN1_INTEGER(aq, &tmp); *buf_len = r; retval = 0; cleanup: if (ap != NULL) ASN1_INTEGER_free(ap); if (ag != NULL) ASN1_INTEGER_free(ag); if (aq != NULL) ASN1_INTEGER_free(aq); return retval; } #if OPENSSL_VERSION_NUMBER >= 0x10100000L /* * We need to decode DomainParameters from RFC 3279 section 2.3.3. We would * like to just call d2i_DHxparams(), but Microsoft's implementation may omit * the q value in violation of the RFC. Instead we must copy the internal * structures and sequence declarations from dh_asn1.c, modified to make the q * field optional. */ typedef struct { ASN1_BIT_STRING *seed; BIGNUM *counter; } int_dhvparams; typedef struct { BIGNUM *p; BIGNUM *q; BIGNUM *g; BIGNUM *j; int_dhvparams *vparams; } int_dhx942_dh; ASN1_SEQUENCE(DHvparams) = { ASN1_SIMPLE(int_dhvparams, seed, ASN1_BIT_STRING), ASN1_SIMPLE(int_dhvparams, counter, BIGNUM) } static_ASN1_SEQUENCE_END_name(int_dhvparams, DHvparams) ASN1_SEQUENCE(DHxparams) = { ASN1_SIMPLE(int_dhx942_dh, p, BIGNUM), ASN1_SIMPLE(int_dhx942_dh, g, BIGNUM), ASN1_OPT(int_dhx942_dh, q, BIGNUM), ASN1_OPT(int_dhx942_dh, j, BIGNUM), ASN1_OPT(int_dhx942_dh, vparams, DHvparams), } static_ASN1_SEQUENCE_END_name(int_dhx942_dh, DHxparams) static DH * decode_dh_params(const uint8_t *p, unsigned int len) { int_dhx942_dh *params; DH *dh; dh = DH_new(); if (dh == NULL) return NULL; params = (int_dhx942_dh *)ASN1_item_d2i(NULL, &p, len, ASN1_ITEM_rptr(DHxparams)); if (params == NULL) { DH_free(dh); return NULL; } /* Steal the p, q, and g values from dhparams for dh. Ignore j and * vparams. */ DH_set0_pqg(dh, params->p, params->q, params->g); params->p = params->q = params->g = NULL; ASN1_item_free((ASN1_VALUE *)params, ASN1_ITEM_rptr(DHxparams)); return dh; } #else /* OPENSSL_VERSION_NUMBER < 0x10100000L */ /* * Do the same decoding (except without decoding j and vparams or checking the * sequence length) using the pre-OpenSSL-1.1 asn1_mac.h. Define an internal * function in the form demanded by the macros, then wrap it for caller * convenience. */ static DH * decode_dh_params_int(DH ** a, uint8_t **pp, unsigned int len) { ASN1_INTEGER ai, *aip = NULL; long length = (long) len; M_ASN1_D2I_vars(a, DH *, DH_new); M_ASN1_D2I_Init(); M_ASN1_D2I_start_sequence(); aip = &ai; ai.data = NULL; ai.length = 0; M_ASN1_D2I_get_x(ASN1_INTEGER, aip, d2i_ASN1_INTEGER); if (aip == NULL) return NULL; else { ret->p = ASN1_INTEGER_to_BN(aip, NULL); if (ret->p == NULL) return NULL; if (ai.data != NULL) { OPENSSL_free(ai.data); ai.data = NULL; ai.length = 0; } } M_ASN1_D2I_get_x(ASN1_INTEGER, aip, d2i_ASN1_INTEGER); if (aip == NULL) return NULL; else { ret->g = ASN1_INTEGER_to_BN(aip, NULL); if (ret->g == NULL) return NULL; if (ai.data != NULL) { OPENSSL_free(ai.data); ai.data = NULL; ai.length = 0; } } M_ASN1_D2I_get_opt(aip, d2i_ASN1_INTEGER, V_ASN1_INTEGER); if (aip == NULL || ai.data == NULL) ret->q = NULL; else { ret->q = ASN1_INTEGER_to_BN(aip, NULL); if (ret->q == NULL) return NULL; if (ai.data != NULL) { OPENSSL_free(ai.data); ai.data = NULL; ai.length = 0; } } M_ASN1_D2I_end_sequence(); M_ASN1_D2I_Finish(a, DH_free, 0); } static DH * decode_dh_params(const uint8_t *p, unsigned int len) { uint8_t *ptr = (uint8_t *)p; return decode_dh_params_int(NULL, &ptr, len); } #endif /* OPENSSL_VERSION_NUMBER < 0x10100000L */ static krb5_error_code pkinit_create_sequence_of_principal_identifiers( krb5_context context, pkinit_plg_crypto_context plg_cryptoctx, pkinit_req_crypto_context req_cryptoctx, pkinit_identity_crypto_context id_cryptoctx, int type, krb5_pa_data ***e_data_out) { krb5_error_code retval = KRB5KRB_ERR_GENERIC; krb5_external_principal_identifier **krb5_trusted_certifiers = NULL; krb5_data *td_certifiers = NULL; krb5_pa_data **pa_data = NULL; switch(type) { case TD_TRUSTED_CERTIFIERS: retval = create_krb5_trustedCertifiers(context, plg_cryptoctx, req_cryptoctx, id_cryptoctx, &krb5_trusted_certifiers); if (retval) { pkiDebug("create_krb5_trustedCertifiers failed\n"); goto cleanup; } break; case TD_INVALID_CERTIFICATES: retval = create_krb5_invalidCertificates(context, plg_cryptoctx, req_cryptoctx, id_cryptoctx, &krb5_trusted_certifiers); if (retval) { pkiDebug("create_krb5_invalidCertificates failed\n"); goto cleanup; } break; default: retval = -1; goto cleanup; } retval = k5int_encode_krb5_td_trusted_certifiers((krb5_external_principal_identifier *const *)krb5_trusted_certifiers, &td_certifiers); if (retval) { pkiDebug("encode_krb5_td_trusted_certifiers failed\n"); goto cleanup; } #ifdef DEBUG_ASN1 print_buffer_bin((unsigned char *)td_certifiers->data, td_certifiers->length, "/tmp/kdc_td_certifiers"); #endif pa_data = malloc(2 * sizeof(krb5_pa_data *)); if (pa_data == NULL) { retval = ENOMEM; goto cleanup; } pa_data[1] = NULL; pa_data[0] = malloc(sizeof(krb5_pa_data)); if (pa_data[0] == NULL) { free(pa_data); retval = ENOMEM; goto cleanup; } pa_data[0]->pa_type = type; pa_data[0]->length = td_certifiers->length; pa_data[0]->contents = (krb5_octet *)td_certifiers->data; *e_data_out = pa_data; retval = 0; cleanup: if (krb5_trusted_certifiers != NULL) free_krb5_external_principal_identifier(&krb5_trusted_certifiers); free(td_certifiers); return retval; } krb5_error_code pkinit_create_td_trusted_certifiers(krb5_context context, pkinit_plg_crypto_context plg_cryptoctx, pkinit_req_crypto_context req_cryptoctx, pkinit_identity_crypto_context id_cryptoctx, krb5_pa_data ***e_data_out) { krb5_error_code retval = KRB5KRB_ERR_GENERIC; retval = pkinit_create_sequence_of_principal_identifiers(context, plg_cryptoctx, req_cryptoctx, id_cryptoctx, TD_TRUSTED_CERTIFIERS, e_data_out); return retval; } krb5_error_code pkinit_create_td_invalid_certificate( krb5_context context, pkinit_plg_crypto_context plg_cryptoctx, pkinit_req_crypto_context req_cryptoctx, pkinit_identity_crypto_context id_cryptoctx, krb5_pa_data ***e_data_out) { krb5_error_code retval = KRB5KRB_ERR_GENERIC; retval = pkinit_create_sequence_of_principal_identifiers(context, plg_cryptoctx, req_cryptoctx, id_cryptoctx, TD_INVALID_CERTIFICATES, e_data_out); return retval; } krb5_error_code pkinit_create_td_dh_parameters(krb5_context context, pkinit_plg_crypto_context plg_cryptoctx, pkinit_req_crypto_context req_cryptoctx, pkinit_identity_crypto_context id_cryptoctx, pkinit_plg_opts *opts, krb5_pa_data ***e_data_out) { krb5_error_code retval = ENOMEM; unsigned int buf1_len = 0, buf2_len = 0, buf3_len = 0, i = 0; unsigned char *buf1 = NULL, *buf2 = NULL, *buf3 = NULL; krb5_pa_data **pa_data = NULL; krb5_data *encoded_algId = NULL; krb5_algorithm_identifier **algId = NULL; const BIGNUM *p, *q, *g; if (opts->dh_min_bits > 4096) goto cleanup; if (opts->dh_min_bits <= 1024) { DH_get0_pqg(plg_cryptoctx->dh_1024, &p, &q, &g); retval = pkinit_encode_dh_params(p, g, q, &buf1, &buf1_len); if (retval) goto cleanup; } if (opts->dh_min_bits <= 2048) { DH_get0_pqg(plg_cryptoctx->dh_2048, &p, &q, &g); retval = pkinit_encode_dh_params(p, g, q, &buf2, &buf2_len); if (retval) goto cleanup; } DH_get0_pqg(plg_cryptoctx->dh_4096, &p, &q, &g); retval = pkinit_encode_dh_params(p, g, q, &buf3, &buf3_len); if (retval) goto cleanup; if (opts->dh_min_bits <= 1024) { algId = malloc(4 * sizeof(krb5_algorithm_identifier *)); if (algId == NULL) goto cleanup; algId[3] = NULL; algId[0] = malloc(sizeof(krb5_algorithm_identifier)); if (algId[0] == NULL) goto cleanup; algId[0]->parameters.data = malloc(buf2_len); if (algId[0]->parameters.data == NULL) goto cleanup; memcpy(algId[0]->parameters.data, buf2, buf2_len); algId[0]->parameters.length = buf2_len; algId[0]->algorithm = dh_oid; algId[1] = malloc(sizeof(krb5_algorithm_identifier)); if (algId[1] == NULL) goto cleanup; algId[1]->parameters.data = malloc(buf3_len); if (algId[1]->parameters.data == NULL) goto cleanup; memcpy(algId[1]->parameters.data, buf3, buf3_len); algId[1]->parameters.length = buf3_len; algId[1]->algorithm = dh_oid; algId[2] = malloc(sizeof(krb5_algorithm_identifier)); if (algId[2] == NULL) goto cleanup; algId[2]->parameters.data = malloc(buf1_len); if (algId[2]->parameters.data == NULL) goto cleanup; memcpy(algId[2]->parameters.data, buf1, buf1_len); algId[2]->parameters.length = buf1_len; algId[2]->algorithm = dh_oid; } else if (opts->dh_min_bits <= 2048) { algId = malloc(3 * sizeof(krb5_algorithm_identifier *)); if (algId == NULL) goto cleanup; algId[2] = NULL; algId[0] = malloc(sizeof(krb5_algorithm_identifier)); if (algId[0] == NULL) goto cleanup; algId[0]->parameters.data = malloc(buf2_len); if (algId[0]->parameters.data == NULL) goto cleanup; memcpy(algId[0]->parameters.data, buf2, buf2_len); algId[0]->parameters.length = buf2_len; algId[0]->algorithm = dh_oid; algId[1] = malloc(sizeof(krb5_algorithm_identifier)); if (algId[1] == NULL) goto cleanup; algId[1]->parameters.data = malloc(buf3_len); if (algId[1]->parameters.data == NULL) goto cleanup; memcpy(algId[1]->parameters.data, buf3, buf3_len); algId[1]->parameters.length = buf3_len; algId[1]->algorithm = dh_oid; } else if (opts->dh_min_bits <= 4096) { algId = malloc(2 * sizeof(krb5_algorithm_identifier *)); if (algId == NULL) goto cleanup; algId[1] = NULL; algId[0] = malloc(sizeof(krb5_algorithm_identifier)); if (algId[0] == NULL) goto cleanup; algId[0]->parameters.data = malloc(buf3_len); if (algId[0]->parameters.data == NULL) goto cleanup; memcpy(algId[0]->parameters.data, buf3, buf3_len); algId[0]->parameters.length = buf3_len; algId[0]->algorithm = dh_oid; } retval = k5int_encode_krb5_td_dh_parameters((krb5_algorithm_identifier *const *)algId, &encoded_algId); if (retval) goto cleanup; #ifdef DEBUG_ASN1 print_buffer_bin((unsigned char *)encoded_algId->data, encoded_algId->length, "/tmp/kdc_td_dh_params"); #endif pa_data = malloc(2 * sizeof(krb5_pa_data *)); if (pa_data == NULL) { retval = ENOMEM; goto cleanup; } pa_data[1] = NULL; pa_data[0] = malloc(sizeof(krb5_pa_data)); if (pa_data[0] == NULL) { free(pa_data); retval = ENOMEM; goto cleanup; } pa_data[0]->pa_type = TD_DH_PARAMETERS; pa_data[0]->length = encoded_algId->length; pa_data[0]->contents = (krb5_octet *)encoded_algId->data; *e_data_out = pa_data; retval = 0; cleanup: free(buf1); free(buf2); free(buf3); free(encoded_algId); if (algId != NULL) { while(algId[i] != NULL) { free(algId[i]->parameters.data); free(algId[i]); i++; } free(algId); } return retval; } krb5_error_code pkinit_check_kdc_pkid(krb5_context context, pkinit_plg_crypto_context plg_cryptoctx, pkinit_req_crypto_context req_cryptoctx, pkinit_identity_crypto_context id_cryptoctx, unsigned char *pdid_buf, unsigned int pkid_len, int *valid_kdcPkId) { PKCS7_ISSUER_AND_SERIAL *is = NULL; const unsigned char *p = pdid_buf; int status = 1; X509 *kdc_cert = sk_X509_value(id_cryptoctx->my_certs, id_cryptoctx->cert_index); *valid_kdcPkId = 0; pkiDebug("found kdcPkId in AS REQ\n"); is = d2i_PKCS7_ISSUER_AND_SERIAL(NULL, &p, (int)pkid_len); if (is == NULL) return KRB5KDC_ERR_PREAUTH_FAILED; status = X509_NAME_cmp(X509_get_issuer_name(kdc_cert), is->issuer); if (!status) { status = ASN1_INTEGER_cmp(X509_get_serialNumber(kdc_cert), is->serial); if (!status) *valid_kdcPkId = 1; } X509_NAME_free(is->issuer); ASN1_INTEGER_free(is->serial); free(is); return 0; } /* Check parameters against a well-known DH group. */ static int pkinit_check_dh_params(DH *dh1, DH *dh2) { const BIGNUM *p1, *p2, *g1, *g2; DH_get0_pqg(dh1, &p1, NULL, &g1); DH_get0_pqg(dh2, &p2, NULL, &g2); if (BN_cmp(p1, p2) != 0) { pkiDebug("p is not well-known group dhparameter\n"); return -1; } if (BN_cmp(g1, g2) != 0) { pkiDebug("bad g dhparameter\n"); return -1; } pkiDebug("good %d dhparams\n", BN_num_bits(p1)); return 0; } krb5_error_code pkinit_process_td_dh_params(krb5_context context, pkinit_plg_crypto_context cryptoctx, pkinit_req_crypto_context req_cryptoctx, pkinit_identity_crypto_context id_cryptoctx, krb5_algorithm_identifier **algId, int *new_dh_size) { krb5_error_code retval = KRB5KDC_ERR_DH_KEY_PARAMETERS_NOT_ACCEPTED; int i = 0, use_sent_dh = 0, ok = 0; pkiDebug("dh parameters\n"); while (algId[i] != NULL) { DH *dh = NULL; const BIGNUM *p; int dh_prime_bits = 0; if (algId[i]->algorithm.length != dh_oid.length || memcmp(algId[i]->algorithm.data, dh_oid.data, dh_oid.length)) goto cleanup; dh = decode_dh_params((uint8_t *)algId[i]->parameters.data, algId[i]->parameters.length); if (dh == NULL) goto cleanup; DH_get0_pqg(dh, &p, NULL, NULL); dh_prime_bits = BN_num_bits(p); pkiDebug("client sent %d DH bits server prefers %d DH bits\n", *new_dh_size, dh_prime_bits); ok = check_dh_wellknown(cryptoctx, dh, dh_prime_bits); if (ok) { *new_dh_size = dh_prime_bits; } if (!ok) { DH_check(dh, &retval); if (retval != 0) { pkiDebug("DH parameters provided by server are unacceptable\n"); retval = KRB5KDC_ERR_DH_KEY_PARAMETERS_NOT_ACCEPTED; } else { use_sent_dh = 1; ok = 1; } } if (!use_sent_dh) DH_free(dh); if (ok) { if (req_cryptoctx->dh != NULL) { DH_free(req_cryptoctx->dh); req_cryptoctx->dh = NULL; } if (use_sent_dh) req_cryptoctx->dh = dh; break; } i++; } if (ok) retval = 0; cleanup: return retval; } static int openssl_callback(int ok, X509_STORE_CTX * ctx) { #ifdef DEBUG if (!ok) { X509 *cert = X509_STORE_CTX_get_current_cert(ctx); int err = X509_STORE_CTX_get_error(ctx); const char *errmsg = X509_verify_cert_error_string(err); char buf[DN_BUF_LEN]; X509_NAME_oneline(X509_get_subject_name(cert), buf, sizeof(buf)); pkiDebug("cert = %s\n", buf); pkiDebug("callback function: %d (%s)\n", err, errmsg); } #endif return ok; } static int openssl_callback_ignore_crls(int ok, X509_STORE_CTX * ctx) { if (ok) return ok; return X509_STORE_CTX_get_error(ctx) == X509_V_ERR_UNABLE_TO_GET_CRL; } static ASN1_OBJECT * pkinit_pkcs7type2oid(pkinit_plg_crypto_context cryptoctx, int pkcs7_type) { switch (pkcs7_type) { case CMS_SIGN_CLIENT: return cryptoctx->id_pkinit_authData; case CMS_SIGN_DRAFT9: return OBJ_nid2obj(NID_pkcs7_data); case CMS_SIGN_SERVER: return cryptoctx->id_pkinit_DHKeyData; case CMS_ENVEL_SERVER: return cryptoctx->id_pkinit_rkeyData; default: return NULL; } } static int wrap_signeddata(unsigned char *data, unsigned int data_len, unsigned char **out, unsigned int *out_len) { unsigned int orig_len = 0, oid_len = 0, tot_len = 0; ASN1_OBJECT *oid = NULL; unsigned char *p = NULL; /* Get length to wrap the original data with SEQUENCE tag */ tot_len = orig_len = ASN1_object_size(1, (int)data_len, V_ASN1_SEQUENCE); /* Add the signedData OID and adjust lengths */ oid = OBJ_nid2obj(NID_pkcs7_signed); oid_len = i2d_ASN1_OBJECT(oid, NULL); tot_len = ASN1_object_size(1, (int)(orig_len+oid_len), V_ASN1_SEQUENCE); p = *out = malloc(tot_len); if (p == NULL) return -1; ASN1_put_object(&p, 1, (int)(orig_len+oid_len), V_ASN1_SEQUENCE, V_ASN1_UNIVERSAL); i2d_ASN1_OBJECT(oid, &p); ASN1_put_object(&p, 1, (int)data_len, 0, V_ASN1_CONTEXT_SPECIFIC); memcpy(p, data, data_len); *out_len = tot_len; return 0; } static int prepare_enc_data(const uint8_t *indata, int indata_len, uint8_t **outdata, int *outdata_len) { int tag, class; long tlen, slen; const uint8_t *p = indata, *oldp; if (ASN1_get_object(&p, &slen, &tag, &class, indata_len) & 0x80) return EINVAL; if (tag != V_ASN1_SEQUENCE) return EINVAL; oldp = p; if (ASN1_get_object(&p, &tlen, &tag, &class, slen) & 0x80) return EINVAL; p += tlen; slen -= (p - oldp); if (ASN1_get_object(&p, &tlen, &tag, &class, slen) & 0x80) return EINVAL; *outdata = malloc(tlen); if (*outdata == NULL) return ENOMEM; memcpy(*outdata, p, tlen); *outdata_len = tlen; return 0; } #ifndef WITHOUT_PKCS11 static void * pkinit_C_LoadModule(const char *modname, CK_FUNCTION_LIST_PTR_PTR p11p) { void *handle; CK_RV (*getflist)(CK_FUNCTION_LIST_PTR_PTR); pkiDebug("loading module \"%s\"... ", modname); handle = dlopen(modname, RTLD_NOW); if (handle == NULL) { pkiDebug("not found\n"); return NULL; } getflist = (CK_RV (*)(CK_FUNCTION_LIST_PTR_PTR)) dlsym(handle, "C_GetFunctionList"); if (getflist == NULL || (*getflist)(p11p) != CKR_OK) { dlclose(handle); pkiDebug("failed\n"); return NULL; } pkiDebug("ok\n"); return handle; } static CK_RV pkinit_C_UnloadModule(void *handle) { dlclose(handle); return CKR_OK; } static krb5_error_code pkinit_login(krb5_context context, pkinit_identity_crypto_context id_cryptoctx, CK_TOKEN_INFO *tip, const char *password) { krb5_data rdat; char *prompt; const char *warning; krb5_prompt kprompt; krb5_prompt_type prompt_type; int r = 0; if (tip->flags & CKF_PROTECTED_AUTHENTICATION_PATH) { rdat.data = NULL; rdat.length = 0; } else if (password != NULL) { rdat.data = strdup(password); rdat.length = strlen(password); } else if (id_cryptoctx->prompter == NULL) { r = KRB5_LIBOS_CANTREADPWD; rdat.data = NULL; } else { if (tip->flags & CKF_USER_PIN_LOCKED) warning = " (Warning: PIN locked)"; else if (tip->flags & CKF_USER_PIN_FINAL_TRY) warning = " (Warning: PIN final try)"; else if (tip->flags & CKF_USER_PIN_COUNT_LOW) warning = " (Warning: PIN count low)"; else warning = ""; if (asprintf(&prompt, "%.*s PIN%s", (int) sizeof (tip->label), tip->label, warning) < 0) return ENOMEM; rdat.data = malloc(tip->ulMaxPinLen + 2); rdat.length = tip->ulMaxPinLen + 1; kprompt.prompt = prompt; kprompt.hidden = 1; kprompt.reply = &rdat; prompt_type = KRB5_PROMPT_TYPE_PREAUTH; /* PROMPTER_INVOCATION */ k5int_set_prompt_types(context, &prompt_type); r = (*id_cryptoctx->prompter)(context, id_cryptoctx->prompter_data, NULL, NULL, 1, &kprompt); k5int_set_prompt_types(context, 0); free(prompt); } if (r == 0) { r = id_cryptoctx->p11->C_Login(id_cryptoctx->session, CKU_USER, (u_char *) rdat.data, rdat.length); if (r != CKR_OK) { pkiDebug("C_Login: %s\n", pkinit_pkcs11_code_to_text(r)); r = KRB5KDC_ERR_PREAUTH_FAILED; } } free(rdat.data); return r; } static krb5_error_code pkinit_open_session(krb5_context context, pkinit_identity_crypto_context cctx) { CK_ULONG i, r; unsigned char *cp; size_t label_len; CK_ULONG count = 0; CK_SLOT_ID_PTR slotlist; CK_TOKEN_INFO tinfo; char *p11name; const char *password; if (cctx->p11_module != NULL) return 0; /* session already open */ /* Load module */ cctx->p11_module = pkinit_C_LoadModule(cctx->p11_module_name, &cctx->p11); if (cctx->p11_module == NULL) return KRB5KDC_ERR_PREAUTH_FAILED; /* Init */ if ((r = cctx->p11->C_Initialize(NULL)) != CKR_OK) { pkiDebug("C_Initialize: %s\n", pkinit_pkcs11_code_to_text(r)); return KRB5KDC_ERR_PREAUTH_FAILED; } /* Get the list of available slots */ if (cctx->p11->C_GetSlotList(TRUE, NULL, &count) != CKR_OK) return KRB5KDC_ERR_PREAUTH_FAILED; if (count == 0) return KRB5KDC_ERR_PREAUTH_FAILED; slotlist = calloc(count, sizeof(CK_SLOT_ID)); if (slotlist == NULL) return ENOMEM; if (cctx->p11->C_GetSlotList(TRUE, slotlist, &count) != CKR_OK) return KRB5KDC_ERR_PREAUTH_FAILED; /* Look for the given token label, or if none given take the first one */ for (i = 0; i < count; i++) { /* Skip slots that don't match the specified slotid, if given. */ if (cctx->slotid != PK_NOSLOT && cctx->slotid != slotlist[i]) continue; /* Open session */ if ((r = cctx->p11->C_OpenSession(slotlist[i], CKF_SERIAL_SESSION, NULL, NULL, &cctx->session)) != CKR_OK) { pkiDebug("C_OpenSession: %s\n", pkinit_pkcs11_code_to_text(r)); return KRB5KDC_ERR_PREAUTH_FAILED; } /* Get token info */ if ((r = cctx->p11->C_GetTokenInfo(slotlist[i], &tinfo)) != CKR_OK) { pkiDebug("C_GetTokenInfo: %s\n", pkinit_pkcs11_code_to_text(r)); return KRB5KDC_ERR_PREAUTH_FAILED; } /* tinfo.label is zero-filled but not necessarily zero-terminated. * Find the length, ignoring any trailing spaces. */ for (cp = tinfo.label + sizeof(tinfo.label); cp > tinfo.label; cp--) { if (cp[-1] != '\0' && cp[-1] != ' ') break; } label_len = cp - tinfo.label; pkiDebug("open_session: slotid %d token \"%.*s\"\n", (int)slotlist[i], (int)label_len, tinfo.label); if (cctx->token_label == NULL || (strlen(cctx->token_label) == label_len && memcmp(cctx->token_label, tinfo.label, label_len) == 0)) break; cctx->p11->C_CloseSession(cctx->session); } if (i >= count) { free(slotlist); pkiDebug("open_session: no matching token found\n"); return KRB5KDC_ERR_PREAUTH_FAILED; } cctx->slotid = slotlist[i]; free(slotlist); pkiDebug("open_session: slotid %d (%lu of %d)\n", (int)cctx->slotid, i + 1, (int) count); /* Login if needed */ if (tinfo.flags & CKF_LOGIN_REQUIRED) { if (cctx->p11_module_name != NULL) { if (cctx->slotid != PK_NOSLOT) { if (asprintf(&p11name, "PKCS11:module_name=%s:slotid=%ld:token=%.*s", cctx->p11_module_name, (long)cctx->slotid, (int)label_len, tinfo.label) < 0) p11name = NULL; } else { if (asprintf(&p11name, "PKCS11:module_name=%s,token=%.*s", cctx->p11_module_name, (int)label_len, tinfo.label) < 0) p11name = NULL; } } else { p11name = NULL; } if (cctx->defer_id_prompt) { /* Supply the identity name to be passed to the responder. */ pkinit_set_deferred_id(&cctx->deferred_ids, p11name, tinfo.flags, NULL); free(p11name); return KRB5KRB_ERR_GENERIC; } /* Look up a responder-supplied password for the token. */ password = pkinit_find_deferred_id(cctx->deferred_ids, p11name); free(p11name); r = pkinit_login(context, cctx, &tinfo, password); } return r; } /* * Look for a key that's: * 1. private * 2. capable of the specified operation (usually signing or decrypting) * 3. RSA (this may be wrong but it's all we can do for now) * 4. matches the id of the cert we chose * * You must call pkinit_get_certs before calling pkinit_find_private_key * (that's because we need the ID of the private key) * * pkcs11 says the id of the key doesn't have to match that of the cert, but * I can't figure out any other way to decide which key to use. * * We should only find one key that fits all the requirements. * If there are more than one, we just take the first one. */ krb5_error_code pkinit_find_private_key(pkinit_identity_crypto_context id_cryptoctx, CK_ATTRIBUTE_TYPE usage, CK_OBJECT_HANDLE *objp) { CK_OBJECT_CLASS cls; CK_ATTRIBUTE attrs[4]; CK_ULONG count; CK_KEY_TYPE keytype; unsigned int nattrs = 0; int r; #ifdef PKINIT_USE_KEY_USAGE CK_BBOOL true_false; #endif cls = CKO_PRIVATE_KEY; attrs[nattrs].type = CKA_CLASS; attrs[nattrs].pValue = &cls; attrs[nattrs].ulValueLen = sizeof cls; nattrs++; #ifdef PKINIT_USE_KEY_USAGE /* * Some cards get confused if you try to specify a key usage, * so don't, and hope for the best. This will fail if you have * several keys with the same id and different usages but I have * not seen this on real cards. */ true_false = TRUE; attrs[nattrs].type = usage; attrs[nattrs].pValue = &true_false; attrs[nattrs].ulValueLen = sizeof true_false; nattrs++; #endif keytype = CKK_RSA; attrs[nattrs].type = CKA_KEY_TYPE; attrs[nattrs].pValue = &keytype; attrs[nattrs].ulValueLen = sizeof keytype; nattrs++; attrs[nattrs].type = CKA_ID; attrs[nattrs].pValue = id_cryptoctx->cert_id; attrs[nattrs].ulValueLen = id_cryptoctx->cert_id_len; nattrs++; r = id_cryptoctx->p11->C_FindObjectsInit(id_cryptoctx->session, attrs, nattrs); if (r != CKR_OK) { pkiDebug("krb5_pkinit_sign_data: C_FindObjectsInit: %s\n", pkinit_pkcs11_code_to_text(r)); return KRB5KDC_ERR_PREAUTH_FAILED; } r = id_cryptoctx->p11->C_FindObjects(id_cryptoctx->session, objp, 1, &count); id_cryptoctx->p11->C_FindObjectsFinal(id_cryptoctx->session); pkiDebug("found %d private keys (%s)\n", (int) count, pkinit_pkcs11_code_to_text(r)); if (r != CKR_OK || count < 1) return KRB5KDC_ERR_PREAUTH_FAILED; return 0; } #endif static krb5_error_code pkinit_decode_data_fs(krb5_context context, pkinit_identity_crypto_context id_cryptoctx, const uint8_t *data, unsigned int data_len, uint8_t **decoded_data, unsigned int *decoded_data_len) { X509 *cert = sk_X509_value(id_cryptoctx->my_certs, id_cryptoctx->cert_index); EVP_PKEY *pkey = id_cryptoctx->my_key; uint8_t *buf; int buf_len, decrypt_len; *decoded_data = NULL; *decoded_data_len = 0; if (cert != NULL && !X509_check_private_key(cert, pkey)) { pkiDebug("private key does not match certificate\n"); return KRB5KDC_ERR_PREAUTH_FAILED; } buf_len = EVP_PKEY_size(pkey); buf = malloc(buf_len + 10); if (buf == NULL) return KRB5KDC_ERR_PREAUTH_FAILED; decrypt_len = EVP_PKEY_decrypt_old(buf, data, data_len, pkey); if (decrypt_len <= 0) { pkiDebug("unable to decrypt received data (len=%d)\n", data_len); free(buf); return KRB5KDC_ERR_PREAUTH_FAILED; } *decoded_data = buf; *decoded_data_len = decrypt_len; return 0; } #ifndef WITHOUT_PKCS11 /* * When using the ActivCard Linux pkcs11 library (v2.0.1), the decrypt function * fails. By inserting an extra function call, which serves nothing but to * change the stack, we were able to work around the issue. If the ActivCard * library is fixed in the future, this function can be inlined back into the * caller. */ static CK_RV pkinit_C_Decrypt(pkinit_identity_crypto_context id_cryptoctx, CK_BYTE_PTR pEncryptedData, CK_ULONG ulEncryptedDataLen, CK_BYTE_PTR pData, CK_ULONG_PTR pulDataLen) { CK_RV rv = CKR_OK; rv = id_cryptoctx->p11->C_Decrypt(id_cryptoctx->session, pEncryptedData, ulEncryptedDataLen, pData, pulDataLen); if (rv == CKR_OK) { pkiDebug("pData %p *pulDataLen %d\n", (void *) pData, (int) *pulDataLen); } return rv; } static krb5_error_code pkinit_decode_data_pkcs11(krb5_context context, pkinit_identity_crypto_context id_cryptoctx, const uint8_t *data, unsigned int data_len, uint8_t **decoded_data, unsigned int *decoded_data_len) { CK_OBJECT_HANDLE obj; CK_ULONG len; CK_MECHANISM mech; uint8_t *cp; int r; *decoded_data = NULL; *decoded_data_len = 0; if (pkinit_open_session(context, id_cryptoctx)) { pkiDebug("can't open pkcs11 session\n"); return KRB5KDC_ERR_PREAUTH_FAILED; } pkinit_find_private_key(id_cryptoctx, CKA_DECRYPT, &obj); mech.mechanism = CKM_RSA_PKCS; mech.pParameter = NULL; mech.ulParameterLen = 0; if ((r = id_cryptoctx->p11->C_DecryptInit(id_cryptoctx->session, &mech, obj)) != CKR_OK) { pkiDebug("C_DecryptInit: 0x%x\n", (int) r); return KRB5KDC_ERR_PREAUTH_FAILED; } pkiDebug("data_len = %d\n", data_len); cp = malloc((size_t) data_len); if (cp == NULL) return ENOMEM; len = data_len; pkiDebug("session %p edata %p edata_len %d data %p datalen @%p %d\n", (void *) id_cryptoctx->session, (void *) data, (int) data_len, (void *) cp, (void *) &len, (int) len); r = pkinit_C_Decrypt(id_cryptoctx, (CK_BYTE_PTR) data, (CK_ULONG) data_len, cp, &len); if (r != CKR_OK) { pkiDebug("C_Decrypt: %s\n", pkinit_pkcs11_code_to_text(r)); if (r == CKR_BUFFER_TOO_SMALL) pkiDebug("decrypt %d needs %d\n", (int) data_len, (int) len); return KRB5KDC_ERR_PREAUTH_FAILED; } pkiDebug("decrypt %d -> %d\n", (int) data_len, (int) len); *decoded_data_len = len; *decoded_data = cp; return 0; } #endif krb5_error_code pkinit_decode_data(krb5_context context, pkinit_identity_crypto_context id_cryptoctx, const uint8_t *data, unsigned int data_len, uint8_t **decoded_data, unsigned int *decoded_data_len) { krb5_error_code retval = KRB5KDC_ERR_PREAUTH_FAILED; *decoded_data = NULL; *decoded_data_len = 0; if (id_cryptoctx->pkcs11_method != 1) retval = pkinit_decode_data_fs(context, id_cryptoctx, data, data_len, decoded_data, decoded_data_len); #ifndef WITHOUT_PKCS11 else retval = pkinit_decode_data_pkcs11(context, id_cryptoctx, data, data_len, decoded_data, decoded_data_len); #endif return retval; } static krb5_error_code pkinit_sign_data_fs(krb5_context context, pkinit_identity_crypto_context id_cryptoctx, unsigned char *data, unsigned int data_len, unsigned char **sig, unsigned int *sig_len) { if (create_signature(sig, sig_len, data, data_len, id_cryptoctx->my_key) != 0) { pkiDebug("failed to create the signature\n"); return KRB5KDC_ERR_PREAUTH_FAILED; } return 0; } #ifndef WITHOUT_PKCS11 static krb5_error_code pkinit_sign_data_pkcs11(krb5_context context, pkinit_identity_crypto_context id_cryptoctx, unsigned char *data, unsigned int data_len, unsigned char **sig, unsigned int *sig_len) { CK_OBJECT_HANDLE obj; CK_ULONG len; CK_MECHANISM mech; unsigned char *cp; int r; if (pkinit_open_session(context, id_cryptoctx)) { pkiDebug("can't open pkcs11 session\n"); return KRB5KDC_ERR_PREAUTH_FAILED; } pkinit_find_private_key(id_cryptoctx, CKA_SIGN, &obj); mech.mechanism = id_cryptoctx->mech; mech.pParameter = NULL; mech.ulParameterLen = 0; if ((r = id_cryptoctx->p11->C_SignInit(id_cryptoctx->session, &mech, obj)) != CKR_OK) { pkiDebug("C_SignInit: %s\n", pkinit_pkcs11_code_to_text(r)); return KRB5KDC_ERR_PREAUTH_FAILED; } /* * Key len would give an upper bound on sig size, but there's no way to * get that. So guess, and if it's too small, re-malloc. */ len = PK_SIGLEN_GUESS; cp = malloc((size_t) len); if (cp == NULL) return ENOMEM; r = id_cryptoctx->p11->C_Sign(id_cryptoctx->session, data, (CK_ULONG) data_len, cp, &len); if (r == CKR_BUFFER_TOO_SMALL || (r == CKR_OK && len >= PK_SIGLEN_GUESS)) { free(cp); pkiDebug("C_Sign realloc %d\n", (int) len); cp = malloc((size_t) len); r = id_cryptoctx->p11->C_Sign(id_cryptoctx->session, data, (CK_ULONG) data_len, cp, &len); } if (r != CKR_OK) { pkiDebug("C_Sign: %s\n", pkinit_pkcs11_code_to_text(r)); return KRB5KDC_ERR_PREAUTH_FAILED; } pkiDebug("sign %d -> %d\n", (int) data_len, (int) len); *sig_len = len; *sig = cp; return 0; } #endif krb5_error_code pkinit_sign_data(krb5_context context, pkinit_identity_crypto_context id_cryptoctx, unsigned char *data, unsigned int data_len, unsigned char **sig, unsigned int *sig_len) { krb5_error_code retval = KRB5KDC_ERR_PREAUTH_FAILED; if (id_cryptoctx == NULL || id_cryptoctx->pkcs11_method != 1) retval = pkinit_sign_data_fs(context, id_cryptoctx, data, data_len, sig, sig_len); #ifndef WITHOUT_PKCS11 else retval = pkinit_sign_data_pkcs11(context, id_cryptoctx, data, data_len, sig, sig_len); #endif return retval; } static krb5_error_code create_signature(unsigned char **sig, unsigned int *sig_len, unsigned char *data, unsigned int data_len, EVP_PKEY *pkey) { krb5_error_code retval = ENOMEM; EVP_MD_CTX *ctx; if (pkey == NULL) return retval; ctx = EVP_MD_CTX_new(); if (ctx == NULL) return ENOMEM; EVP_SignInit(ctx, EVP_sha1()); EVP_SignUpdate(ctx, data, data_len); *sig_len = EVP_PKEY_size(pkey); if ((*sig = malloc(*sig_len)) == NULL) goto cleanup; EVP_SignFinal(ctx, *sig, sig_len, pkey); retval = 0; cleanup: EVP_MD_CTX_free(ctx); return retval; } /* * Note: * This is not the routine the KDC uses to get its certificate. * This routine is intended to be called by the client * to obtain the KDC's certificate from some local storage * to be sent as a hint in its request to the KDC. */ krb5_error_code pkinit_get_kdc_cert(krb5_context context, pkinit_plg_crypto_context plg_cryptoctx, pkinit_req_crypto_context req_cryptoctx, pkinit_identity_crypto_context id_cryptoctx, krb5_principal princ) { krb5_error_code retval = KRB5KDC_ERR_PREAUTH_FAILED; req_cryptoctx->received_cert = NULL; retval = 0; return retval; } static char * reassemble_pkcs12_name(const char *filename) { char *ret; if (asprintf(&ret, "PKCS12:%s", filename) < 0) return NULL; return ret; } static krb5_error_code pkinit_get_certs_pkcs12(krb5_context context, pkinit_plg_crypto_context plg_cryptoctx, pkinit_req_crypto_context req_cryptoctx, pkinit_identity_opts *idopts, pkinit_identity_crypto_context id_cryptoctx, krb5_principal princ) { krb5_error_code retval = KRB5KDC_ERR_PREAUTH_FAILED; char *prompt_string = NULL; X509 *x = NULL; PKCS12 *p12 = NULL; int ret; FILE *fp; EVP_PKEY *y = NULL; if (idopts->cert_filename == NULL) { pkiDebug("%s: failed to get user's cert location\n", __FUNCTION__); goto cleanup; } if (idopts->key_filename == NULL) { pkiDebug("%s: failed to get user's private key location\n", __FUNCTION__); goto cleanup; } fp = fopen(idopts->cert_filename, "rb"); if (fp == NULL) { TRACE_PKINIT_PKCS_OPEN_FAIL(context, idopts->cert_filename, errno); goto cleanup; } set_cloexec_file(fp); p12 = d2i_PKCS12_fp(fp, NULL); fclose(fp); if (p12 == NULL) { TRACE_PKINIT_PKCS_DECODE_FAIL(context, idopts->cert_filename); goto cleanup; } /* * Try parsing with no pass phrase first. If that fails, * prompt for the pass phrase and try again. */ ret = PKCS12_parse(p12, NULL, &y, &x, NULL); if (ret == 0) { krb5_data rdat; krb5_prompt kprompt; krb5_prompt_type prompt_type; krb5_error_code r; char prompt_reply[128]; char *prompt_prefix = _("Pass phrase for"); char *p12name = reassemble_pkcs12_name(idopts->cert_filename); const char *tmp; TRACE_PKINIT_PKCS_PARSE_FAIL_FIRST(context); if (id_cryptoctx->defer_id_prompt) { /* Supply the identity name to be passed to the responder. */ pkinit_set_deferred_id(&id_cryptoctx->deferred_ids, p12name, 0, NULL); free(p12name); retval = 0; goto cleanup; } /* Try to read a responder-supplied password. */ tmp = pkinit_find_deferred_id(id_cryptoctx->deferred_ids, p12name); free(p12name); if (tmp != NULL) { /* Try using the responder-supplied password. */ rdat.data = (char *)tmp; rdat.length = strlen(tmp); } else if (id_cryptoctx->prompter == NULL) { /* We can't use a prompter. */ goto cleanup; } else { /* Ask using a prompter. */ memset(prompt_reply, '\0', sizeof(prompt_reply)); rdat.data = prompt_reply; rdat.length = sizeof(prompt_reply); if (asprintf(&prompt_string, "%s %s", prompt_prefix, idopts->cert_filename) < 0) { prompt_string = NULL; goto cleanup; } kprompt.prompt = prompt_string; kprompt.hidden = 1; kprompt.reply = &rdat; prompt_type = KRB5_PROMPT_TYPE_PREAUTH; /* PROMPTER_INVOCATION */ k5int_set_prompt_types(context, &prompt_type); r = (*id_cryptoctx->prompter)(context, id_cryptoctx->prompter_data, NULL, NULL, 1, &kprompt); k5int_set_prompt_types(context, 0); if (r) { TRACE_PKINIT_PKCS_PROMPT_FAIL(context); goto cleanup; } } ret = PKCS12_parse(p12, rdat.data, &y, &x, NULL); if (ret == 0) { TRACE_PKINIT_PKCS_PARSE_FAIL_SECOND(context); goto cleanup; } } id_cryptoctx->creds[0] = malloc(sizeof(struct _pkinit_cred_info)); if (id_cryptoctx->creds[0] == NULL) goto cleanup; id_cryptoctx->creds[0]->name = reassemble_pkcs12_name(idopts->cert_filename); id_cryptoctx->creds[0]->cert = x; #ifndef WITHOUT_PKCS11 id_cryptoctx->creds[0]->cert_id = NULL; id_cryptoctx->creds[0]->cert_id_len = 0; #endif id_cryptoctx->creds[0]->key = y; id_cryptoctx->creds[1] = NULL; retval = 0; cleanup: free(prompt_string); if (p12) PKCS12_free(p12); if (retval) { if (x != NULL) X509_free(x); if (y != NULL) EVP_PKEY_free(y); } return retval; } static char * reassemble_files_name(const char *certfile, const char *keyfile) { char *ret; if (keyfile != NULL) { if (asprintf(&ret, "FILE:%s,%s", certfile, keyfile) < 0) return NULL; } else { if (asprintf(&ret, "FILE:%s", certfile) < 0) return NULL; } return ret; } static krb5_error_code pkinit_load_fs_cert_and_key(krb5_context context, pkinit_identity_crypto_context id_cryptoctx, char *certname, char *keyname, int cindex) { krb5_error_code retval; X509 *x = NULL; EVP_PKEY *y = NULL; char *fsname = NULL; const char *password; fsname = reassemble_files_name(certname, keyname); /* Try to read a responder-supplied password. */ password = pkinit_find_deferred_id(id_cryptoctx->deferred_ids, fsname); /* Load the certificate. */ retval = get_cert(certname, &x); if (retval != 0 || x == NULL) { retval = oerr(context, 0, _("Cannot read certificate file '%s'"), certname); goto cleanup; } /* Load the key. */ retval = get_key(context, id_cryptoctx, keyname, fsname, &y, password); if (retval != 0 || y == NULL) { retval = oerr(context, 0, _("Cannot read key file '%s'"), fsname); goto cleanup; } id_cryptoctx->creds[cindex] = malloc(sizeof(struct _pkinit_cred_info)); if (id_cryptoctx->creds[cindex] == NULL) { retval = ENOMEM; goto cleanup; } id_cryptoctx->creds[cindex]->name = reassemble_files_name(certname, keyname); id_cryptoctx->creds[cindex]->cert = x; #ifndef WITHOUT_PKCS11 id_cryptoctx->creds[cindex]->cert_id = NULL; id_cryptoctx->creds[cindex]->cert_id_len = 0; #endif id_cryptoctx->creds[cindex]->key = y; id_cryptoctx->creds[cindex+1] = NULL; retval = 0; cleanup: free(fsname); if (retval != 0 || y == NULL) { if (x != NULL) X509_free(x); if (y != NULL) EVP_PKEY_free(y); } return retval; } static krb5_error_code pkinit_get_certs_fs(krb5_context context, pkinit_plg_crypto_context plg_cryptoctx, pkinit_req_crypto_context req_cryptoctx, pkinit_identity_opts *idopts, pkinit_identity_crypto_context id_cryptoctx, krb5_principal princ) { krb5_error_code retval = KRB5KDC_ERR_PREAUTH_FAILED; if (idopts->cert_filename == NULL) { pkiDebug("%s: failed to get user's cert location\n", __FUNCTION__); goto cleanup; } if (idopts->key_filename == NULL) { TRACE_PKINIT_NO_PRIVKEY(context); goto cleanup; } retval = pkinit_load_fs_cert_and_key(context, id_cryptoctx, idopts->cert_filename, idopts->key_filename, 0); cleanup: return retval; } static krb5_error_code pkinit_get_certs_dir(krb5_context context, pkinit_plg_crypto_context plg_cryptoctx, pkinit_req_crypto_context req_cryptoctx, pkinit_identity_opts *idopts, pkinit_identity_crypto_context id_cryptoctx, krb5_principal princ) { krb5_error_code retval = ENOMEM; DIR *d = NULL; struct dirent *dentry = NULL; char certname[1024]; char keyname[1024]; int i = 0, len; char *dirname, *suf; if (idopts->cert_filename == NULL) { TRACE_PKINIT_NO_CERT(context); return ENOENT; } dirname = idopts->cert_filename; d = opendir(dirname); if (d == NULL) return errno; /* * We'll assume that certs are named XXX.crt and the corresponding * key is named XXX.key */ while ((i < MAX_CREDS_ALLOWED) && (dentry = readdir(d)) != NULL) { /* Ignore subdirectories and anything starting with a dot */ #ifdef DT_DIR if (dentry->d_type == DT_DIR) continue; #endif if (dentry->d_name[0] == '.') continue; len = strlen(dentry->d_name); if (len < 5) continue; suf = dentry->d_name + (len - 4); if (strncmp(suf, ".crt", 4) != 0) continue; /* Checked length */ if (strlen(dirname) + strlen(dentry->d_name) + 2 > sizeof(certname)) { pkiDebug("%s: Path too long -- directory '%s' and file '%s'\n", __FUNCTION__, dirname, dentry->d_name); continue; } snprintf(certname, sizeof(certname), "%s/%s", dirname, dentry->d_name); snprintf(keyname, sizeof(keyname), "%s/%s", dirname, dentry->d_name); len = strlen(keyname); keyname[len - 3] = 'k'; keyname[len - 2] = 'e'; keyname[len - 1] = 'y'; retval = pkinit_load_fs_cert_and_key(context, id_cryptoctx, certname, keyname, i); if (retval == 0) { TRACE_PKINIT_LOADED_CERT(context, dentry->d_name); i++; } else continue; } if (!id_cryptoctx->defer_id_prompt && i == 0) { TRACE_PKINIT_NO_CERT_AND_KEY(context, idopts->cert_filename); retval = ENOENT; goto cleanup; } retval = 0; cleanup: if (d) closedir(d); return retval; } #ifndef WITHOUT_PKCS11 static char * reassemble_pkcs11_name(pkinit_identity_opts *idopts) { struct k5buf buf; int n = 0; char *ret; k5_buf_init_dynamic(&buf); k5_buf_add(&buf, "PKCS11:"); n = 0; if (idopts->p11_module_name != NULL) { k5_buf_add_fmt(&buf, "%smodule_name=%s", n++ ? ":" : "", idopts->p11_module_name); } if (idopts->token_label != NULL) { k5_buf_add_fmt(&buf, "%stoken=%s", n++ ? ":" : "", idopts->token_label); } if (idopts->cert_label != NULL) { k5_buf_add_fmt(&buf, "%scertlabel=%s", n++ ? ":" : "", idopts->cert_label); } if (idopts->cert_id_string != NULL) { k5_buf_add_fmt(&buf, "%scertid=%s", n++ ? ":" : "", idopts->cert_id_string); } if (idopts->slotid != PK_NOSLOT) { k5_buf_add_fmt(&buf, "%sslotid=%ld", n++ ? ":" : "", (long)idopts->slotid); } if (k5_buf_status(&buf) == 0) ret = strdup(buf.data); else ret = NULL; k5_buf_free(&buf); return ret; } static krb5_error_code pkinit_get_certs_pkcs11(krb5_context context, pkinit_plg_crypto_context plg_cryptoctx, pkinit_req_crypto_context req_cryptoctx, pkinit_identity_opts *idopts, pkinit_identity_crypto_context id_cryptoctx, krb5_principal princ) { #ifdef PKINIT_USE_MECH_LIST CK_MECHANISM_TYPE_PTR mechp; CK_MECHANISM_INFO info; #endif CK_OBJECT_CLASS cls; CK_OBJECT_HANDLE obj; CK_ATTRIBUTE attrs[4]; CK_ULONG count; CK_CERTIFICATE_TYPE certtype; CK_BYTE_PTR cert = NULL, cert_id; const unsigned char *cp; int i, r; unsigned int nattrs; X509 *x = NULL; /* Copy stuff from idopts -> id_cryptoctx */ if (idopts->p11_module_name != NULL) { free(id_cryptoctx->p11_module_name); id_cryptoctx->p11_module_name = strdup(idopts->p11_module_name); if (id_cryptoctx->p11_module_name == NULL) return ENOMEM; } if (idopts->token_label != NULL) { id_cryptoctx->token_label = strdup(idopts->token_label); if (id_cryptoctx->token_label == NULL) return ENOMEM; } if (idopts->cert_label != NULL) { id_cryptoctx->cert_label = strdup(idopts->cert_label); if (id_cryptoctx->cert_label == NULL) return ENOMEM; } /* Convert the ascii cert_id string into a binary blob */ if (idopts->cert_id_string != NULL) { BIGNUM *bn = NULL; BN_hex2bn(&bn, idopts->cert_id_string); if (bn == NULL) return ENOMEM; id_cryptoctx->cert_id_len = BN_num_bytes(bn); id_cryptoctx->cert_id = malloc((size_t) id_cryptoctx->cert_id_len); if (id_cryptoctx->cert_id == NULL) { BN_free(bn); return ENOMEM; } BN_bn2bin(bn, id_cryptoctx->cert_id); BN_free(bn); } id_cryptoctx->slotid = idopts->slotid; id_cryptoctx->pkcs11_method = 1; if (pkinit_open_session(context, id_cryptoctx)) { pkiDebug("can't open pkcs11 session\n"); if (!id_cryptoctx->defer_id_prompt) return KRB5KDC_ERR_PREAUTH_FAILED; } if (id_cryptoctx->defer_id_prompt) { /* * We need to reset all of the PKCS#11 state, so that the next time we * poke at it, it'll be in as close to the state it was in after we * loaded it the first time as we can make it. */ pkinit_fini_pkcs11(id_cryptoctx); pkinit_init_pkcs11(id_cryptoctx); return 0; } #ifndef PKINIT_USE_MECH_LIST /* * We'd like to use CKM_SHA1_RSA_PKCS for signing if it's available, but * many cards seems to be confused about whether they are capable of * this or not. The safe thing seems to be to ignore the mechanism list, * always use CKM_RSA_PKCS and calculate the sha1 digest ourselves. */ id_cryptoctx->mech = CKM_RSA_PKCS; #else if ((r = id_cryptoctx->p11->C_GetMechanismList(id_cryptoctx->slotid, NULL, &count)) != CKR_OK || count <= 0) { pkiDebug("C_GetMechanismList: %s\n", pkinit_pkcs11_code_to_text(r)); return KRB5KDC_ERR_PREAUTH_FAILED; } mechp = malloc(count * sizeof (CK_MECHANISM_TYPE)); if (mechp == NULL) return ENOMEM; if ((r = id_cryptoctx->p11->C_GetMechanismList(id_cryptoctx->slotid, mechp, &count)) != CKR_OK) return KRB5KDC_ERR_PREAUTH_FAILED; for (i = 0; i < count; i++) { if ((r = id_cryptoctx->p11->C_GetMechanismInfo(id_cryptoctx->slotid, mechp[i], &info)) != CKR_OK) return KRB5KDC_ERR_PREAUTH_FAILED; #ifdef DEBUG_MECHINFO pkiDebug("mech %x flags %x\n", (int) mechp[i], (int) info.flags); if ((info.flags & (CKF_SIGN|CKF_DECRYPT)) == (CKF_SIGN|CKF_DECRYPT)) pkiDebug(" this mech is good for sign & decrypt\n"); #endif if (mechp[i] == CKM_RSA_PKCS) { /* This seems backwards... */ id_cryptoctx->mech = (info.flags & CKF_SIGN) ? CKM_SHA1_RSA_PKCS : CKM_RSA_PKCS; } } free(mechp); pkiDebug("got %d mechs from card\n", (int) count); #endif cls = CKO_CERTIFICATE; attrs[0].type = CKA_CLASS; attrs[0].pValue = &cls; attrs[0].ulValueLen = sizeof cls; certtype = CKC_X_509; attrs[1].type = CKA_CERTIFICATE_TYPE; attrs[1].pValue = &certtype; attrs[1].ulValueLen = sizeof certtype; nattrs = 2; /* If a cert id and/or label were given, use them too */ if (id_cryptoctx->cert_id_len > 0) { attrs[nattrs].type = CKA_ID; attrs[nattrs].pValue = id_cryptoctx->cert_id; attrs[nattrs].ulValueLen = id_cryptoctx->cert_id_len; nattrs++; } if (id_cryptoctx->cert_label != NULL) { attrs[nattrs].type = CKA_LABEL; attrs[nattrs].pValue = id_cryptoctx->cert_label; attrs[nattrs].ulValueLen = strlen(id_cryptoctx->cert_label); nattrs++; } r = id_cryptoctx->p11->C_FindObjectsInit(id_cryptoctx->session, attrs, nattrs); if (r != CKR_OK) { pkiDebug("C_FindObjectsInit: %s\n", pkinit_pkcs11_code_to_text(r)); return KRB5KDC_ERR_PREAUTH_FAILED; } for (i = 0; ; i++) { if (i >= MAX_CREDS_ALLOWED) return KRB5KDC_ERR_PREAUTH_FAILED; /* Look for x.509 cert */ if ((r = id_cryptoctx->p11->C_FindObjects(id_cryptoctx->session, &obj, 1, &count)) != CKR_OK || count <= 0) { id_cryptoctx->creds[i] = NULL; break; } /* Get cert and id len */ attrs[0].type = CKA_VALUE; attrs[0].pValue = NULL; attrs[0].ulValueLen = 0; attrs[1].type = CKA_ID; attrs[1].pValue = NULL; attrs[1].ulValueLen = 0; if ((r = id_cryptoctx->p11->C_GetAttributeValue(id_cryptoctx->session, obj, attrs, 2)) != CKR_OK && r != CKR_BUFFER_TOO_SMALL) { pkiDebug("C_GetAttributeValue: %s\n", pkinit_pkcs11_code_to_text(r)); return KRB5KDC_ERR_PREAUTH_FAILED; } cert = (CK_BYTE_PTR) malloc((size_t) attrs[0].ulValueLen + 1); cert_id = (CK_BYTE_PTR) malloc((size_t) attrs[1].ulValueLen + 1); if (cert == NULL || cert_id == NULL) return ENOMEM; /* Read the cert and id off the card */ attrs[0].type = CKA_VALUE; attrs[0].pValue = cert; attrs[1].type = CKA_ID; attrs[1].pValue = cert_id; if ((r = id_cryptoctx->p11->C_GetAttributeValue(id_cryptoctx->session, obj, attrs, 2)) != CKR_OK) { pkiDebug("C_GetAttributeValue: %s\n", pkinit_pkcs11_code_to_text(r)); return KRB5KDC_ERR_PREAUTH_FAILED; } pkiDebug("cert %d size %d id %d idlen %d\n", i, (int) attrs[0].ulValueLen, (int) cert_id[0], (int) attrs[1].ulValueLen); cp = (unsigned char *) cert; x = d2i_X509(NULL, &cp, (int) attrs[0].ulValueLen); if (x == NULL) return KRB5KDC_ERR_PREAUTH_FAILED; id_cryptoctx->creds[i] = malloc(sizeof(struct _pkinit_cred_info)); if (id_cryptoctx->creds[i] == NULL) return KRB5KDC_ERR_PREAUTH_FAILED; id_cryptoctx->creds[i]->name = reassemble_pkcs11_name(idopts); id_cryptoctx->creds[i]->cert = x; id_cryptoctx->creds[i]->key = NULL; id_cryptoctx->creds[i]->cert_id = cert_id; id_cryptoctx->creds[i]->cert_id_len = attrs[1].ulValueLen; free(cert); } id_cryptoctx->p11->C_FindObjectsFinal(id_cryptoctx->session); if (cert == NULL) return KRB5KDC_ERR_PREAUTH_FAILED; return 0; } #endif static void free_cred_info(krb5_context context, pkinit_identity_crypto_context id_cryptoctx, struct _pkinit_cred_info *cred) { if (cred != NULL) { if (cred->cert != NULL) X509_free(cred->cert); if (cred->key != NULL) EVP_PKEY_free(cred->key); #ifndef WITHOUT_PKCS11 free(cred->cert_id); #endif free(cred->name); free(cred); } } krb5_error_code crypto_free_cert_info(krb5_context context, pkinit_plg_crypto_context plg_cryptoctx, pkinit_req_crypto_context req_cryptoctx, pkinit_identity_crypto_context id_cryptoctx) { int i; if (id_cryptoctx == NULL) return EINVAL; for (i = 0; i < MAX_CREDS_ALLOWED; i++) { if (id_cryptoctx->creds[i] != NULL) { free_cred_info(context, id_cryptoctx, id_cryptoctx->creds[i]); id_cryptoctx->creds[i] = NULL; } } return 0; } krb5_error_code crypto_load_certs(krb5_context context, pkinit_plg_crypto_context plg_cryptoctx, pkinit_req_crypto_context req_cryptoctx, pkinit_identity_opts *idopts, pkinit_identity_crypto_context id_cryptoctx, krb5_principal princ, krb5_boolean defer_id_prompts) { krb5_error_code retval; id_cryptoctx->defer_id_prompt = defer_id_prompts; switch(idopts->idtype) { case IDTYPE_FILE: retval = pkinit_get_certs_fs(context, plg_cryptoctx, req_cryptoctx, idopts, id_cryptoctx, princ); break; case IDTYPE_DIR: retval = pkinit_get_certs_dir(context, plg_cryptoctx, req_cryptoctx, idopts, id_cryptoctx, princ); break; #ifndef WITHOUT_PKCS11 case IDTYPE_PKCS11: retval = pkinit_get_certs_pkcs11(context, plg_cryptoctx, req_cryptoctx, idopts, id_cryptoctx, princ); break; #endif case IDTYPE_PKCS12: retval = pkinit_get_certs_pkcs12(context, plg_cryptoctx, req_cryptoctx, idopts, id_cryptoctx, princ); break; default: retval = EINVAL; } if (retval) goto cleanup; cleanup: return retval; } /* * Get certificate Key Usage and Extended Key Usage */ static krb5_error_code crypto_retrieve_X509_key_usage(krb5_context context, pkinit_plg_crypto_context plgcctx, pkinit_req_crypto_context reqcctx, X509 *x, unsigned int *ret_ku_bits, unsigned int *ret_eku_bits) { krb5_error_code retval = 0; int i; unsigned int eku_bits = 0, ku_bits = 0; ASN1_BIT_STRING *usage = NULL; if (ret_ku_bits == NULL && ret_eku_bits == NULL) return EINVAL; if (ret_eku_bits) *ret_eku_bits = 0; else { pkiDebug("%s: EKUs not requested, not checking\n", __FUNCTION__); goto check_kus; } /* Start with Extended Key usage */ i = X509_get_ext_by_NID(x, NID_ext_key_usage, -1); if (i >= 0) { EXTENDED_KEY_USAGE *eku; eku = X509_get_ext_d2i(x, NID_ext_key_usage, NULL, NULL); if (eku) { for (i = 0; i < sk_ASN1_OBJECT_num(eku); i++) { ASN1_OBJECT *certoid; certoid = sk_ASN1_OBJECT_value(eku, i); if ((OBJ_cmp(certoid, plgcctx->id_pkinit_KPClientAuth)) == 0) eku_bits |= PKINIT_EKU_PKINIT; else if ((OBJ_cmp(certoid, OBJ_nid2obj(NID_ms_smartcard_login))) == 0) eku_bits |= PKINIT_EKU_MSSCLOGIN; else if ((OBJ_cmp(certoid, OBJ_nid2obj(NID_client_auth))) == 0) eku_bits |= PKINIT_EKU_CLIENTAUTH; else if ((OBJ_cmp(certoid, OBJ_nid2obj(NID_email_protect))) == 0) eku_bits |= PKINIT_EKU_EMAILPROTECTION; } EXTENDED_KEY_USAGE_free(eku); } } pkiDebug("%s: returning eku 0x%08x\n", __FUNCTION__, eku_bits); *ret_eku_bits = eku_bits; check_kus: /* Now the Key Usage bits */ if (ret_ku_bits) *ret_ku_bits = 0; else { pkiDebug("%s: KUs not requested, not checking\n", __FUNCTION__); goto out; } /* Make sure usage exists before checking bits */ X509_check_ca(x); usage = X509_get_ext_d2i(x, NID_key_usage, NULL, NULL); if (usage) { if (!ku_reject(x, X509v3_KU_DIGITAL_SIGNATURE)) ku_bits |= PKINIT_KU_DIGITALSIGNATURE; if (!ku_reject(x, X509v3_KU_KEY_ENCIPHERMENT)) ku_bits |= PKINIT_KU_KEYENCIPHERMENT; ASN1_BIT_STRING_free(usage); } pkiDebug("%s: returning ku 0x%08x\n", __FUNCTION__, ku_bits); *ret_ku_bits = ku_bits; retval = 0; out: return retval; } /* * Return a string format of an X509_NAME in buf where * size is an in/out parameter. On input it is the size * of the buffer, and on output it is the actual length * of the name. * If buf is NULL, returns the length req'd to hold name */ static char * X509_NAME_oneline_ex(X509_NAME * a, char *buf, unsigned int *size, unsigned long flag) { BIO *out = NULL; out = BIO_new(BIO_s_mem ()); if (X509_NAME_print_ex(out, a, 0, flag) > 0) { if (buf != NULL && (*size) > (unsigned int) BIO_number_written(out)) { memset(buf, 0, *size); BIO_read(out, buf, (int) BIO_number_written(out)); } else { *size = BIO_number_written(out); } } BIO_free(out); return (buf); } /* * Get number of certificates available after crypto_load_certs() */ static krb5_error_code crypto_cert_get_count(pkinit_identity_crypto_context id_cryptoctx, int *cert_count) { int count; *cert_count = 0; if (id_cryptoctx == NULL || id_cryptoctx->creds[0] == NULL) return EINVAL; for (count = 0; count <= MAX_CREDS_ALLOWED && id_cryptoctx->creds[count] != NULL; count++); *cert_count = count; return 0; } void crypto_cert_free_matching_data(krb5_context context, pkinit_cert_matching_data *md) { int i; if (md == NULL) return; free(md->subject_dn); free(md->issuer_dn); for (i = 0; md->sans != NULL && md->sans[i] != NULL; i++) krb5_free_principal(context, md->sans[i]); free(md->sans); free(md); } /* * Free certificate matching data. */ void crypto_cert_free_matching_data_list(krb5_context context, pkinit_cert_matching_data **list) { int i; for (i = 0; list != NULL && list[i] != NULL; i++) crypto_cert_free_matching_data(context, list[i]); free(list); } /* * Get certificate matching data for cert. */ static krb5_error_code get_matching_data(krb5_context context, pkinit_plg_crypto_context plg_cryptoctx, pkinit_req_crypto_context req_cryptoctx, X509 *cert, pkinit_cert_matching_data **md_out) { krb5_error_code ret = ENOMEM; pkinit_cert_matching_data *md = NULL; krb5_principal *pkinit_sans = NULL, *upn_sans = NULL; size_t i, j; char buf[DN_BUF_LEN]; unsigned int bufsize = sizeof(buf); *md_out = NULL; md = calloc(1, sizeof(*md)); if (md == NULL) goto cleanup; /* Get the subject name (in rfc2253 format). */ X509_NAME_oneline_ex(X509_get_subject_name(cert), buf, &bufsize, XN_FLAG_SEP_COMMA_PLUS); md->subject_dn = strdup(buf); if (md->subject_dn == NULL) { ret = ENOMEM; goto cleanup; } /* Get the issuer name (in rfc2253 format). */ X509_NAME_oneline_ex(X509_get_issuer_name(cert), buf, &bufsize, XN_FLAG_SEP_COMMA_PLUS); md->issuer_dn = strdup(buf); if (md->issuer_dn == NULL) { ret = ENOMEM; goto cleanup; } /* Get the SAN data. */ ret = crypto_retrieve_X509_sans(context, plg_cryptoctx, req_cryptoctx, cert, &pkinit_sans, &upn_sans, NULL); if (ret) goto cleanup; j = 0; if (pkinit_sans != NULL) { for (i = 0; pkinit_sans[i] != NULL; i++) j++; } if (upn_sans != NULL) { for (i = 0; upn_sans[i] != NULL; i++) j++; } if (j != 0) { md->sans = calloc((size_t)j+1, sizeof(*md->sans)); if (md->sans == NULL) { ret = ENOMEM; goto cleanup; } j = 0; if (pkinit_sans != NULL) { for (i = 0; pkinit_sans[i] != NULL; i++) md->sans[j++] = pkinit_sans[i]; free(pkinit_sans); } if (upn_sans != NULL) { for (i = 0; upn_sans[i] != NULL; i++) md->sans[j++] = upn_sans[i]; free(upn_sans); } md->sans[j] = NULL; } else md->sans = NULL; /* Get the KU and EKU data. */ ret = crypto_retrieve_X509_key_usage(context, plg_cryptoctx, req_cryptoctx, cert, &md->ku_bits, &md->eku_bits); if (ret) goto cleanup; *md_out = md; md = NULL; cleanup: crypto_cert_free_matching_data(context, md); return ret; } krb5_error_code crypto_cert_get_matching_data(krb5_context context, pkinit_plg_crypto_context plg_cryptoctx, pkinit_req_crypto_context req_cryptoctx, pkinit_identity_crypto_context id_cryptoctx, pkinit_cert_matching_data ***md_out) { krb5_error_code ret; pkinit_cert_matching_data **md_list = NULL; int count, i; ret = crypto_cert_get_count(id_cryptoctx, &count); if (ret) goto cleanup; md_list = calloc(count + 1, sizeof(*md_list)); if (md_list == NULL) { ret = ENOMEM; goto cleanup; } for (i = 0; i < count; i++) { ret = get_matching_data(context, plg_cryptoctx, req_cryptoctx, id_cryptoctx->creds[i]->cert, &md_list[i]); if (ret) { pkiDebug("%s: crypto_cert_get_matching_data error %d, %s\n", __FUNCTION__, ret, error_message(ret)); goto cleanup; } } *md_out = md_list; md_list = NULL; cleanup: crypto_cert_free_matching_data_list(context, md_list); return ret; } /* * Set the certificate in idctx->creds[cred_index] as the selected certificate. */ krb5_error_code crypto_cert_select(krb5_context context, pkinit_identity_crypto_context idctx, size_t cred_index) { pkinit_cred_info ci = NULL; if (cred_index >= MAX_CREDS_ALLOWED || idctx->creds[cred_index] == NULL) return ENOENT; ci = idctx->creds[cred_index]; /* copy the selected cert into our id_cryptoctx */ if (idctx->my_certs != NULL) sk_X509_pop_free(idctx->my_certs, X509_free); idctx->my_certs = sk_X509_new_null(); sk_X509_push(idctx->my_certs, ci->cert); free(idctx->identity); /* hang on to the selected credential name */ if (ci->name != NULL) idctx->identity = strdup(ci->name); else idctx->identity = NULL; ci->cert = NULL; /* Don't free it twice */ idctx->cert_index = 0; if (idctx->pkcs11_method != 1) { idctx->my_key = ci->key; ci->key = NULL; /* Don't free it twice */ } #ifndef WITHOUT_PKCS11 else { idctx->cert_id = ci->cert_id; ci->cert_id = NULL; /* Don't free it twice */ idctx->cert_id_len = ci->cert_id_len; } #endif return 0; } /* * Choose the default certificate as "the chosen one" */ krb5_error_code crypto_cert_select_default(krb5_context context, pkinit_plg_crypto_context plg_cryptoctx, pkinit_req_crypto_context req_cryptoctx, pkinit_identity_crypto_context id_cryptoctx) { krb5_error_code retval; int cert_count; retval = crypto_cert_get_count(id_cryptoctx, &cert_count); if (retval) goto errout; if (cert_count != 1) { TRACE_PKINIT_NO_DEFAULT_CERT(context, cert_count); retval = EINVAL; goto errout; } /* copy the selected cert into our id_cryptoctx */ if (id_cryptoctx->my_certs != NULL) { sk_X509_pop_free(id_cryptoctx->my_certs, X509_free); } id_cryptoctx->my_certs = sk_X509_new_null(); sk_X509_push(id_cryptoctx->my_certs, id_cryptoctx->creds[0]->cert); id_cryptoctx->creds[0]->cert = NULL; /* Don't free it twice */ id_cryptoctx->cert_index = 0; /* hang on to the selected credential name */ if (id_cryptoctx->creds[0]->name != NULL) id_cryptoctx->identity = strdup(id_cryptoctx->creds[0]->name); else id_cryptoctx->identity = NULL; if (id_cryptoctx->pkcs11_method != 1) { id_cryptoctx->my_key = id_cryptoctx->creds[0]->key; id_cryptoctx->creds[0]->key = NULL; /* Don't free it twice */ } #ifndef WITHOUT_PKCS11 else { id_cryptoctx->cert_id = id_cryptoctx->creds[0]->cert_id; id_cryptoctx->creds[0]->cert_id = NULL; /* Don't free it twice */ id_cryptoctx->cert_id_len = id_cryptoctx->creds[0]->cert_id_len; } #endif retval = 0; errout: return retval; } static krb5_error_code load_cas_and_crls(krb5_context context, pkinit_plg_crypto_context plg_cryptoctx, pkinit_req_crypto_context req_cryptoctx, pkinit_identity_crypto_context id_cryptoctx, int catype, char *filename) { STACK_OF(X509_INFO) *sk = NULL; STACK_OF(X509) *ca_certs = NULL; STACK_OF(X509_CRL) *ca_crls = NULL; BIO *in = NULL; krb5_error_code retval = ENOMEM; int i = 0; /* If there isn't already a stack in the context, * create a temporary one now */ switch(catype) { case CATYPE_ANCHORS: if (id_cryptoctx->trustedCAs != NULL) ca_certs = id_cryptoctx->trustedCAs; else { ca_certs = sk_X509_new_null(); if (ca_certs == NULL) return ENOMEM; } break; case CATYPE_INTERMEDIATES: if (id_cryptoctx->intermediateCAs != NULL) ca_certs = id_cryptoctx->intermediateCAs; else { ca_certs = sk_X509_new_null(); if (ca_certs == NULL) return ENOMEM; } break; case CATYPE_CRLS: if (id_cryptoctx->revoked != NULL) ca_crls = id_cryptoctx->revoked; else { ca_crls = sk_X509_CRL_new_null(); if (ca_crls == NULL) return ENOMEM; } break; default: return ENOTSUP; } if (!(in = BIO_new_file(filename, "r"))) { retval = oerr(context, 0, _("Cannot open file '%s'"), filename); goto cleanup; } /* This loads from a file, a stack of x509/crl/pkey sets */ if ((sk = PEM_X509_INFO_read_bio(in, NULL, NULL, NULL)) == NULL) { pkiDebug("%s: error reading file '%s'\n", __FUNCTION__, filename); retval = oerr(context, 0, _("Cannot read file '%s'"), filename); goto cleanup; } /* scan over the stack created from loading the file contents, * weed out duplicates, and push new ones onto the return stack */ for (i = 0; i < sk_X509_INFO_num(sk); i++) { X509_INFO *xi = sk_X509_INFO_value(sk, i); if (xi != NULL && xi->x509 != NULL && catype != CATYPE_CRLS) { int j = 0, size = sk_X509_num(ca_certs), flag = 0; if (!size) { sk_X509_push(ca_certs, xi->x509); xi->x509 = NULL; continue; } for (j = 0; j < size; j++) { X509 *x = sk_X509_value(ca_certs, j); flag = X509_cmp(x, xi->x509); if (flag == 0) break; else continue; } if (flag != 0) { sk_X509_push(ca_certs, X509_dup(xi->x509)); } } else if (xi != NULL && xi->crl != NULL && catype == CATYPE_CRLS) { int j = 0, size = sk_X509_CRL_num(ca_crls), flag = 0; if (!size) { sk_X509_CRL_push(ca_crls, xi->crl); xi->crl = NULL; continue; } for (j = 0; j < size; j++) { X509_CRL *x = sk_X509_CRL_value(ca_crls, j); flag = X509_CRL_cmp(x, xi->crl); if (flag == 0) break; else continue; } if (flag != 0) { sk_X509_CRL_push(ca_crls, X509_CRL_dup(xi->crl)); } } } /* If we added something and there wasn't a stack in the * context before, add the temporary stack to the context. */ switch(catype) { case CATYPE_ANCHORS: if (sk_X509_num(ca_certs) == 0) { TRACE_PKINIT_NO_CA_ANCHOR(context, filename); if (id_cryptoctx->trustedCAs == NULL) sk_X509_free(ca_certs); } else { if (id_cryptoctx->trustedCAs == NULL) id_cryptoctx->trustedCAs = ca_certs; } break; case CATYPE_INTERMEDIATES: if (sk_X509_num(ca_certs) == 0) { TRACE_PKINIT_NO_CA_INTERMEDIATE(context, filename); if (id_cryptoctx->intermediateCAs == NULL) sk_X509_free(ca_certs); } else { if (id_cryptoctx->intermediateCAs == NULL) id_cryptoctx->intermediateCAs = ca_certs; } break; case CATYPE_CRLS: if (sk_X509_CRL_num(ca_crls) == 0) { TRACE_PKINIT_NO_CRL(context, filename); if (id_cryptoctx->revoked == NULL) sk_X509_CRL_free(ca_crls); } else { if (id_cryptoctx->revoked == NULL) id_cryptoctx->revoked = ca_crls; } break; default: /* Should have been caught above! */ retval = EINVAL; goto cleanup; break; } retval = 0; cleanup: if (in != NULL) BIO_free(in); if (sk != NULL) sk_X509_INFO_pop_free(sk, X509_INFO_free); return retval; } static krb5_error_code load_cas_and_crls_dir(krb5_context context, pkinit_plg_crypto_context plg_cryptoctx, pkinit_req_crypto_context req_cryptoctx, pkinit_identity_crypto_context id_cryptoctx, int catype, char *dirname) { krb5_error_code retval = EINVAL; DIR *d = NULL; struct dirent *dentry = NULL; char filename[1024]; if (dirname == NULL) return EINVAL; d = opendir(dirname); if (d == NULL) return ENOENT; while ((dentry = readdir(d))) { if (strlen(dirname) + strlen(dentry->d_name) + 2 > sizeof(filename)) { pkiDebug("%s: Path too long -- directory '%s' and file '%s'\n", __FUNCTION__, dirname, dentry->d_name); goto cleanup; } /* Ignore subdirectories and anything starting with a dot */ #ifdef DT_DIR if (dentry->d_type == DT_DIR) continue; #endif if (dentry->d_name[0] == '.') continue; snprintf(filename, sizeof(filename), "%s/%s", dirname, dentry->d_name); retval = load_cas_and_crls(context, plg_cryptoctx, req_cryptoctx, id_cryptoctx, catype, filename); if (retval) goto cleanup; } retval = 0; cleanup: if (d != NULL) closedir(d); return retval; } krb5_error_code crypto_load_cas_and_crls(krb5_context context, pkinit_plg_crypto_context plg_cryptoctx, pkinit_req_crypto_context req_cryptoctx, pkinit_identity_opts *idopts, pkinit_identity_crypto_context id_cryptoctx, int idtype, int catype, char *id) { switch (idtype) { case IDTYPE_FILE: TRACE_PKINIT_LOAD_FROM_FILE(context); return load_cas_and_crls(context, plg_cryptoctx, req_cryptoctx, id_cryptoctx, catype, id); break; case IDTYPE_DIR: TRACE_PKINIT_LOAD_FROM_DIR(context); return load_cas_and_crls_dir(context, plg_cryptoctx, req_cryptoctx, id_cryptoctx, catype, id); break; default: return ENOTSUP; break; } } static krb5_error_code create_identifiers_from_stack(STACK_OF(X509) *sk, krb5_external_principal_identifier *** ids) { int i = 0, sk_size = sk_X509_num(sk); krb5_external_principal_identifier **krb5_cas = NULL; X509 *x = NULL; X509_NAME *xn = NULL; unsigned char *p = NULL; int len = 0; PKCS7_ISSUER_AND_SERIAL *is = NULL; char buf[DN_BUF_LEN]; *ids = NULL; krb5_cas = calloc(sk_size + 1, sizeof(*krb5_cas)); if (krb5_cas == NULL) return ENOMEM; for (i = 0; i < sk_size; i++) { krb5_cas[i] = malloc(sizeof(krb5_external_principal_identifier)); x = sk_X509_value(sk, i); X509_NAME_oneline(X509_get_subject_name(x), buf, sizeof(buf)); pkiDebug("#%d cert= %s\n", i, buf); /* fill-in subjectName */ krb5_cas[i]->subjectName.magic = 0; krb5_cas[i]->subjectName.length = 0; krb5_cas[i]->subjectName.data = NULL; xn = X509_get_subject_name(x); len = i2d_X509_NAME(xn, NULL); if ((p = malloc((size_t) len)) == NULL) goto oom; krb5_cas[i]->subjectName.data = (char *)p; i2d_X509_NAME(xn, &p); krb5_cas[i]->subjectName.length = len; /* fill-in issuerAndSerialNumber */ krb5_cas[i]->issuerAndSerialNumber.length = 0; krb5_cas[i]->issuerAndSerialNumber.magic = 0; krb5_cas[i]->issuerAndSerialNumber.data = NULL; is = PKCS7_ISSUER_AND_SERIAL_new(); if (is == NULL) goto oom; X509_NAME_set(&is->issuer, X509_get_issuer_name(x)); ASN1_INTEGER_free(is->serial); is->serial = ASN1_INTEGER_dup(X509_get_serialNumber(x)); if (is->serial == NULL) goto oom; len = i2d_PKCS7_ISSUER_AND_SERIAL(is, NULL); p = malloc(len); if (p == NULL) goto oom; krb5_cas[i]->issuerAndSerialNumber.data = (char *)p; i2d_PKCS7_ISSUER_AND_SERIAL(is, &p); krb5_cas[i]->issuerAndSerialNumber.length = len; /* fill-in subjectKeyIdentifier */ krb5_cas[i]->subjectKeyIdentifier.length = 0; krb5_cas[i]->subjectKeyIdentifier.magic = 0; krb5_cas[i]->subjectKeyIdentifier.data = NULL; if (X509_get_ext_by_NID(x, NID_subject_key_identifier, -1) >= 0) { ASN1_OCTET_STRING *ikeyid; ikeyid = X509_get_ext_d2i(x, NID_subject_key_identifier, NULL, NULL); if (ikeyid != NULL) { len = i2d_ASN1_OCTET_STRING(ikeyid, NULL); p = malloc(len); if (p == NULL) goto oom; krb5_cas[i]->subjectKeyIdentifier.data = (char *)p; i2d_ASN1_OCTET_STRING(ikeyid, &p); krb5_cas[i]->subjectKeyIdentifier.length = len; ASN1_OCTET_STRING_free(ikeyid); } } PKCS7_ISSUER_AND_SERIAL_free(is); is = NULL; } *ids = krb5_cas; return 0; oom: free_krb5_external_principal_identifier(&krb5_cas); PKCS7_ISSUER_AND_SERIAL_free(is); return ENOMEM; } static krb5_error_code create_krb5_invalidCertificates(krb5_context context, pkinit_plg_crypto_context plg_cryptoctx, pkinit_req_crypto_context req_cryptoctx, pkinit_identity_crypto_context id_cryptoctx, krb5_external_principal_identifier *** ids) { krb5_error_code retval = ENOMEM; STACK_OF(X509) *sk = NULL; *ids = NULL; if (req_cryptoctx->received_cert == NULL) return KRB5KDC_ERR_PREAUTH_FAILED; sk = sk_X509_new_null(); if (sk == NULL) goto cleanup; sk_X509_push(sk, req_cryptoctx->received_cert); retval = create_identifiers_from_stack(sk, ids); sk_X509_free(sk); cleanup: return retval; } krb5_error_code create_krb5_supportedCMSTypes(krb5_context context, pkinit_plg_crypto_context plg_cryptoctx, pkinit_req_crypto_context req_cryptoctx, pkinit_identity_crypto_context id_cryptoctx, krb5_algorithm_identifier ***oids) { krb5_error_code retval = ENOMEM; krb5_algorithm_identifier **loids = NULL; krb5_data des3oid = {0, 8, "\x2A\x86\x48\x86\xF7\x0D\x03\x07" }; *oids = NULL; loids = malloc(2 * sizeof(krb5_algorithm_identifier *)); if (loids == NULL) goto cleanup; loids[1] = NULL; loids[0] = malloc(sizeof(krb5_algorithm_identifier)); if (loids[0] == NULL) { free(loids); goto cleanup; } retval = pkinit_copy_krb5_data(&loids[0]->algorithm, &des3oid); if (retval) { free(loids[0]); free(loids); goto cleanup; } loids[0]->parameters.length = 0; loids[0]->parameters.data = NULL; *oids = loids; retval = 0; cleanup: return retval; } krb5_error_code create_krb5_trustedCertifiers(krb5_context context, pkinit_plg_crypto_context plg_cryptoctx, pkinit_req_crypto_context req_cryptoctx, pkinit_identity_crypto_context id_cryptoctx, krb5_external_principal_identifier *** ids) { krb5_error_code retval = ENOMEM; STACK_OF(X509) *sk = id_cryptoctx->trustedCAs; *ids = NULL; if (id_cryptoctx->trustedCAs == NULL) return KRB5KDC_ERR_PREAUTH_FAILED; retval = create_identifiers_from_stack(sk, ids); return retval; } krb5_error_code create_issuerAndSerial(krb5_context context, pkinit_plg_crypto_context plg_cryptoctx, pkinit_req_crypto_context req_cryptoctx, pkinit_identity_crypto_context id_cryptoctx, unsigned char **out, unsigned int *out_len) { unsigned char *p = NULL; PKCS7_ISSUER_AND_SERIAL *is = NULL; int len = 0; krb5_error_code retval = ENOMEM; X509 *cert = req_cryptoctx->received_cert; *out = NULL; *out_len = 0; if (req_cryptoctx->received_cert == NULL) return 0; is = PKCS7_ISSUER_AND_SERIAL_new(); X509_NAME_set(&is->issuer, X509_get_issuer_name(cert)); ASN1_INTEGER_free(is->serial); is->serial = ASN1_INTEGER_dup(X509_get_serialNumber(cert)); len = i2d_PKCS7_ISSUER_AND_SERIAL(is, NULL); if ((p = *out = malloc((size_t) len)) == NULL) goto cleanup; i2d_PKCS7_ISSUER_AND_SERIAL(is, &p); *out_len = len; retval = 0; cleanup: X509_NAME_free(is->issuer); ASN1_INTEGER_free(is->serial); free(is); return retval; } static int pkcs7_decrypt(krb5_context context, pkinit_identity_crypto_context id_cryptoctx, PKCS7 *p7, BIO *data) { BIO *tmpmem = NULL; int retval = 0, i = 0; char buf[4096]; if(p7 == NULL) return 0; if(!PKCS7_type_is_enveloped(p7)) { pkiDebug("wrong pkcs7 content type\n"); return 0; } if(!(tmpmem = pkcs7_dataDecode(context, id_cryptoctx, p7))) { pkiDebug("unable to decrypt pkcs7 object\n"); return 0; } for(;;) { i = BIO_read(tmpmem, buf, sizeof(buf)); if (i <= 0) break; BIO_write(data, buf, i); BIO_free_all(tmpmem); return 1; } return retval; } krb5_error_code pkinit_process_td_trusted_certifiers( krb5_context context, pkinit_plg_crypto_context plg_cryptoctx, pkinit_req_crypto_context req_cryptoctx, pkinit_identity_crypto_context id_cryptoctx, krb5_external_principal_identifier **krb5_trusted_certifiers, int td_type) { krb5_error_code retval = ENOMEM; STACK_OF(X509_NAME) *sk_xn = NULL; X509_NAME *xn = NULL; PKCS7_ISSUER_AND_SERIAL *is = NULL; ASN1_OCTET_STRING *id = NULL; const unsigned char *p = NULL; char buf[DN_BUF_LEN]; int i = 0; if (td_type == TD_TRUSTED_CERTIFIERS) pkiDebug("received trusted certifiers\n"); else pkiDebug("received invalid certificate\n"); sk_xn = sk_X509_NAME_new_null(); while(krb5_trusted_certifiers[i] != NULL) { if (krb5_trusted_certifiers[i]->subjectName.data != NULL) { p = (unsigned char *)krb5_trusted_certifiers[i]->subjectName.data; xn = d2i_X509_NAME(NULL, &p, (int)krb5_trusted_certifiers[i]->subjectName.length); if (xn == NULL) goto cleanup; X509_NAME_oneline(xn, buf, sizeof(buf)); if (td_type == TD_TRUSTED_CERTIFIERS) pkiDebug("#%d cert = %s is trusted by kdc\n", i, buf); else pkiDebug("#%d cert = %s is invalid\n", i, buf); sk_X509_NAME_push(sk_xn, xn); } if (krb5_trusted_certifiers[i]->issuerAndSerialNumber.data != NULL) { p = (unsigned char *) krb5_trusted_certifiers[i]->issuerAndSerialNumber.data; is = d2i_PKCS7_ISSUER_AND_SERIAL(NULL, &p, (int)krb5_trusted_certifiers[i]->issuerAndSerialNumber.length); if (is == NULL) goto cleanup; X509_NAME_oneline(is->issuer, buf, sizeof(buf)); if (td_type == TD_TRUSTED_CERTIFIERS) pkiDebug("#%d issuer = %s serial = %ld is trusted bu kdc\n", i, buf, ASN1_INTEGER_get(is->serial)); else pkiDebug("#%d issuer = %s serial = %ld is invalid\n", i, buf, ASN1_INTEGER_get(is->serial)); PKCS7_ISSUER_AND_SERIAL_free(is); } if (krb5_trusted_certifiers[i]->subjectKeyIdentifier.data != NULL) { p = (unsigned char *) krb5_trusted_certifiers[i]->subjectKeyIdentifier.data; id = d2i_ASN1_OCTET_STRING(NULL, &p, (int)krb5_trusted_certifiers[i]->subjectKeyIdentifier.length); if (id == NULL) goto cleanup; /* XXX */ ASN1_OCTET_STRING_free(id); } i++; } /* XXX Since we not doing anything with received trusted certifiers * return an error. this is the place where we can pick a different * client certificate based on the information in td_trusted_certifiers */ retval = KRB5KDC_ERR_PREAUTH_FAILED; cleanup: if (sk_xn != NULL) sk_X509_NAME_pop_free(sk_xn, X509_NAME_free); return retval; } static BIO * pkcs7_dataDecode(krb5_context context, pkinit_identity_crypto_context id_cryptoctx, PKCS7 *p7) { unsigned int eklen=0, tkeylen=0; BIO *out=NULL,*etmp=NULL,*bio=NULL; unsigned char *ek=NULL, *tkey=NULL; ASN1_OCTET_STRING *data_body=NULL; const EVP_CIPHER *evp_cipher=NULL; EVP_CIPHER_CTX *evp_ctx=NULL; X509_ALGOR *enc_alg=NULL; STACK_OF(PKCS7_RECIP_INFO) *rsk=NULL; PKCS7_RECIP_INFO *ri=NULL; p7->state=PKCS7_S_HEADER; rsk=p7->d.enveloped->recipientinfo; enc_alg=p7->d.enveloped->enc_data->algorithm; data_body=p7->d.enveloped->enc_data->enc_data; evp_cipher=EVP_get_cipherbyobj(enc_alg->algorithm); if (evp_cipher == NULL) { PKCS7err(PKCS7_F_PKCS7_DATADECODE,PKCS7_R_UNSUPPORTED_CIPHER_TYPE); goto cleanup; } if ((etmp=BIO_new(BIO_f_cipher())) == NULL) { PKCS7err(PKCS7_F_PKCS7_DATADECODE,ERR_R_BIO_LIB); goto cleanup; } /* It was encrypted, we need to decrypt the secret key * with the private key */ /* RFC 4556 section 3.2.3.2 requires that there be exactly one * recipientInfo. */ if (sk_PKCS7_RECIP_INFO_num(rsk) != 1) { pkiDebug("invalid number of EnvelopedData RecipientInfos\n"); goto cleanup; } ri = sk_PKCS7_RECIP_INFO_value(rsk, 0); (void)pkinit_decode_data(context, id_cryptoctx, ASN1_STRING_get0_data(ri->enc_key), ASN1_STRING_length(ri->enc_key), &ek, &eklen); evp_ctx=NULL; BIO_get_cipher_ctx(etmp,&evp_ctx); if (EVP_CipherInit_ex(evp_ctx,evp_cipher,NULL,NULL,NULL,0) <= 0) goto cleanup; if (EVP_CIPHER_asn1_to_param(evp_ctx,enc_alg->parameter) < 0) goto cleanup; /* Generate a random symmetric key to avoid exposing timing data if RSA * decryption fails the padding check. */ tkeylen = EVP_CIPHER_CTX_key_length(evp_ctx); tkey = OPENSSL_malloc(tkeylen); if (tkey == NULL) goto cleanup; if (EVP_CIPHER_CTX_rand_key(evp_ctx, tkey) <= 0) goto cleanup; if (ek == NULL) { ek = tkey; eklen = tkeylen; tkey = NULL; } if (eklen != (unsigned)EVP_CIPHER_CTX_key_length(evp_ctx)) { /* Some S/MIME clients don't use the same key * and effective key length. The key length is * determined by the size of the decrypted RSA key. */ if (!EVP_CIPHER_CTX_set_key_length(evp_ctx, (int)eklen)) { ek = tkey; eklen = tkeylen; tkey = NULL; } } if (EVP_CipherInit_ex(evp_ctx,NULL,NULL,ek,NULL,0) <= 0) goto cleanup; if (out == NULL) out=etmp; else BIO_push(out,etmp); etmp=NULL; if (data_body->length > 0) bio = BIO_new_mem_buf(data_body->data, data_body->length); else { bio=BIO_new(BIO_s_mem()); BIO_set_mem_eof_return(bio,0); } BIO_push(out,bio); bio=NULL; if (0) { cleanup: if (out != NULL) BIO_free_all(out); if (etmp != NULL) BIO_free_all(etmp); if (bio != NULL) BIO_free_all(bio); out=NULL; } if (ek != NULL) { OPENSSL_cleanse(ek, eklen); OPENSSL_free(ek); } if (tkey != NULL) { OPENSSL_cleanse(tkey, tkeylen); OPENSSL_free(tkey); } return(out); } #ifdef DEBUG_DH static void print_dh(DH * dh, char *msg) { BIO *bio_err = NULL; bio_err = BIO_new(BIO_s_file()); BIO_set_fp(bio_err, stderr, BIO_NOCLOSE | BIO_FP_TEXT); if (msg) BIO_puts(bio_err, (const char *)msg); if (dh) DHparams_print(bio_err, dh); BIO_puts(bio_err, "private key: "); BN_print(bio_err, dh->priv_key); BIO_puts(bio_err, (const char *)"\n"); BIO_free(bio_err); } static void print_pubkey(BIGNUM * key, char *msg) { BIO *bio_err = NULL; bio_err = BIO_new(BIO_s_file()); BIO_set_fp(bio_err, stderr, BIO_NOCLOSE | BIO_FP_TEXT); if (msg) BIO_puts(bio_err, (const char *)msg); if (key) BN_print(bio_err, key); BIO_puts(bio_err, "\n"); BIO_free(bio_err); } #endif static char * pkinit_pkcs11_code_to_text(int err) { int i; static char uc[32]; for (i = 0; pkcs11_errstrings[i].text != NULL; i++) if (pkcs11_errstrings[i].code == err) break; if (pkcs11_errstrings[i].text != NULL) return (pkcs11_errstrings[i].text); snprintf(uc, sizeof(uc), _("unknown code 0x%x"), err); return (uc); } /* * Add an item to the pkinit_identity_crypto_context's list of deferred * identities. */ krb5_error_code crypto_set_deferred_id(krb5_context context, pkinit_identity_crypto_context id_cryptoctx, const char *identity, const char *password) { unsigned long ck_flags; ck_flags = pkinit_get_deferred_id_flags(id_cryptoctx->deferred_ids, identity); return pkinit_set_deferred_id(&id_cryptoctx->deferred_ids, identity, ck_flags, password); } /* * Retrieve a read-only copy of the pkinit_identity_crypto_context's list of * deferred identities, sure to be valid only until the next time someone calls * either pkinit_set_deferred_id() or crypto_set_deferred_id(). */ const pkinit_deferred_id * crypto_get_deferred_ids(krb5_context context, pkinit_identity_crypto_context id_cryptoctx) { pkinit_deferred_id *deferred; const pkinit_deferred_id *ret; deferred = id_cryptoctx->deferred_ids; ret = (const pkinit_deferred_id *)deferred; return ret; } /* Return the received certificate as DER-encoded data. */ krb5_error_code crypto_encode_der_cert(krb5_context context, pkinit_req_crypto_context reqctx, uint8_t **der_out, size_t *der_len) { int len; unsigned char *der, *p; *der_out = NULL; *der_len = 0; if (reqctx->received_cert == NULL) return EINVAL; p = NULL; len = i2d_X509(reqctx->received_cert, NULL); if (len <= 0) return EINVAL; p = der = malloc(len); if (der == NULL) return ENOMEM; if (i2d_X509(reqctx->received_cert, &p) <= 0) { free(der); return EINVAL; } *der_out = der; *der_len = len; return 0; } /* * Get the certificate matching data from the request certificate. */ krb5_error_code crypto_req_cert_matching_data(krb5_context context, pkinit_plg_crypto_context plgctx, pkinit_req_crypto_context reqctx, pkinit_cert_matching_data **md_out) { *md_out = NULL; if (reqctx == NULL || reqctx->received_cert == NULL) return ENOENT; return get_matching_data(context, plgctx, reqctx, reqctx->received_cert, md_out); }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_2834_0
crossvul-cpp_data_good_339_5
/* * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* Initially written by David Mattes <david.mattes@boeing.com> */ /* Support for multiple key containers by Lukas Wunner <lukas@wunner.de> */ #if HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <string.h> #include <stdio.h> #include "internal.h" #include "pkcs15.h" #define MANU_ID "Gemplus" #define APPLET_NAME "GemSAFE V1" #define DRIVER_SERIAL_NUMBER "v0.9" #define GEMSAFE_APP_PATH "3F001600" #define GEMSAFE_PATH "3F0016000004" /* Apparently, the Applet max read "quanta" is 248 bytes * Gemalto ClassicClient reads files in chunks of 238 bytes */ #define GEMSAFE_READ_QUANTUM 248 #define GEMSAFE_MAX_OBJLEN 28672 int sc_pkcs15emu_gemsafeV1_init_ex(sc_pkcs15_card_t *, struct sc_aid *,sc_pkcs15emu_opt_t *); static int sc_pkcs15emu_add_cert(sc_pkcs15_card_t *p15card, int type, int authority, const sc_path_t *path, const sc_pkcs15_id_t *id, const char *label, int obj_flags); static int sc_pkcs15emu_add_pin(sc_pkcs15_card_t *p15card, const sc_pkcs15_id_t *id, const char *label, const sc_path_t *path, int ref, int type, unsigned int min_length, unsigned int max_length, int flags, int tries_left, const char pad_char, int obj_flags); static int sc_pkcs15emu_add_prkey(sc_pkcs15_card_t *p15card, const sc_pkcs15_id_t *id, const char *label, int type, unsigned int modulus_length, int usage, const sc_path_t *path, int ref, const sc_pkcs15_id_t *auth_id, int obj_flags); typedef struct cdata_st { char *label; int authority; const char *path; size_t index; size_t count; const char *id; int obj_flags; } cdata; const unsigned int gemsafe_cert_max = 12; cdata gemsafe_cert[] = { {"DS certificate #1", 0, GEMSAFE_PATH, 0, 0, "45", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #2", 0, GEMSAFE_PATH, 0, 0, "46", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #3", 0, GEMSAFE_PATH, 0, 0, "47", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #4", 0, GEMSAFE_PATH, 0, 0, "48", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #5", 0, GEMSAFE_PATH, 0, 0, "49", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #6", 0, GEMSAFE_PATH, 0, 0, "50", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #7", 0, GEMSAFE_PATH, 0, 0, "51", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #8", 0, GEMSAFE_PATH, 0, 0, "52", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #9", 0, GEMSAFE_PATH, 0, 0, "53", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #10", 0, GEMSAFE_PATH, 0, 0, "54", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #11", 0, GEMSAFE_PATH, 0, 0, "55", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #12", 0, GEMSAFE_PATH, 0, 0, "56", SC_PKCS15_CO_FLAG_MODIFIABLE}, }; typedef struct pdata_st { const u8 atr[SC_MAX_ATR_SIZE]; const size_t atr_len; const char *id; const char *label; const char *path; const int ref; const int type; const unsigned int maxlen; const unsigned int minlen; const int flags; const int tries_left; const char pad_char; const int obj_flags; } pindata; const unsigned int gemsafe_pin_max = 2; const pindata gemsafe_pin[] = { /* ATR-specific PIN policies, first match found is used: */ { {0x3B, 0x7D, 0x96, 0x00, 0x00, 0x80, 0x31, 0x80, 0x65, 0xB0, 0x83, 0x11, 0x48, 0xC8, 0x83, 0x00, 0x90, 0x00}, 18, "01", "DS pin", GEMSAFE_PATH, 0x01, SC_PKCS15_PIN_TYPE_ASCII_NUMERIC, 8, 4, SC_PKCS15_PIN_FLAG_NEEDS_PADDING | SC_PKCS15_PIN_FLAG_LOCAL, 3, 0x00, SC_PKCS15_CO_FLAG_MODIFIABLE | SC_PKCS15_CO_FLAG_PRIVATE }, /* default PIN policy comes last: */ { { 0 }, 0, "01", "DS pin", GEMSAFE_PATH, 0x01, SC_PKCS15_PIN_TYPE_BCD, 16, 6, SC_PKCS15_PIN_FLAG_NEEDS_PADDING | SC_PKCS15_PIN_FLAG_LOCAL, 3, 0xFF, SC_PKCS15_CO_FLAG_MODIFIABLE | SC_PKCS15_CO_FLAG_PRIVATE } }; typedef struct prdata_st { const char *id; char *label; unsigned int modulus_len; int usage; const char *path; int ref; const char *auth_id; int obj_flags; } prdata; #define USAGE_NONREP SC_PKCS15_PRKEY_USAGE_NONREPUDIATION #define USAGE_KE SC_PKCS15_PRKEY_USAGE_ENCRYPT | \ SC_PKCS15_PRKEY_USAGE_DECRYPT | \ SC_PKCS15_PRKEY_USAGE_WRAP | \ SC_PKCS15_PRKEY_USAGE_UNWRAP #define USAGE_AUT SC_PKCS15_PRKEY_USAGE_ENCRYPT | \ SC_PKCS15_PRKEY_USAGE_DECRYPT | \ SC_PKCS15_PRKEY_USAGE_WRAP | \ SC_PKCS15_PRKEY_USAGE_UNWRAP | \ SC_PKCS15_PRKEY_USAGE_SIGN prdata gemsafe_prkeys[] = { { "45", "DS key #1", 1024, USAGE_AUT, GEMSAFE_PATH, 0x03, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "46", "DS key #2", 1024, USAGE_AUT, GEMSAFE_PATH, 0x04, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "47", "DS key #3", 1024, USAGE_AUT, GEMSAFE_PATH, 0x05, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "48", "DS key #4", 1024, USAGE_AUT, GEMSAFE_PATH, 0x06, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "49", "DS key #5", 1024, USAGE_AUT, GEMSAFE_PATH, 0x07, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "50", "DS key #6", 1024, USAGE_AUT, GEMSAFE_PATH, 0x08, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "51", "DS key #7", 1024, USAGE_AUT, GEMSAFE_PATH, 0x09, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "52", "DS key #8", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0a, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "53", "DS key #9", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0b, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "54", "DS key #10", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0c, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "55", "DS key #11", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0d, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "56", "DS key #12", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0e, "01", SC_PKCS15_CO_FLAG_PRIVATE}, }; static int gemsafe_get_cert_len(sc_card_t *card) { int r; u8 ibuf[GEMSAFE_MAX_OBJLEN]; u8 *iptr; struct sc_path path; struct sc_file *file; size_t objlen, certlen; unsigned int ind, i=0; sc_format_path(GEMSAFE_PATH, &path); r = sc_select_file(card, &path, &file); if (r != SC_SUCCESS || !file) return SC_ERROR_INTERNAL; /* Initial read */ r = sc_read_binary(card, 0, ibuf, GEMSAFE_READ_QUANTUM, 0); if (r < 0) return SC_ERROR_INTERNAL; /* Actual stored object size is encoded in first 2 bytes * (allocated EF space is much greater!) */ objlen = (((size_t) ibuf[0]) << 8) | ibuf[1]; sc_log(card->ctx, "Stored object is of size: %"SC_FORMAT_LEN_SIZE_T"u", objlen); if (objlen < 1 || objlen > GEMSAFE_MAX_OBJLEN) { sc_log(card->ctx, "Invalid object size: %"SC_FORMAT_LEN_SIZE_T"u", objlen); return SC_ERROR_INTERNAL; } /* It looks like the first thing in the block is a table of * which keys are allocated. The table is small and is in the * first 248 bytes. Example for a card with 10 key containers: * 01 f0 00 03 03 b0 00 03 <= 1st key unallocated * 01 f0 00 04 03 b0 00 04 <= 2nd key unallocated * 01 fe 14 00 05 03 b0 00 05 <= 3rd key allocated * 01 fe 14 01 06 03 b0 00 06 <= 4th key allocated * 01 f0 00 07 03 b0 00 07 <= 5th key unallocated * ... * 01 f0 00 0c 03 b0 00 0c <= 10th key unallocated * For allocated keys, the fourth byte seems to indicate the * default key and the fifth byte indicates the key_ref of * the private key. */ ind = 2; /* skip length */ while (ibuf[ind] == 0x01 && i < gemsafe_cert_max) { if (ibuf[ind+1] == 0xFE) { gemsafe_prkeys[i].ref = ibuf[ind+4]; sc_log(card->ctx, "Key container %d is allocated and uses key_ref %d", i+1, gemsafe_prkeys[i].ref); ind += 9; } else { gemsafe_prkeys[i].label = NULL; gemsafe_cert[i].label = NULL; sc_log(card->ctx, "Key container %d is unallocated", i+1); ind += 8; } i++; } /* Delete additional key containers from the data structures if * this card can't accommodate them. */ for (; i < gemsafe_cert_max; i++) { gemsafe_prkeys[i].label = NULL; gemsafe_cert[i].label = NULL; } /* Read entire file, then dissect in memory. * Gemalto ClassicClient seems to do it the same way. */ iptr = ibuf + GEMSAFE_READ_QUANTUM; while ((size_t)(iptr - ibuf) < objlen) { r = sc_read_binary(card, iptr - ibuf, iptr, MIN(GEMSAFE_READ_QUANTUM, objlen - (iptr - ibuf)), 0); if (r < 0) { sc_log(card->ctx, "Could not read cert object"); return SC_ERROR_INTERNAL; } iptr += GEMSAFE_READ_QUANTUM; } /* Search buffer for certificates, they start with 0x3082. */ i = 0; while (ind < objlen - 1) { if (ibuf[ind] == 0x30 && ibuf[ind+1] == 0x82) { /* Find next allocated key container */ while (i < gemsafe_cert_max && gemsafe_cert[i].label == NULL) i++; if (i == gemsafe_cert_max) { sc_log(card->ctx, "Warning: Found orphaned certificate at offset %d", ind); return SC_SUCCESS; } /* DER cert len is encoded this way */ if (ind+3 >= sizeof ibuf) return SC_ERROR_INVALID_DATA; certlen = ((((size_t) ibuf[ind+2]) << 8) | ibuf[ind+3]) + 4; sc_log(card->ctx, "Found certificate of key container %d at offset %d, len %"SC_FORMAT_LEN_SIZE_T"u", i+1, ind, certlen); gemsafe_cert[i].index = ind; gemsafe_cert[i].count = certlen; ind += certlen; i++; } else ind++; } /* Delete additional key containers from the data structures if * they're missing on the card. */ for (; i < gemsafe_cert_max; i++) { if (gemsafe_cert[i].label) { sc_log(card->ctx, "Warning: Certificate of key container %d is missing", i+1); gemsafe_prkeys[i].label = NULL; gemsafe_cert[i].label = NULL; } } return SC_SUCCESS; } static int gemsafe_detect_card( sc_pkcs15_card_t *p15card) { if (strcmp(p15card->card->name, "GemSAFE V1")) return SC_ERROR_WRONG_CARD; return SC_SUCCESS; } static int sc_pkcs15emu_gemsafeV1_init( sc_pkcs15_card_t *p15card) { int r; unsigned int i; struct sc_path path; struct sc_file *file = NULL; struct sc_card *card = p15card->card; struct sc_apdu apdu; u8 rbuf[SC_MAX_APDU_BUFFER_SIZE]; sc_log(p15card->card->ctx, "Setting pkcs15 parameters"); if (p15card->tokeninfo->label) free(p15card->tokeninfo->label); p15card->tokeninfo->label = malloc(strlen(APPLET_NAME) + 1); if (!p15card->tokeninfo->label) return SC_ERROR_INTERNAL; strcpy(p15card->tokeninfo->label, APPLET_NAME); if (p15card->tokeninfo->serial_number) free(p15card->tokeninfo->serial_number); p15card->tokeninfo->serial_number = malloc(strlen(DRIVER_SERIAL_NUMBER) + 1); if (!p15card->tokeninfo->serial_number) return SC_ERROR_INTERNAL; strcpy(p15card->tokeninfo->serial_number, DRIVER_SERIAL_NUMBER); /* the GemSAFE applet version number */ sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xca, 0xdf, 0x03); apdu.cla = 0x80; apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); /* Manual says Le=0x05, but should be 0x08 to return full version number */ apdu.le = 0x08; apdu.lc = 0; apdu.datalen = 0; r = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); if (apdu.sw1 != 0x90 || apdu.sw2 != 0x00) return SC_ERROR_INTERNAL; if (r != SC_SUCCESS) return SC_ERROR_INTERNAL; /* the manufacturer ID, in this case GemPlus */ if (p15card->tokeninfo->manufacturer_id) free(p15card->tokeninfo->manufacturer_id); p15card->tokeninfo->manufacturer_id = malloc(strlen(MANU_ID) + 1); if (!p15card->tokeninfo->manufacturer_id) return SC_ERROR_INTERNAL; strcpy(p15card->tokeninfo->manufacturer_id, MANU_ID); /* determine allocated key containers and length of certificates */ r = gemsafe_get_cert_len(card); if (r != SC_SUCCESS) return SC_ERROR_INTERNAL; /* set certs */ sc_log(p15card->card->ctx, "Setting certificates"); for (i = 0; i < gemsafe_cert_max; i++) { struct sc_pkcs15_id p15Id; struct sc_path path; if (gemsafe_cert[i].label == NULL) continue; sc_format_path(gemsafe_cert[i].path, &path); sc_pkcs15_format_id(gemsafe_cert[i].id, &p15Id); path.index = gemsafe_cert[i].index; path.count = gemsafe_cert[i].count; sc_pkcs15emu_add_cert(p15card, SC_PKCS15_TYPE_CERT_X509, gemsafe_cert[i].authority, &path, &p15Id, gemsafe_cert[i].label, gemsafe_cert[i].obj_flags); } /* set gemsafe_pin */ sc_log(p15card->card->ctx, "Setting PIN"); for (i=0; i < gemsafe_pin_max; i++) { struct sc_pkcs15_id p15Id; struct sc_path path; sc_pkcs15_format_id(gemsafe_pin[i].id, &p15Id); sc_format_path(gemsafe_pin[i].path, &path); if (gemsafe_pin[i].atr_len == 0 || (gemsafe_pin[i].atr_len == p15card->card->atr.len && memcmp(p15card->card->atr.value, gemsafe_pin[i].atr, p15card->card->atr.len) == 0)) { sc_pkcs15emu_add_pin(p15card, &p15Id, gemsafe_pin[i].label, &path, gemsafe_pin[i].ref, gemsafe_pin[i].type, gemsafe_pin[i].minlen, gemsafe_pin[i].maxlen, gemsafe_pin[i].flags, gemsafe_pin[i].tries_left, gemsafe_pin[i].pad_char, gemsafe_pin[i].obj_flags); break; } }; /* set private keys */ sc_log(p15card->card->ctx, "Setting private keys"); for (i = 0; i < gemsafe_cert_max; i++) { struct sc_pkcs15_id p15Id, authId, *pauthId; struct sc_path path; int key_ref = 0x03; if (gemsafe_prkeys[i].label == NULL) continue; sc_pkcs15_format_id(gemsafe_prkeys[i].id, &p15Id); if (gemsafe_prkeys[i].auth_id) { sc_pkcs15_format_id(gemsafe_prkeys[i].auth_id, &authId); pauthId = &authId; } else pauthId = NULL; sc_format_path(gemsafe_prkeys[i].path, &path); /* * The key ref may be different for different sites; * by adding flags=n where the low order 4 bits can be * the key ref we can force it. */ if ( p15card->card->flags & 0x0F) { key_ref = p15card->card->flags & 0x0F; sc_debug(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, "Overriding key_ref %d with %d\n", gemsafe_prkeys[i].ref, key_ref); } else key_ref = gemsafe_prkeys[i].ref; sc_pkcs15emu_add_prkey(p15card, &p15Id, gemsafe_prkeys[i].label, SC_PKCS15_TYPE_PRKEY_RSA, gemsafe_prkeys[i].modulus_len, gemsafe_prkeys[i].usage, &path, key_ref, pauthId, gemsafe_prkeys[i].obj_flags); } /* select the application DF */ sc_log(p15card->card->ctx, "Selecting application DF"); sc_format_path(GEMSAFE_APP_PATH, &path); r = sc_select_file(card, &path, &file); if (r != SC_SUCCESS || !file) return SC_ERROR_INTERNAL; /* set the application DF */ if (p15card->file_app) free(p15card->file_app); p15card->file_app = file; return SC_SUCCESS; } int sc_pkcs15emu_gemsafeV1_init_ex( sc_pkcs15_card_t *p15card, struct sc_aid *aid, sc_pkcs15emu_opt_t *opts) { if (opts && opts->flags & SC_PKCS15EMU_FLAGS_NO_CHECK) return sc_pkcs15emu_gemsafeV1_init(p15card); else { int r = gemsafe_detect_card(p15card); if (r) return SC_ERROR_WRONG_CARD; return sc_pkcs15emu_gemsafeV1_init(p15card); } } static sc_pkcs15_df_t * sc_pkcs15emu_get_df(sc_pkcs15_card_t *p15card, unsigned int type) { sc_pkcs15_df_t *df; sc_file_t *file; int created = 0; while (1) { for (df = p15card->df_list; df; df = df->next) { if (df->type == type) { if (created) df->enumerated = 1; return df; } } assert(created == 0); file = sc_file_new(); if (!file) return NULL; sc_format_path("11001101", &file->path); sc_pkcs15_add_df(p15card, type, &file->path); sc_file_free(file); created++; } } static int sc_pkcs15emu_add_object(sc_pkcs15_card_t *p15card, int type, const char *label, void *data, const sc_pkcs15_id_t *auth_id, int obj_flags) { sc_pkcs15_object_t *obj; int df_type; obj = calloc(1, sizeof(*obj)); obj->type = type; obj->data = data; if (label) strncpy(obj->label, label, sizeof(obj->label)-1); obj->flags = obj_flags; if (auth_id) obj->auth_id = *auth_id; switch (type & SC_PKCS15_TYPE_CLASS_MASK) { case SC_PKCS15_TYPE_AUTH: df_type = SC_PKCS15_AODF; break; case SC_PKCS15_TYPE_PRKEY: df_type = SC_PKCS15_PRKDF; break; case SC_PKCS15_TYPE_PUBKEY: df_type = SC_PKCS15_PUKDF; break; case SC_PKCS15_TYPE_CERT: df_type = SC_PKCS15_CDF; break; default: sc_log(p15card->card->ctx, "Unknown PKCS15 object type %d", type); free(obj); return SC_ERROR_INVALID_ARGUMENTS; } obj->df = sc_pkcs15emu_get_df(p15card, df_type); sc_pkcs15_add_object(p15card, obj); return 0; } static int sc_pkcs15emu_add_pin(sc_pkcs15_card_t *p15card, const sc_pkcs15_id_t *id, const char *label, const sc_path_t *path, int ref, int type, unsigned int min_length, unsigned int max_length, int flags, int tries_left, const char pad_char, int obj_flags) { sc_pkcs15_auth_info_t *info; info = calloc(1, sizeof(*info)); if (!info) LOG_FUNC_RETURN(p15card->card->ctx, SC_ERROR_OUT_OF_MEMORY); info->auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN; info->auth_method = SC_AC_CHV; info->auth_id = *id; info->attrs.pin.min_length = min_length; info->attrs.pin.max_length = max_length; info->attrs.pin.stored_length = max_length; info->attrs.pin.type = type; info->attrs.pin.reference = ref; info->attrs.pin.flags = flags; info->attrs.pin.pad_char = pad_char; info->tries_left = tries_left; info->logged_in = SC_PIN_STATE_UNKNOWN; if (path) info->path = *path; return sc_pkcs15emu_add_object(p15card, SC_PKCS15_TYPE_AUTH_PIN, label, info, NULL, obj_flags); } static int sc_pkcs15emu_add_cert(sc_pkcs15_card_t *p15card, int type, int authority, const sc_path_t *path, const sc_pkcs15_id_t *id, const char *label, int obj_flags) { sc_pkcs15_cert_info_t *info; info = calloc(1, sizeof(*info)); if (!info) { LOG_FUNC_RETURN(p15card->card->ctx, SC_ERROR_OUT_OF_MEMORY); } info->id = *id; info->authority = authority; if (path) info->path = *path; return sc_pkcs15emu_add_object(p15card, type, label, info, NULL, obj_flags); } static int sc_pkcs15emu_add_prkey(sc_pkcs15_card_t *p15card, const sc_pkcs15_id_t *id, const char *label, int type, unsigned int modulus_length, int usage, const sc_path_t *path, int ref, const sc_pkcs15_id_t *auth_id, int obj_flags) { sc_pkcs15_prkey_info_t *info; info = calloc(1, sizeof(*info)); if (!info) { LOG_FUNC_RETURN(p15card->card->ctx, SC_ERROR_OUT_OF_MEMORY); } info->id = *id; info->modulus_length = modulus_length; info->usage = usage; info->native = 1; info->access_flags = SC_PKCS15_PRKEY_ACCESS_SENSITIVE | SC_PKCS15_PRKEY_ACCESS_ALWAYSSENSITIVE | SC_PKCS15_PRKEY_ACCESS_NEVEREXTRACTABLE | SC_PKCS15_PRKEY_ACCESS_LOCAL; info->key_reference = ref; if (path) info->path = *path; return sc_pkcs15emu_add_object(p15card, type, label, info, auth_id, obj_flags); } /* SC_IMPLEMENT_DRIVER_VERSION("0.9.4") */
./CrossVul/dataset_final_sorted/CWE-119/c/good_339_5
crossvul-cpp_data_bad_4907_1
/* * linux/fs/proc/root.c * * Copyright (C) 1991, 1992 Linus Torvalds * * proc root directory handling functions */ #include <asm/uaccess.h> #include <linux/errno.h> #include <linux/time.h> #include <linux/proc_fs.h> #include <linux/stat.h> #include <linux/init.h> #include <linux/sched.h> #include <linux/module.h> #include <linux/bitops.h> #include <linux/user_namespace.h> #include <linux/mount.h> #include <linux/pid_namespace.h> #include <linux/parser.h> #include "internal.h" static int proc_test_super(struct super_block *sb, void *data) { return sb->s_fs_info == data; } static int proc_set_super(struct super_block *sb, void *data) { int err = set_anon_super(sb, NULL); if (!err) { struct pid_namespace *ns = (struct pid_namespace *)data; sb->s_fs_info = get_pid_ns(ns); } return err; } enum { Opt_gid, Opt_hidepid, Opt_err, }; static const match_table_t tokens = { {Opt_hidepid, "hidepid=%u"}, {Opt_gid, "gid=%u"}, {Opt_err, NULL}, }; static int proc_parse_options(char *options, struct pid_namespace *pid) { char *p; substring_t args[MAX_OPT_ARGS]; int option; if (!options) return 1; while ((p = strsep(&options, ",")) != NULL) { int token; if (!*p) continue; args[0].to = args[0].from = NULL; token = match_token(p, tokens, args); switch (token) { case Opt_gid: if (match_int(&args[0], &option)) return 0; pid->pid_gid = make_kgid(current_user_ns(), option); break; case Opt_hidepid: if (match_int(&args[0], &option)) return 0; if (option < 0 || option > 2) { pr_err("proc: hidepid value must be between 0 and 2.\n"); return 0; } pid->hide_pid = option; break; default: pr_err("proc: unrecognized mount option \"%s\" " "or missing value\n", p); return 0; } } return 1; } int proc_remount(struct super_block *sb, int *flags, char *data) { struct pid_namespace *pid = sb->s_fs_info; sync_filesystem(sb); return !proc_parse_options(data, pid); } static struct dentry *proc_mount(struct file_system_type *fs_type, int flags, const char *dev_name, void *data) { int err; struct super_block *sb; struct pid_namespace *ns; char *options; if (flags & MS_KERNMOUNT) { ns = (struct pid_namespace *)data; options = NULL; } else { ns = task_active_pid_ns(current); options = data; /* Does the mounter have privilege over the pid namespace? */ if (!ns_capable(ns->user_ns, CAP_SYS_ADMIN)) return ERR_PTR(-EPERM); } sb = sget(fs_type, proc_test_super, proc_set_super, flags, ns); if (IS_ERR(sb)) return ERR_CAST(sb); if (!proc_parse_options(options, ns)) { deactivate_locked_super(sb); return ERR_PTR(-EINVAL); } if (!sb->s_root) { err = proc_fill_super(sb); if (err) { deactivate_locked_super(sb); return ERR_PTR(err); } sb->s_flags |= MS_ACTIVE; /* User space would break if executables appear on proc */ sb->s_iflags |= SB_I_NOEXEC; } return dget(sb->s_root); } static void proc_kill_sb(struct super_block *sb) { struct pid_namespace *ns; ns = (struct pid_namespace *)sb->s_fs_info; if (ns->proc_self) dput(ns->proc_self); if (ns->proc_thread_self) dput(ns->proc_thread_self); kill_anon_super(sb); put_pid_ns(ns); } static struct file_system_type proc_fs_type = { .name = "proc", .mount = proc_mount, .kill_sb = proc_kill_sb, .fs_flags = FS_USERNS_VISIBLE | FS_USERNS_MOUNT, }; void __init proc_root_init(void) { int err; proc_init_inodecache(); err = register_filesystem(&proc_fs_type); if (err) return; proc_self_init(); proc_thread_self_init(); proc_symlink("mounts", NULL, "self/mounts"); proc_net_init(); #ifdef CONFIG_SYSVIPC proc_mkdir("sysvipc", NULL); #endif proc_mkdir("fs", NULL); proc_mkdir("driver", NULL); proc_create_mount_point("fs/nfsd"); /* somewhere for the nfsd filesystem to be mounted */ #if defined(CONFIG_SUN_OPENPROMFS) || defined(CONFIG_SUN_OPENPROMFS_MODULE) /* just give it a mountpoint */ proc_create_mount_point("openprom"); #endif proc_tty_init(); proc_mkdir("bus", NULL); proc_sys_init(); } static int proc_root_getattr(struct vfsmount *mnt, struct dentry *dentry, struct kstat *stat ) { generic_fillattr(d_inode(dentry), stat); stat->nlink = proc_root.nlink + nr_processes(); return 0; } static struct dentry *proc_root_lookup(struct inode * dir, struct dentry * dentry, unsigned int flags) { if (!proc_pid_lookup(dir, dentry, flags)) return NULL; return proc_lookup(dir, dentry, flags); } static int proc_root_readdir(struct file *file, struct dir_context *ctx) { if (ctx->pos < FIRST_PROCESS_ENTRY) { int error = proc_readdir(file, ctx); if (unlikely(error <= 0)) return error; ctx->pos = FIRST_PROCESS_ENTRY; } return proc_pid_readdir(file, ctx); } /* * The root /proc directory is special, as it has the * <pid> directories. Thus we don't use the generic * directory handling functions for that.. */ static const struct file_operations proc_root_operations = { .read = generic_read_dir, .iterate_shared = proc_root_readdir, .llseek = generic_file_llseek, }; /* * proc root can do almost nothing.. */ static const struct inode_operations proc_root_inode_operations = { .lookup = proc_root_lookup, .getattr = proc_root_getattr, }; /* * This is the root "inode" in the /proc tree.. */ struct proc_dir_entry proc_root = { .low_ino = PROC_ROOT_INO, .namelen = 5, .mode = S_IFDIR | S_IRUGO | S_IXUGO, .nlink = 2, .count = ATOMIC_INIT(1), .proc_iops = &proc_root_inode_operations, .proc_fops = &proc_root_operations, .parent = &proc_root, .subdir = RB_ROOT, .name = "/proc", }; int pid_ns_prepare_proc(struct pid_namespace *ns) { struct vfsmount *mnt; mnt = kern_mount_data(&proc_fs_type, ns); if (IS_ERR(mnt)) return PTR_ERR(mnt); ns->proc_mnt = mnt; return 0; } void pid_ns_release_proc(struct pid_namespace *ns) { kern_unmount(ns->proc_mnt); }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_4907_1
crossvul-cpp_data_good_2483_3
/* * Architecture-specific setup. * * Copyright (C) 1998-2001, 2003-2004 Hewlett-Packard Co * David Mosberger-Tang <davidm@hpl.hp.com> * Stephane Eranian <eranian@hpl.hp.com> * Copyright (C) 2000, 2004 Intel Corp * Rohit Seth <rohit.seth@intel.com> * Suresh Siddha <suresh.b.siddha@intel.com> * Gordon Jin <gordon.jin@intel.com> * Copyright (C) 1999 VA Linux Systems * Copyright (C) 1999 Walt Drummond <drummond@valinux.com> * * 12/26/04 S.Siddha, G.Jin, R.Seth * Add multi-threading and multi-core detection * 11/12/01 D.Mosberger Convert get_cpuinfo() to seq_file based show_cpuinfo(). * 04/04/00 D.Mosberger renamed cpu_initialized to cpu_online_map * 03/31/00 R.Seth cpu_initialized and current->processor fixes * 02/04/00 D.Mosberger some more get_cpuinfo fixes... * 02/01/00 R.Seth fixed get_cpuinfo for SMP * 01/07/99 S.Eranian added the support for command line argument * 06/24/99 W.Drummond added boot_cpu_data. * 05/28/05 Z. Menyhart Dynamic stride size for "flush_icache_range()" */ #include <linux/module.h> #include <linux/init.h> #include <linux/acpi.h> #include <linux/bootmem.h> #include <linux/console.h> #include <linux/delay.h> #include <linux/kernel.h> #include <linux/reboot.h> #include <linux/sched.h> #include <linux/seq_file.h> #include <linux/string.h> #include <linux/threads.h> #include <linux/screen_info.h> #include <linux/dmi.h> #include <linux/serial.h> #include <linux/serial_core.h> #include <linux/efi.h> #include <linux/initrd.h> #include <linux/pm.h> #include <linux/cpufreq.h> #include <linux/kexec.h> #include <linux/crash_dump.h> #include <asm/ia32.h> #include <asm/machvec.h> #include <asm/mca.h> #include <asm/meminit.h> #include <asm/page.h> #include <asm/patch.h> #include <asm/pgtable.h> #include <asm/processor.h> #include <asm/sal.h> #include <asm/sections.h> #include <asm/setup.h> #include <asm/smp.h> #include <asm/system.h> #include <asm/tlbflush.h> #include <asm/unistd.h> #include <asm/hpsim.h> #if defined(CONFIG_SMP) && (IA64_CPU_SIZE > PAGE_SIZE) # error "struct cpuinfo_ia64 too big!" #endif #ifdef CONFIG_SMP unsigned long __per_cpu_offset[NR_CPUS]; EXPORT_SYMBOL(__per_cpu_offset); #endif DEFINE_PER_CPU(struct cpuinfo_ia64, cpu_info); DEFINE_PER_CPU(unsigned long, local_per_cpu_offset); unsigned long ia64_cycles_per_usec; struct ia64_boot_param *ia64_boot_param; struct screen_info screen_info; unsigned long vga_console_iobase; unsigned long vga_console_membase; static struct resource data_resource = { .name = "Kernel data", .flags = IORESOURCE_BUSY | IORESOURCE_MEM }; static struct resource code_resource = { .name = "Kernel code", .flags = IORESOURCE_BUSY | IORESOURCE_MEM }; static struct resource bss_resource = { .name = "Kernel bss", .flags = IORESOURCE_BUSY | IORESOURCE_MEM }; unsigned long ia64_max_cacheline_size; int dma_get_cache_alignment(void) { return ia64_max_cacheline_size; } EXPORT_SYMBOL(dma_get_cache_alignment); unsigned long ia64_iobase; /* virtual address for I/O accesses */ EXPORT_SYMBOL(ia64_iobase); struct io_space io_space[MAX_IO_SPACES]; EXPORT_SYMBOL(io_space); unsigned int num_io_spaces; /* * "flush_icache_range()" needs to know what processor dependent stride size to use * when it makes i-cache(s) coherent with d-caches. */ #define I_CACHE_STRIDE_SHIFT 5 /* Safest way to go: 32 bytes by 32 bytes */ unsigned long ia64_i_cache_stride_shift = ~0; /* * The merge_mask variable needs to be set to (max(iommu_page_size(iommu)) - 1). This * mask specifies a mask of address bits that must be 0 in order for two buffers to be * mergeable by the I/O MMU (i.e., the end address of the first buffer and the start * address of the second buffer must be aligned to (merge_mask+1) in order to be * mergeable). By default, we assume there is no I/O MMU which can merge physically * discontiguous buffers, so we set the merge_mask to ~0UL, which corresponds to a iommu * page-size of 2^64. */ unsigned long ia64_max_iommu_merge_mask = ~0UL; EXPORT_SYMBOL(ia64_max_iommu_merge_mask); /* * We use a special marker for the end of memory and it uses the extra (+1) slot */ struct rsvd_region rsvd_region[IA64_MAX_RSVD_REGIONS + 1] __initdata; int num_rsvd_regions __initdata; /* * Filter incoming memory segments based on the primitive map created from the boot * parameters. Segments contained in the map are removed from the memory ranges. A * caller-specified function is called with the memory ranges that remain after filtering. * This routine does not assume the incoming segments are sorted. */ int __init filter_rsvd_memory (unsigned long start, unsigned long end, void *arg) { unsigned long range_start, range_end, prev_start; void (*func)(unsigned long, unsigned long, int); int i; #if IGNORE_PFN0 if (start == PAGE_OFFSET) { printk(KERN_WARNING "warning: skipping physical page 0\n"); start += PAGE_SIZE; if (start >= end) return 0; } #endif /* * lowest possible address(walker uses virtual) */ prev_start = PAGE_OFFSET; func = arg; for (i = 0; i < num_rsvd_regions; ++i) { range_start = max(start, prev_start); range_end = min(end, rsvd_region[i].start); if (range_start < range_end) call_pernode_memory(__pa(range_start), range_end - range_start, func); /* nothing more available in this segment */ if (range_end == end) return 0; prev_start = rsvd_region[i].end; } /* end of memory marker allows full processing inside loop body */ return 0; } /* * Similar to "filter_rsvd_memory()", but the reserved memory ranges * are not filtered out. */ int __init filter_memory(unsigned long start, unsigned long end, void *arg) { void (*func)(unsigned long, unsigned long, int); #if IGNORE_PFN0 if (start == PAGE_OFFSET) { printk(KERN_WARNING "warning: skipping physical page 0\n"); start += PAGE_SIZE; if (start >= end) return 0; } #endif func = arg; if (start < end) call_pernode_memory(__pa(start), end - start, func); return 0; } static void __init sort_regions (struct rsvd_region *rsvd_region, int max) { int j; /* simple bubble sorting */ while (max--) { for (j = 0; j < max; ++j) { if (rsvd_region[j].start > rsvd_region[j+1].start) { struct rsvd_region tmp; tmp = rsvd_region[j]; rsvd_region[j] = rsvd_region[j + 1]; rsvd_region[j + 1] = tmp; } } } } /* * Request address space for all standard resources */ static int __init register_memory(void) { code_resource.start = ia64_tpa(_text); code_resource.end = ia64_tpa(_etext) - 1; data_resource.start = ia64_tpa(_etext); data_resource.end = ia64_tpa(_edata) - 1; bss_resource.start = ia64_tpa(__bss_start); bss_resource.end = ia64_tpa(_end) - 1; efi_initialize_iomem_resources(&code_resource, &data_resource, &bss_resource); return 0; } __initcall(register_memory); #ifdef CONFIG_KEXEC /* * This function checks if the reserved crashkernel is allowed on the specific * IA64 machine flavour. Machines without an IO TLB use swiotlb and require * some memory below 4 GB (i.e. in 32 bit area), see the implementation of * lib/swiotlb.c. The hpzx1 architecture has an IO TLB but cannot use that * in kdump case. See the comment in sba_init() in sba_iommu.c. * * So, the only machvec that really supports loading the kdump kernel * over 4 GB is "sn2". */ static int __init check_crashkernel_memory(unsigned long pbase, size_t size) { if (ia64_platform_is("sn2") || ia64_platform_is("uv")) return 1; else return pbase < (1UL << 32); } static void __init setup_crashkernel(unsigned long total, int *n) { unsigned long long base = 0, size = 0; int ret; ret = parse_crashkernel(boot_command_line, total, &size, &base); if (ret == 0 && size > 0) { if (!base) { sort_regions(rsvd_region, *n); base = kdump_find_rsvd_region(size, rsvd_region, *n); } if (!check_crashkernel_memory(base, size)) { pr_warning("crashkernel: There would be kdump memory " "at %ld GB but this is unusable because it " "must\nbe below 4 GB. Change the memory " "configuration of the machine.\n", (unsigned long)(base >> 30)); return; } if (base != ~0UL) { printk(KERN_INFO "Reserving %ldMB of memory at %ldMB " "for crashkernel (System RAM: %ldMB)\n", (unsigned long)(size >> 20), (unsigned long)(base >> 20), (unsigned long)(total >> 20)); rsvd_region[*n].start = (unsigned long)__va(base); rsvd_region[*n].end = (unsigned long)__va(base + size); (*n)++; crashk_res.start = base; crashk_res.end = base + size - 1; } } efi_memmap_res.start = ia64_boot_param->efi_memmap; efi_memmap_res.end = efi_memmap_res.start + ia64_boot_param->efi_memmap_size; boot_param_res.start = __pa(ia64_boot_param); boot_param_res.end = boot_param_res.start + sizeof(*ia64_boot_param); } #else static inline void __init setup_crashkernel(unsigned long total, int *n) {} #endif /** * reserve_memory - setup reserved memory areas * * Setup the reserved memory areas set aside for the boot parameters, * initrd, etc. There are currently %IA64_MAX_RSVD_REGIONS defined, * see include/asm-ia64/meminit.h if you need to define more. */ void __init reserve_memory (void) { int n = 0; unsigned long total_memory; /* * none of the entries in this table overlap */ rsvd_region[n].start = (unsigned long) ia64_boot_param; rsvd_region[n].end = rsvd_region[n].start + sizeof(*ia64_boot_param); n++; rsvd_region[n].start = (unsigned long) __va(ia64_boot_param->efi_memmap); rsvd_region[n].end = rsvd_region[n].start + ia64_boot_param->efi_memmap_size; n++; rsvd_region[n].start = (unsigned long) __va(ia64_boot_param->command_line); rsvd_region[n].end = (rsvd_region[n].start + strlen(__va(ia64_boot_param->command_line)) + 1); n++; rsvd_region[n].start = (unsigned long) ia64_imva((void *)KERNEL_START); rsvd_region[n].end = (unsigned long) ia64_imva(_end); n++; #ifdef CONFIG_BLK_DEV_INITRD if (ia64_boot_param->initrd_start) { rsvd_region[n].start = (unsigned long)__va(ia64_boot_param->initrd_start); rsvd_region[n].end = rsvd_region[n].start + ia64_boot_param->initrd_size; n++; } #endif #ifdef CONFIG_PROC_VMCORE if (reserve_elfcorehdr(&rsvd_region[n].start, &rsvd_region[n].end) == 0) n++; #endif total_memory = efi_memmap_init(&rsvd_region[n].start, &rsvd_region[n].end); n++; setup_crashkernel(total_memory, &n); /* end of memory marker */ rsvd_region[n].start = ~0UL; rsvd_region[n].end = ~0UL; n++; num_rsvd_regions = n; BUG_ON(IA64_MAX_RSVD_REGIONS + 1 < n); sort_regions(rsvd_region, num_rsvd_regions); } /** * find_initrd - get initrd parameters from the boot parameter structure * * Grab the initrd start and end from the boot parameter struct given us by * the boot loader. */ void __init find_initrd (void) { #ifdef CONFIG_BLK_DEV_INITRD if (ia64_boot_param->initrd_start) { initrd_start = (unsigned long)__va(ia64_boot_param->initrd_start); initrd_end = initrd_start+ia64_boot_param->initrd_size; printk(KERN_INFO "Initial ramdisk at: 0x%lx (%lu bytes)\n", initrd_start, ia64_boot_param->initrd_size); } #endif } static void __init io_port_init (void) { unsigned long phys_iobase; /* * Set `iobase' based on the EFI memory map or, failing that, the * value firmware left in ar.k0. * * Note that in ia32 mode, IN/OUT instructions use ar.k0 to compute * the port's virtual address, so ia32_load_state() loads it with a * user virtual address. But in ia64 mode, glibc uses the * *physical* address in ar.k0 to mmap the appropriate area from * /dev/mem, and the inX()/outX() interfaces use MMIO. In both * cases, user-mode can only use the legacy 0-64K I/O port space. * * ar.k0 is not involved in kernel I/O port accesses, which can use * any of the I/O port spaces and are done via MMIO using the * virtual mmio_base from the appropriate io_space[]. */ phys_iobase = efi_get_iobase(); if (!phys_iobase) { phys_iobase = ia64_get_kr(IA64_KR_IO_BASE); printk(KERN_INFO "No I/O port range found in EFI memory map, " "falling back to AR.KR0 (0x%lx)\n", phys_iobase); } ia64_iobase = (unsigned long) ioremap(phys_iobase, 0); ia64_set_kr(IA64_KR_IO_BASE, __pa(ia64_iobase)); /* setup legacy IO port space */ io_space[0].mmio_base = ia64_iobase; io_space[0].sparse = 1; num_io_spaces = 1; } /** * early_console_setup - setup debugging console * * Consoles started here require little enough setup that we can start using * them very early in the boot process, either right after the machine * vector initialization, or even before if the drivers can detect their hw. * * Returns non-zero if a console couldn't be setup. */ static inline int __init early_console_setup (char *cmdline) { int earlycons = 0; #ifdef CONFIG_SERIAL_SGI_L1_CONSOLE { extern int sn_serial_console_early_setup(void); if (!sn_serial_console_early_setup()) earlycons++; } #endif #ifdef CONFIG_EFI_PCDP if (!efi_setup_pcdp_console(cmdline)) earlycons++; #endif if (!simcons_register()) earlycons++; return (earlycons) ? 0 : -1; } static inline void mark_bsp_online (void) { #ifdef CONFIG_SMP /* If we register an early console, allow CPU 0 to printk */ cpu_set(smp_processor_id(), cpu_online_map); #endif } static __initdata int nomca; static __init int setup_nomca(char *s) { nomca = 1; return 0; } early_param("nomca", setup_nomca); #ifdef CONFIG_PROC_VMCORE /* elfcorehdr= specifies the location of elf core header * stored by the crashed kernel. */ static int __init parse_elfcorehdr(char *arg) { if (!arg) return -EINVAL; elfcorehdr_addr = memparse(arg, &arg); return 0; } early_param("elfcorehdr", parse_elfcorehdr); int __init reserve_elfcorehdr(unsigned long *start, unsigned long *end) { unsigned long length; /* We get the address using the kernel command line, * but the size is extracted from the EFI tables. * Both address and size are required for reservation * to work properly. */ if (elfcorehdr_addr >= ELFCORE_ADDR_MAX) return -EINVAL; if ((length = vmcore_find_descriptor_size(elfcorehdr_addr)) == 0) { elfcorehdr_addr = ELFCORE_ADDR_MAX; return -EINVAL; } *start = (unsigned long)__va(elfcorehdr_addr); *end = *start + length; return 0; } #endif /* CONFIG_PROC_VMCORE */ void __init setup_arch (char **cmdline_p) { unw_init(); ia64_patch_vtop((u64) __start___vtop_patchlist, (u64) __end___vtop_patchlist); *cmdline_p = __va(ia64_boot_param->command_line); strlcpy(boot_command_line, *cmdline_p, COMMAND_LINE_SIZE); efi_init(); io_port_init(); #ifdef CONFIG_IA64_GENERIC /* machvec needs to be parsed from the command line * before parse_early_param() is called to ensure * that ia64_mv is initialised before any command line * settings may cause console setup to occur */ machvec_init_from_cmdline(*cmdline_p); #endif parse_early_param(); if (early_console_setup(*cmdline_p) == 0) mark_bsp_online(); #ifdef CONFIG_ACPI /* Initialize the ACPI boot-time table parser */ acpi_table_init(); # ifdef CONFIG_ACPI_NUMA acpi_numa_init(); per_cpu_scan_finalize((cpus_weight(early_cpu_possible_map) == 0 ? 32 : cpus_weight(early_cpu_possible_map)), additional_cpus); # endif #else # ifdef CONFIG_SMP smp_build_cpu_map(); /* happens, e.g., with the Ski simulator */ # endif #endif /* CONFIG_APCI_BOOT */ find_memory(); /* process SAL system table: */ ia64_sal_init(__va(efi.sal_systab)); #ifdef CONFIG_ITANIUM ia64_patch_rse((u64) __start___rse_patchlist, (u64) __end___rse_patchlist); #else { u64 num_phys_stacked; if (ia64_pal_rse_info(&num_phys_stacked, 0) == 0 && num_phys_stacked > 96) ia64_patch_rse((u64) __start___rse_patchlist, (u64) __end___rse_patchlist); } #endif #ifdef CONFIG_SMP cpu_physical_id(0) = hard_smp_processor_id(); #endif cpu_init(); /* initialize the bootstrap CPU */ mmu_context_init(); /* initialize context_id bitmap */ check_sal_cache_flush(); #ifdef CONFIG_ACPI acpi_boot_init(); #endif #ifdef CONFIG_VT if (!conswitchp) { # if defined(CONFIG_DUMMY_CONSOLE) conswitchp = &dummy_con; # endif # if defined(CONFIG_VGA_CONSOLE) /* * Non-legacy systems may route legacy VGA MMIO range to system * memory. vga_con probes the MMIO hole, so memory looks like * a VGA device to it. The EFI memory map can tell us if it's * memory so we can avoid this problem. */ if (efi_mem_type(0xA0000) != EFI_CONVENTIONAL_MEMORY) conswitchp = &vga_con; # endif } #endif /* enable IA-64 Machine Check Abort Handling unless disabled */ if (!nomca) ia64_mca_init(); platform_setup(cmdline_p); paging_init(); } /* * Display cpu info for all CPUs. */ static int show_cpuinfo (struct seq_file *m, void *v) { #ifdef CONFIG_SMP # define lpj c->loops_per_jiffy # define cpunum c->cpu #else # define lpj loops_per_jiffy # define cpunum 0 #endif static struct { unsigned long mask; const char *feature_name; } feature_bits[] = { { 1UL << 0, "branchlong" }, { 1UL << 1, "spontaneous deferral"}, { 1UL << 2, "16-byte atomic ops" } }; char features[128], *cp, *sep; struct cpuinfo_ia64 *c = v; unsigned long mask; unsigned long proc_freq; int i, size; mask = c->features; /* build the feature string: */ memcpy(features, "standard", 9); cp = features; size = sizeof(features); sep = ""; for (i = 0; i < ARRAY_SIZE(feature_bits) && size > 1; ++i) { if (mask & feature_bits[i].mask) { cp += snprintf(cp, size, "%s%s", sep, feature_bits[i].feature_name), sep = ", "; mask &= ~feature_bits[i].mask; size = sizeof(features) - (cp - features); } } if (mask && size > 1) { /* print unknown features as a hex value */ snprintf(cp, size, "%s0x%lx", sep, mask); } proc_freq = cpufreq_quick_get(cpunum); if (!proc_freq) proc_freq = c->proc_freq / 1000; seq_printf(m, "processor : %d\n" "vendor : %s\n" "arch : IA-64\n" "family : %u\n" "model : %u\n" "model name : %s\n" "revision : %u\n" "archrev : %u\n" "features : %s\n" "cpu number : %lu\n" "cpu regs : %u\n" "cpu MHz : %lu.%03lu\n" "itc MHz : %lu.%06lu\n" "BogoMIPS : %lu.%02lu\n", cpunum, c->vendor, c->family, c->model, c->model_name, c->revision, c->archrev, features, c->ppn, c->number, proc_freq / 1000, proc_freq % 1000, c->itc_freq / 1000000, c->itc_freq % 1000000, lpj*HZ/500000, (lpj*HZ/5000) % 100); #ifdef CONFIG_SMP seq_printf(m, "siblings : %u\n", cpus_weight(cpu_core_map[cpunum])); if (c->socket_id != -1) seq_printf(m, "physical id: %u\n", c->socket_id); if (c->threads_per_core > 1 || c->cores_per_socket > 1) seq_printf(m, "core id : %u\n" "thread id : %u\n", c->core_id, c->thread_id); #endif seq_printf(m,"\n"); return 0; } static void * c_start (struct seq_file *m, loff_t *pos) { #ifdef CONFIG_SMP while (*pos < NR_CPUS && !cpu_isset(*pos, cpu_online_map)) ++*pos; #endif return *pos < NR_CPUS ? cpu_data(*pos) : NULL; } static void * c_next (struct seq_file *m, void *v, loff_t *pos) { ++*pos; return c_start(m, pos); } static void c_stop (struct seq_file *m, void *v) { } const struct seq_operations cpuinfo_op = { .start = c_start, .next = c_next, .stop = c_stop, .show = show_cpuinfo }; #define MAX_BRANDS 8 static char brandname[MAX_BRANDS][128]; static char * __cpuinit get_model_name(__u8 family, __u8 model) { static int overflow; char brand[128]; int i; memcpy(brand, "Unknown", 8); if (ia64_pal_get_brand_info(brand)) { if (family == 0x7) memcpy(brand, "Merced", 7); else if (family == 0x1f) switch (model) { case 0: memcpy(brand, "McKinley", 9); break; case 1: memcpy(brand, "Madison", 8); break; case 2: memcpy(brand, "Madison up to 9M cache", 23); break; } } for (i = 0; i < MAX_BRANDS; i++) if (strcmp(brandname[i], brand) == 0) return brandname[i]; for (i = 0; i < MAX_BRANDS; i++) if (brandname[i][0] == '\0') return strcpy(brandname[i], brand); if (overflow++ == 0) printk(KERN_ERR "%s: Table overflow. Some processor model information will be missing\n", __func__); return "Unknown"; } static void __cpuinit identify_cpu (struct cpuinfo_ia64 *c) { union { unsigned long bits[5]; struct { /* id 0 & 1: */ char vendor[16]; /* id 2 */ u64 ppn; /* processor serial number */ /* id 3: */ unsigned number : 8; unsigned revision : 8; unsigned model : 8; unsigned family : 8; unsigned archrev : 8; unsigned reserved : 24; /* id 4: */ u64 features; } field; } cpuid; pal_vm_info_1_u_t vm1; pal_vm_info_2_u_t vm2; pal_status_t status; unsigned long impl_va_msb = 50, phys_addr_size = 44; /* Itanium defaults */ int i; for (i = 0; i < 5; ++i) cpuid.bits[i] = ia64_get_cpuid(i); memcpy(c->vendor, cpuid.field.vendor, 16); #ifdef CONFIG_SMP c->cpu = smp_processor_id(); /* below default values will be overwritten by identify_siblings() * for Multi-Threading/Multi-Core capable CPUs */ c->threads_per_core = c->cores_per_socket = c->num_log = 1; c->socket_id = -1; identify_siblings(c); if (c->threads_per_core > smp_num_siblings) smp_num_siblings = c->threads_per_core; #endif c->ppn = cpuid.field.ppn; c->number = cpuid.field.number; c->revision = cpuid.field.revision; c->model = cpuid.field.model; c->family = cpuid.field.family; c->archrev = cpuid.field.archrev; c->features = cpuid.field.features; c->model_name = get_model_name(c->family, c->model); status = ia64_pal_vm_summary(&vm1, &vm2); if (status == PAL_STATUS_SUCCESS) { impl_va_msb = vm2.pal_vm_info_2_s.impl_va_msb; phys_addr_size = vm1.pal_vm_info_1_s.phys_add_size; } c->unimpl_va_mask = ~((7L<<61) | ((1L << (impl_va_msb + 1)) - 1)); c->unimpl_pa_mask = ~((1L<<63) | ((1L << phys_addr_size) - 1)); } void __init setup_per_cpu_areas (void) { /* start_kernel() requires this... */ #ifdef CONFIG_ACPI_HOTPLUG_CPU prefill_possible_map(); #endif } /* * Calculate the max. cache line size. * * In addition, the minimum of the i-cache stride sizes is calculated for * "flush_icache_range()". */ static void __cpuinit get_max_cacheline_size (void) { unsigned long line_size, max = 1; u64 l, levels, unique_caches; pal_cache_config_info_t cci; s64 status; status = ia64_pal_cache_summary(&levels, &unique_caches); if (status != 0) { printk(KERN_ERR "%s: ia64_pal_cache_summary() failed (status=%ld)\n", __func__, status); max = SMP_CACHE_BYTES; /* Safest setup for "flush_icache_range()" */ ia64_i_cache_stride_shift = I_CACHE_STRIDE_SHIFT; goto out; } for (l = 0; l < levels; ++l) { status = ia64_pal_cache_config_info(l, /* cache_type (data_or_unified)= */ 2, &cci); if (status != 0) { printk(KERN_ERR "%s: ia64_pal_cache_config_info(l=%lu, 2) failed (status=%ld)\n", __func__, l, status); max = SMP_CACHE_BYTES; /* The safest setup for "flush_icache_range()" */ cci.pcci_stride = I_CACHE_STRIDE_SHIFT; cci.pcci_unified = 1; } line_size = 1 << cci.pcci_line_size; if (line_size > max) max = line_size; if (!cci.pcci_unified) { status = ia64_pal_cache_config_info(l, /* cache_type (instruction)= */ 1, &cci); if (status != 0) { printk(KERN_ERR "%s: ia64_pal_cache_config_info(l=%lu, 1) failed (status=%ld)\n", __func__, l, status); /* The safest setup for "flush_icache_range()" */ cci.pcci_stride = I_CACHE_STRIDE_SHIFT; } } if (cci.pcci_stride < ia64_i_cache_stride_shift) ia64_i_cache_stride_shift = cci.pcci_stride; } out: if (max > ia64_max_cacheline_size) ia64_max_cacheline_size = max; } /* * cpu_init() initializes state that is per-CPU. This function acts * as a 'CPU state barrier', nothing should get across. */ void __cpuinit cpu_init (void) { extern void __cpuinit ia64_mmu_init (void *); static unsigned long max_num_phys_stacked = IA64_NUM_PHYS_STACK_REG; unsigned long num_phys_stacked; pal_vm_info_2_u_t vmi; unsigned int max_ctx; struct cpuinfo_ia64 *cpu_info; void *cpu_data; cpu_data = per_cpu_init(); #ifdef CONFIG_SMP /* * insert boot cpu into sibling and core mapes * (must be done after per_cpu area is setup) */ if (smp_processor_id() == 0) { cpu_set(0, per_cpu(cpu_sibling_map, 0)); cpu_set(0, cpu_core_map[0]); } #endif /* * We set ar.k3 so that assembly code in MCA handler can compute * physical addresses of per cpu variables with a simple: * phys = ar.k3 + &per_cpu_var */ ia64_set_kr(IA64_KR_PER_CPU_DATA, ia64_tpa(cpu_data) - (long) __per_cpu_start); get_max_cacheline_size(); /* * We can't pass "local_cpu_data" to identify_cpu() because we haven't called * ia64_mmu_init() yet. And we can't call ia64_mmu_init() first because it * depends on the data returned by identify_cpu(). We break the dependency by * accessing cpu_data() through the canonical per-CPU address. */ cpu_info = cpu_data + ((char *) &__ia64_per_cpu_var(cpu_info) - __per_cpu_start); identify_cpu(cpu_info); #ifdef CONFIG_MCKINLEY { # define FEATURE_SET 16 struct ia64_pal_retval iprv; if (cpu_info->family == 0x1f) { PAL_CALL_PHYS(iprv, PAL_PROC_GET_FEATURES, 0, FEATURE_SET, 0); if ((iprv.status == 0) && (iprv.v0 & 0x80) && (iprv.v2 & 0x80)) PAL_CALL_PHYS(iprv, PAL_PROC_SET_FEATURES, (iprv.v1 | 0x80), FEATURE_SET, 0); } } #endif /* Clear the stack memory reserved for pt_regs: */ memset(task_pt_regs(current), 0, sizeof(struct pt_regs)); ia64_set_kr(IA64_KR_FPU_OWNER, 0); /* * Initialize the page-table base register to a global * directory with all zeroes. This ensure that we can handle * TLB-misses to user address-space even before we created the * first user address-space. This may happen, e.g., due to * aggressive use of lfetch.fault. */ ia64_set_kr(IA64_KR_PT_BASE, __pa(ia64_imva(empty_zero_page))); /* * Initialize default control register to defer speculative faults except * for those arising from TLB misses, which are not deferred. The * kernel MUST NOT depend on a particular setting of these bits (in other words, * the kernel must have recovery code for all speculative accesses). Turn on * dcr.lc as per recommendation by the architecture team. Most IA-32 apps * shouldn't be affected by this (moral: keep your ia32 locks aligned and you'll * be fine). */ ia64_setreg(_IA64_REG_CR_DCR, ( IA64_DCR_DP | IA64_DCR_DK | IA64_DCR_DX | IA64_DCR_DR | IA64_DCR_DA | IA64_DCR_DD | IA64_DCR_LC)); atomic_inc(&init_mm.mm_count); current->active_mm = &init_mm; if (current->mm) BUG(); ia64_mmu_init(ia64_imva(cpu_data)); ia64_mca_cpu_init(ia64_imva(cpu_data)); #ifdef CONFIG_IA32_SUPPORT ia32_cpu_init(); #endif /* Clear ITC to eliminate sched_clock() overflows in human time. */ ia64_set_itc(0); /* disable all local interrupt sources: */ ia64_set_itv(1 << 16); ia64_set_lrr0(1 << 16); ia64_set_lrr1(1 << 16); ia64_setreg(_IA64_REG_CR_PMV, 1 << 16); ia64_setreg(_IA64_REG_CR_CMCV, 1 << 16); /* clear TPR & XTP to enable all interrupt classes: */ ia64_setreg(_IA64_REG_CR_TPR, 0); /* Clear any pending interrupts left by SAL/EFI */ while (ia64_get_ivr() != IA64_SPURIOUS_INT_VECTOR) ia64_eoi(); #ifdef CONFIG_SMP normal_xtp(); #endif /* set ia64_ctx.max_rid to the maximum RID that is supported by all CPUs: */ if (ia64_pal_vm_summary(NULL, &vmi) == 0) { max_ctx = (1U << (vmi.pal_vm_info_2_s.rid_size - 3)) - 1; setup_ptcg_sem(vmi.pal_vm_info_2_s.max_purges, NPTCG_FROM_PAL); } else { printk(KERN_WARNING "cpu_init: PAL VM summary failed, assuming 18 RID bits\n"); max_ctx = (1U << 15) - 1; /* use architected minimum */ } while (max_ctx < ia64_ctx.max_ctx) { unsigned int old = ia64_ctx.max_ctx; if (cmpxchg(&ia64_ctx.max_ctx, old, max_ctx) == old) break; } if (ia64_pal_rse_info(&num_phys_stacked, NULL) != 0) { printk(KERN_WARNING "cpu_init: PAL RSE info failed; assuming 96 physical " "stacked regs\n"); num_phys_stacked = 96; } /* size of physical stacked register partition plus 8 bytes: */ if (num_phys_stacked > max_num_phys_stacked) { ia64_patch_phys_stack_reg(num_phys_stacked*8 + 8); max_num_phys_stacked = num_phys_stacked; } platform_cpu_init(); pm_idle = default_idle; } void __init check_bugs (void) { ia64_patch_mckinley_e9((unsigned long) __start___mckinley_e9_bundles, (unsigned long) __end___mckinley_e9_bundles); } static int __init run_dmi_scan(void) { dmi_scan_machine(); return 0; } core_initcall(run_dmi_scan);
./CrossVul/dataset_final_sorted/CWE-119/c/good_2483_3
crossvul-cpp_data_good_4063_1
/* * hextile.c * * Routines to implement Hextile Encoding */ /* * 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. */ #include <rfb/rfb.h> static rfbBool sendHextiles8(rfbClientPtr cl, int x, int y, int w, int h); static rfbBool sendHextiles16(rfbClientPtr cl, int x, int y, int w, int h); static rfbBool sendHextiles32(rfbClientPtr cl, int x, int y, int w, int h); /* * rfbSendRectEncodingHextile - send a rectangle using hextile encoding. */ rfbBool rfbSendRectEncodingHextile(rfbClientPtr cl, int x, int y, int w, int h) { rfbFramebufferUpdateRectHeader rect; if (cl->ublen + sz_rfbFramebufferUpdateRectHeader > UPDATE_BUF_SIZE) { 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(rfbEncodingHextile); memcpy(&cl->updateBuf[cl->ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; rfbStatRecordEncodingSent(cl, rfbEncodingHextile, sz_rfbFramebufferUpdateRectHeader, sz_rfbFramebufferUpdateRectHeader + w * (cl->format.bitsPerPixel / 8) * h); switch (cl->format.bitsPerPixel) { case 8: return sendHextiles8(cl, x, y, w, h); case 16: return sendHextiles16(cl, x, y, w, h); case 32: return sendHextiles32(cl, x, y, w, h); } rfbLog("rfbSendRectEncodingHextile: bpp %d?\n", cl->format.bitsPerPixel); return FALSE; } #define PUT_PIXEL8(pix) (cl->updateBuf[cl->ublen++] = (pix)) #define PUT_PIXEL16(pix) (cl->updateBuf[cl->ublen++] = ((char*)&(pix))[0], \ cl->updateBuf[cl->ublen++] = ((char*)&(pix))[1]) #define PUT_PIXEL32(pix) (cl->updateBuf[cl->ublen++] = ((char*)&(pix))[0], \ cl->updateBuf[cl->ublen++] = ((char*)&(pix))[1], \ cl->updateBuf[cl->ublen++] = ((char*)&(pix))[2], \ cl->updateBuf[cl->ublen++] = ((char*)&(pix))[3]) #define DEFINE_SEND_HEXTILES(bpp) \ \ \ static rfbBool subrectEncode##bpp(rfbClientPtr cli, uint##bpp##_t *data, \ int w, int h, uint##bpp##_t bg, uint##bpp##_t fg, rfbBool mono);\ static void testColours##bpp(uint##bpp##_t *data, int size, rfbBool *mono, \ rfbBool *solid, uint##bpp##_t *bg, uint##bpp##_t *fg); \ \ \ /* \ * rfbSendHextiles \ */ \ \ static rfbBool \ sendHextiles##bpp(rfbClientPtr cl, int rx, int ry, int rw, int rh) { \ int x, y, w, h; \ int startUblen; \ char *fbptr; \ uint##bpp##_t bg = 0, fg = 0, newBg, newFg; \ rfbBool mono, solid; \ rfbBool validBg = FALSE; \ rfbBool validFg = FALSE; \ uint##bpp##_t clientPixelData[16*16*(bpp/8)]; \ \ for (y = ry; y < ry+rh; y += 16) { \ for (x = rx; x < rx+rw; x += 16) { \ w = h = 16; \ if (rx+rw - x < 16) \ w = rx+rw - x; \ if (ry+rh - y < 16) \ h = ry+rh - y; \ \ if ((cl->ublen + 1 + (2 + 16 * 16) * (bpp/8)) > \ UPDATE_BUF_SIZE) { \ if (!rfbSendUpdateBuf(cl)) \ return FALSE; \ } \ \ fbptr = (cl->scaledScreen->frameBuffer + (cl->scaledScreen->paddedWidthInBytes * y) \ + (x * (cl->scaledScreen->bitsPerPixel / 8))); \ \ (*cl->translateFn)(cl->translateLookupTable, &(cl->screen->serverFormat), \ &cl->format, fbptr, (char *)clientPixelData, \ cl->scaledScreen->paddedWidthInBytes, w, h); \ \ startUblen = cl->ublen; \ cl->updateBuf[startUblen] = 0; \ cl->ublen++; \ rfbStatRecordEncodingSentAdd(cl, rfbEncodingHextile, 1); \ \ testColours##bpp(clientPixelData, w * h, \ &mono, &solid, &newBg, &newFg); \ \ if (!validBg || (newBg != bg)) { \ validBg = TRUE; \ bg = newBg; \ cl->updateBuf[startUblen] |= rfbHextileBackgroundSpecified; \ PUT_PIXEL##bpp(bg); \ } \ \ if (solid) { \ continue; \ } \ \ cl->updateBuf[startUblen] |= rfbHextileAnySubrects; \ \ if (mono) { \ if (!validFg || (newFg != fg)) { \ validFg = TRUE; \ fg = newFg; \ cl->updateBuf[startUblen] |= rfbHextileForegroundSpecified; \ PUT_PIXEL##bpp(fg); \ } \ } else { \ validFg = FALSE; \ cl->updateBuf[startUblen] |= rfbHextileSubrectsColoured; \ } \ \ if (!subrectEncode##bpp(cl, clientPixelData, w, h, bg, fg, mono)) { \ /* encoding was too large, use raw */ \ validBg = FALSE; \ validFg = FALSE; \ cl->ublen = startUblen; \ cl->updateBuf[cl->ublen++] = rfbHextileRaw; \ (*cl->translateFn)(cl->translateLookupTable, \ &(cl->screen->serverFormat), &cl->format, fbptr, \ (char *)clientPixelData, \ cl->scaledScreen->paddedWidthInBytes, w, h); \ \ memcpy(&cl->updateBuf[cl->ublen], (char *)clientPixelData, \ w * h * (bpp/8)); \ \ cl->ublen += w * h * (bpp/8); \ rfbStatRecordEncodingSentAdd(cl, rfbEncodingHextile, \ w * h * (bpp/8)); \ } \ } \ } \ \ return TRUE; \ } \ \ \ static rfbBool \ subrectEncode##bpp(rfbClientPtr cl, uint##bpp##_t *data, int w, int h, \ uint##bpp##_t bg, uint##bpp##_t fg, rfbBool mono) \ { \ uint##bpp##_t cl2; \ int x,y; \ int i,j; \ int hx=0,hy,vx=0,vy; \ int hyflag; \ uint##bpp##_t *seg; \ uint##bpp##_t *line; \ int hw,hh,vw,vh; \ int thex,they,thew,theh; \ int numsubs = 0; \ int newLen; \ int nSubrectsUblen; \ \ nSubrectsUblen = cl->ublen; \ cl->ublen++; \ rfbStatRecordEncodingSentAdd(cl, rfbEncodingHextile, 1); \ \ for (y=0; y<h; y++) { \ line = data+(y*w); \ for (x=0; x<w; x++) { \ if (line[x] != bg) { \ cl2 = line[x]; \ hy = y-1; \ hyflag = 1; \ for (j=y; j<h; j++) { \ seg = data+(j*w); \ if (seg[x] != cl2) {break;} \ i = x; \ while ((i < w) && (seg[i] == cl2)) i += 1; \ i -= 1; \ if (j == y) vx = hx = i; \ if (i < vx) vx = i; \ if ((hyflag > 0) && (i >= hx)) { \ hy += 1; \ } else { \ hyflag = 0; \ } \ } \ vy = j-1; \ \ /* We now have two possible subrects: (x,y,hx,hy) and \ * (x,y,vx,vy). We'll choose the bigger of the two. \ */ \ hw = hx-x+1; \ hh = hy-y+1; \ vw = vx-x+1; \ vh = vy-y+1; \ \ thex = x; \ they = y; \ \ if ((hw*hh) > (vw*vh)) { \ thew = hw; \ theh = hh; \ } else { \ thew = vw; \ theh = vh; \ } \ \ if (mono) { \ newLen = cl->ublen - nSubrectsUblen + 2; \ } else { \ newLen = cl->ublen - nSubrectsUblen + bpp/8 + 2; \ } \ \ if (newLen > (w * h * (bpp/8))) \ return FALSE; \ \ numsubs += 1; \ \ if (!mono) PUT_PIXEL##bpp(cl2); \ \ cl->updateBuf[cl->ublen++] = rfbHextilePackXY(thex,they); \ cl->updateBuf[cl->ublen++] = rfbHextilePackWH(thew,theh); \ rfbStatRecordEncodingSentAdd(cl, rfbEncodingHextile, 1); \ \ /* \ * Now mark the subrect as done. \ */ \ for (j=they; j < (they+theh); j++) { \ for (i=thex; i < (thex+thew); i++) { \ data[j*w+i] = bg; \ } \ } \ } \ } \ } \ \ cl->updateBuf[nSubrectsUblen] = numsubs; \ \ return TRUE; \ } \ \ \ /* \ * testColours() tests if there are one (solid), two (mono) or more \ * colours in a tile and gets a reasonable guess at the best background \ * pixel, and the foreground pixel for mono. \ */ \ \ static void \ testColours##bpp(uint##bpp##_t *data, int size, rfbBool *mono, rfbBool *solid, \ uint##bpp##_t *bg, uint##bpp##_t *fg) { \ uint##bpp##_t colour1 = 0, colour2 = 0; \ int n1 = 0, n2 = 0; \ *mono = TRUE; \ *solid = TRUE; \ \ for (; size > 0; size--, data++) { \ \ if (n1 == 0) \ colour1 = *data; \ \ if (*data == colour1) { \ n1++; \ continue; \ } \ \ if (n2 == 0) { \ *solid = FALSE; \ colour2 = *data; \ } \ \ if (*data == colour2) { \ n2++; \ continue; \ } \ \ *mono = FALSE; \ break; \ } \ \ if (n1 > n2) { \ *bg = colour1; \ *fg = colour2; \ } else { \ *bg = colour2; \ *fg = colour1; \ } \ } DEFINE_SEND_HEXTILES(8) DEFINE_SEND_HEXTILES(16) DEFINE_SEND_HEXTILES(32)
./CrossVul/dataset_final_sorted/CWE-119/c/good_4063_1
crossvul-cpp_data_good_5727_1
/* $Id$ */ /* * Copyright (c) 1990-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. */ /* * convert a GIF file into a TIFF file. * based on Paul Haeberli's fromgif program which in turn is * based on a GIF file reader by Marcel J.E. Mol March 23 1989 * * if input is 320 by 200 pixel aspect is probably 1.2 * if input is 640 350 pixel aspect is probably 1.37 * */ #include "tif_config.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #ifdef HAVE_UNISTD_H # include <unistd.h> #endif #ifdef NEED_LIBPORT # include "libport.h" #endif #include "tiffio.h" #define GIFGAMMA (1.5) /* smaller makes output img brighter */ #define IMAX 0xffff /* max intensity value */ #define EXTRAFUDGE 128 /* some people write BAD .gif files */ #define streq(a,b) (strcmp(a,b) == 0) #define strneq(a,b,n) (strncmp(a,b,n) == 0) unsigned short gamtab[256]; void makegamtab(float gam) { int i; for(i=0; i<256; i++) gamtab[i] = (unsigned short) (IMAX*pow(i/255.0,gam)+0.5); } char* stuff[] = { "usage: gif2tiff [options] input.gif output.tif", "where options are:", " -r # make each strip have no more than # rows", "", " -c lzw[:opts] compress output with Lempel-Ziv & Welch encoding", " -c zip[:opts] compress output with deflate encoding", " -c packbits compress output with packbits encoding", " -c none use no compression algorithm on output", "", "LZW and deflate options:", " # set predictor value", "For example, -c lzw:2 to get LZW-encoded data with horizontal differencing", 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 COLSIZE 256 unsigned char *stackp; unsigned int prefix[4096]; unsigned char suffix[4096]; unsigned char stack[4096]; int datasize,codesize,codemask; /* Decoder working variables */ int clear,eoi; /* Special code values */ int avail, oldcode; FILE *infile; int global; /* Is there a global color map? */ int globalbits; /* Number of bits of global colors */ unsigned char globalmap[COLSIZE][3];/* RGB values for global color map */ unsigned char *raster; /* Decoded image data */ unsigned long width, height; unsigned short red[COLSIZE]; unsigned short green[COLSIZE]; unsigned short blue[COLSIZE]; char *filename, *imagename; static uint16 compression = COMPRESSION_PACKBITS; static uint16 predictor = 0; static uint32 rowsperstrip = (uint32) -1; static int processCompressOptions(char*); int convert(void); int checksignature(void); void readscreen(void); int readgifimage(char*); void readextension(void); int readraster(void); int process(int, unsigned char**); void initcolors(unsigned char [COLSIZE][3], int); void rasterize(int, char*); int main(int argc, char* argv[]) { extern int optind; extern char *optarg; int c, status; while ((c = getopt(argc, argv, "c:r:")) != -1) switch (c) { case 'c': /* compression scheme */ if (!processCompressOptions(optarg)) usage(); break; case 'r': /* rows/strip */ rowsperstrip = atoi(optarg); break; case '?': usage(); /*NOTREACHED*/ } if (argc - optind != 2) usage(); makegamtab(GIFGAMMA); filename = argv[optind]; imagename = argv[optind+1]; if ((infile = fopen(imagename, "rb")) != NULL) { int c; fclose(infile); printf("overwrite %s? ", imagename); fflush(stdout); c = getc(stdin); if (c != 'y' && c != 'Y') return (1); } if ((infile = fopen(filename, "rb")) == NULL) { perror(filename); return (1); } status = convert(); fclose(infile); return (status); } static int processCompressOptions(char* opt) { if (streq(opt, "none")) compression = COMPRESSION_NONE; else if (streq(opt, "packbits")) compression = COMPRESSION_PACKBITS; else if (strneq(opt, "lzw", 3)) { char* cp = strchr(opt, ':'); if (cp) predictor = atoi(cp+1); compression = COMPRESSION_LZW; } else if (strneq(opt, "zip", 3)) { char* cp = strchr(opt, ':'); if (cp) predictor = atoi(cp+1); compression = COMPRESSION_DEFLATE; } else return (0); return (1); } int convert(void) { int ch; char* mode = "w"; if (!checksignature()) return (-1); readscreen(); while ((ch = getc(infile)) != ';' && ch != EOF) { switch (ch) { case '\0': break; /* this kludge for non-standard files */ case ',': if (!readgifimage(mode)) return (-1); mode = "a"; /* subsequent images append */ break; case '!': readextension(); break; default: fprintf(stderr, "illegal GIF block type\n"); return (-1); } } return (0); } int checksignature(void) { char buf[6]; fread(buf,1,6,infile); if (strncmp(buf,"GIF",3)) { fprintf(stderr, "file is not a GIF file\n"); return 0; } if (strncmp(&buf[3],"87a",3)) { fprintf(stderr, "unknown GIF version number\n"); return 0; } return 1; } /* * readscreen - * Get information which is global to all the images stored * in the file */ void readscreen(void) { unsigned char buf[7]; fread(buf,1,7,infile); global = buf[4] & 0x80; if (global) { globalbits = (buf[4] & 0x07) + 1; fread(globalmap,3,((size_t)1)<<globalbits,infile); } } int readgifimage(char* mode) { unsigned char buf[9]; int local, interleaved; unsigned char localmap[256][3]; int localbits; int status; if (fread(buf, 1, 9, infile) == 0) { perror(filename); return (0); } width = buf[4] + (buf[5] << 8); height = buf[6] + (buf[7] << 8); local = buf[8] & 0x80; interleaved = buf[8] & 0x40; if (local == 0 && global == 0) { fprintf(stderr, "no colormap present for image\n"); return (0); } if ((raster = (unsigned char*) _TIFFmalloc(width*height+EXTRAFUDGE)) == NULL) { fprintf(stderr, "not enough memory for image\n"); return (0); } if (local) { localbits = (buf[8] & 0x7) + 1; fprintf(stderr, " local colors: %d\n", 1<<localbits); fread(localmap, 3, ((size_t)1)<<localbits, infile); initcolors(localmap, 1<<localbits); } else if (global) { initcolors(globalmap, 1<<globalbits); } if ((status = readraster())) rasterize(interleaved, mode); _TIFFfree(raster); return status; } /* * readextension - * Read a GIF extension block (and do nothing with it). * */ void readextension(void) { int count; char buf[255]; (void) getc(infile); while ((count = getc(infile))) fread(buf, 1, count, infile); } /* * readraster - * Decode a raster image * */ int readraster(void) { unsigned char *fill = raster; unsigned char buf[255]; register int bits=0; register unsigned long datum=0; register unsigned char *ch; register int count, code; int status = 1; datasize = getc(infile); if (datasize > 12) return 0; clear = 1 << datasize; eoi = clear + 1; avail = clear + 2; oldcode = -1; codesize = datasize + 1; codemask = (1 << codesize) - 1; for (code = 0; code < clear; code++) { prefix[code] = 0; suffix[code] = code; } stackp = stack; for (count = getc(infile); count > 0; count = getc(infile)) { fread(buf,1,count,infile); for (ch=buf; count-- > 0; ch++) { datum += (unsigned long) *ch << bits; bits += 8; while (bits >= codesize) { code = datum & codemask; datum >>= codesize; bits -= codesize; if (code == eoi) { /* This kludge put in */ goto exitloop; /* because some GIF files*/ } /* aren't standard */ if (!process(code, &fill)) { status = 0; goto exitloop; } } } if (fill >= raster + width*height) { fprintf(stderr, "raster full before eoi code\n"); break; } } exitloop: if (fill != raster + width*height) { fprintf(stderr, "warning: wrong rastersize: %ld bytes\n", (long) (fill-raster)); fprintf(stderr, " instead of %ld bytes\n", (long) width*height); } return status; } /* * process - * Process a compression code. "clear" resets the code table. * Otherwise make a new code table entry, and output the bytes * associated with the code. */ int process(register int code, unsigned char** fill) { int incode; static unsigned char firstchar; if (code == clear) { codesize = datasize + 1; codemask = (1 << codesize) - 1; avail = clear + 2; oldcode = -1; return 1; } if (oldcode == -1) { if (code >= clear) { fprintf(stderr, "bad input: code=%d is larger than clear=%d\n",code, clear); return 0; } *(*fill)++ = suffix[code]; firstchar = oldcode = code; return 1; } if (code > avail) { fprintf(stderr, "code %d too large for %d\n", code, avail); return 0; } incode = code; if (code == avail) { /* the first code is always < avail */ *stackp++ = firstchar; code = oldcode; } while (code > clear) { *stackp++ = suffix[code]; code = prefix[code]; } *stackp++ = firstchar = suffix[code]; prefix[avail] = oldcode; suffix[avail] = firstchar; avail++; if (((avail & codemask) == 0) && (avail < 4096)) { codesize++; codemask += avail; } oldcode = incode; do { *(*fill)++ = *--stackp; } while (stackp > stack); return 1; } /* * initcolors - * Convert a color map (local or global) to arrays with R, G and B * values. * */ void initcolors(unsigned char colormap[COLSIZE][3], int ncolors) { register int i; for (i = 0; i < ncolors; i++) { red[i] = gamtab[colormap[i][0]]; green[i] = gamtab[colormap[i][1]]; blue[i] = gamtab[colormap[i][2]]; } } void rasterize(int interleaved, char* mode) { register unsigned long row; unsigned char *newras; unsigned char *ras; TIFF *tif; tstrip_t strip; tsize_t stripsize; if ((newras = (unsigned char*) _TIFFmalloc(width*height+EXTRAFUDGE)) == NULL) { fprintf(stderr, "not enough memory for image\n"); return; } #define DRAWSEGMENT(offset, step) { \ for (row = offset; row < height; row += step) { \ _TIFFmemcpy(newras + row*width, ras, width);\ ras += width; \ } \ } ras = raster; if (interleaved) { DRAWSEGMENT(0, 8); DRAWSEGMENT(4, 8); DRAWSEGMENT(2, 4); DRAWSEGMENT(1, 2); } else DRAWSEGMENT(0, 1); #undef DRAWSEGMENT tif = TIFFOpen(imagename, mode); if (!tif) { TIFFError(imagename,"Can not open output image"); exit(-1); } TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, (uint32) width); TIFFSetField(tif, TIFFTAG_IMAGELENGTH, (uint32) height); TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_PALETTE); TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG); TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 1); TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 8); TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, rowsperstrip = TIFFDefaultStripSize(tif, rowsperstrip)); TIFFSetField(tif, TIFFTAG_COMPRESSION, compression); switch (compression) { case COMPRESSION_LZW: case COMPRESSION_DEFLATE: if (predictor != 0) TIFFSetField(tif, TIFFTAG_PREDICTOR, predictor); break; } TIFFSetField(tif, TIFFTAG_COLORMAP, red, green, blue); TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT); strip = 0; stripsize = TIFFStripSize(tif); for (row=0; row<height; row += rowsperstrip) { if (rowsperstrip > height-row) { rowsperstrip = height-row; stripsize = TIFFVStripSize(tif, rowsperstrip); } if (TIFFWriteEncodedStrip(tif, strip, newras+row*width, stripsize) < 0) break; strip++; } TIFFClose(tif); _TIFFfree(newras); } /* vim: set ts=8 sts=8 sw=8 noet: */ /* * Local Variables: * mode: c * c-basic-offset: 8 * fill-column: 78 * End: */
./CrossVul/dataset_final_sorted/CWE-119/c/good_5727_1
crossvul-cpp_data_good_255_0
/** * @file * Read/parse/write an NNTP config file of subscribed newsgroups * * @authors * Copyright (C) 1998 Brandon Long <blong@fiction.net> * Copyright (C) 1999 Andrej Gritsenko <andrej@lucky.net> * Copyright (C) 2000-2017 Vsevolod Volkov <vvv@mutt.org.ua> * * @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 newsrc Read/parse/write an NNTP config file of subscribed newsgroups * * Read/parse/write an NNTP config file of subscribed newsgroups */ #include "config.h" #include <dirent.h> #include <errno.h> #include <limits.h> #include <stdbool.h> #include <stdio.h> #include <string.h> #include <sys/stat.h> #include <time.h> #include <unistd.h> #include "mutt/mutt.h" #include "conn/conn.h" #include "mutt.h" #include "bcache.h" #include "context.h" #include "format_flags.h" #include "globals.h" #include "header.h" #include "mutt_account.h" #include "mutt_curses.h" #include "mutt_socket.h" #include "mutt_window.h" #include "mx.h" #include "nntp.h" #include "options.h" #include "protos.h" #include "sort.h" #include "url.h" #ifdef USE_HCACHE #include "hcache/hcache.h" #endif struct BodyCache; /** * nntp_data_find - Find NntpData for given newsgroup or add it * @param nserv NNTP server * @param group Newsgroup * @retval ptr NNTP data * @retval NULL Error */ static struct NntpData *nntp_data_find(struct NntpServer *nserv, const char *group) { struct NntpData *nntp_data = mutt_hash_find(nserv->groups_hash, group); if (nntp_data) return nntp_data; size_t len = strlen(group) + 1; /* create NntpData structure and add it to hash */ nntp_data = mutt_mem_calloc(1, sizeof(struct NntpData) + len); nntp_data->group = (char *) nntp_data + sizeof(struct NntpData); mutt_str_strfcpy(nntp_data->group, group, len); nntp_data->nserv = nserv; nntp_data->deleted = true; mutt_hash_insert(nserv->groups_hash, nntp_data->group, nntp_data); /* add NntpData to list */ if (nserv->groups_num >= nserv->groups_max) { nserv->groups_max *= 2; mutt_mem_realloc(&nserv->groups_list, nserv->groups_max * sizeof(nntp_data)); } nserv->groups_list[nserv->groups_num++] = nntp_data; return nntp_data; } /** * nntp_acache_free - Remove all temporarily cache files * @param nntp_data NNTP data */ void nntp_acache_free(struct NntpData *nntp_data) { for (int i = 0; i < NNTP_ACACHE_LEN; i++) { if (nntp_data->acache[i].path) { unlink(nntp_data->acache[i].path); FREE(&nntp_data->acache[i].path); } } } /** * nntp_data_free - Free NntpData, used to destroy hash elements * @param data NNTP data */ void nntp_data_free(void *data) { struct NntpData *nntp_data = data; if (!nntp_data) return; nntp_acache_free(nntp_data); mutt_bcache_close(&nntp_data->bcache); FREE(&nntp_data->newsrc_ent); FREE(&nntp_data->desc); FREE(&data); } /** * nntp_hash_destructor - Free our hash table data * @param type Type (UNUSED) * @param obj NNTP data * @param data Data (UNUSED) */ void nntp_hash_destructor(int type, void *obj, intptr_t data) { nntp_data_free(obj); } /** * nntp_newsrc_close - Unlock and close .newsrc file * @param nserv NNTP server */ void nntp_newsrc_close(struct NntpServer *nserv) { if (!nserv->newsrc_fp) return; mutt_debug(1, "Unlocking %s\n", nserv->newsrc_file); mutt_file_unlock(fileno(nserv->newsrc_fp)); mutt_file_fclose(&nserv->newsrc_fp); } /** * nntp_group_unread_stat - Count number of unread articles using .newsrc data * @param nntp_data NNTP data */ void nntp_group_unread_stat(struct NntpData *nntp_data) { nntp_data->unread = 0; if (nntp_data->last_message == 0 || nntp_data->first_message > nntp_data->last_message) return; nntp_data->unread = nntp_data->last_message - nntp_data->first_message + 1; for (unsigned int i = 0; i < nntp_data->newsrc_len; i++) { anum_t first = nntp_data->newsrc_ent[i].first; if (first < nntp_data->first_message) first = nntp_data->first_message; anum_t last = nntp_data->newsrc_ent[i].last; if (last > nntp_data->last_message) last = nntp_data->last_message; if (first <= last) nntp_data->unread -= last - first + 1; } } /** * nntp_newsrc_parse - Parse .newsrc file * @param nserv NNTP server * @retval 0 Not changed * @retval 1 Parsed * @retval -1 Error */ int nntp_newsrc_parse(struct NntpServer *nserv) { char *line = NULL; struct stat sb; if (nserv->newsrc_fp) { /* if we already have a handle, close it and reopen */ mutt_file_fclose(&nserv->newsrc_fp); } else { /* if file doesn't exist, create it */ nserv->newsrc_fp = mutt_file_fopen(nserv->newsrc_file, "a"); mutt_file_fclose(&nserv->newsrc_fp); } /* open .newsrc */ nserv->newsrc_fp = mutt_file_fopen(nserv->newsrc_file, "r"); if (!nserv->newsrc_fp) { mutt_perror(nserv->newsrc_file); return -1; } /* lock it */ mutt_debug(1, "Locking %s\n", nserv->newsrc_file); if (mutt_file_lock(fileno(nserv->newsrc_fp), 0, 1)) { mutt_file_fclose(&nserv->newsrc_fp); return -1; } if (stat(nserv->newsrc_file, &sb)) { mutt_perror(nserv->newsrc_file); nntp_newsrc_close(nserv); return -1; } if (nserv->size == sb.st_size && nserv->mtime == sb.st_mtime) return 0; nserv->size = sb.st_size; nserv->mtime = sb.st_mtime; nserv->newsrc_modified = true; mutt_debug(1, "Parsing %s\n", nserv->newsrc_file); /* .newsrc has been externally modified or hasn't been loaded yet */ for (unsigned int i = 0; i < nserv->groups_num; i++) { struct NntpData *nntp_data = nserv->groups_list[i]; if (!nntp_data) continue; nntp_data->subscribed = false; nntp_data->newsrc_len = 0; FREE(&nntp_data->newsrc_ent); } line = mutt_mem_malloc(sb.st_size + 1); while (sb.st_size && fgets(line, sb.st_size + 1, nserv->newsrc_fp)) { char *b = NULL, *h = NULL; unsigned int j = 1; bool subs = false; /* find end of newsgroup name */ char *p = strpbrk(line, ":!"); if (!p) continue; /* ":" - subscribed, "!" - unsubscribed */ if (*p == ':') subs = true; *p++ = '\0'; /* get newsgroup data */ struct NntpData *nntp_data = nntp_data_find(nserv, line); FREE(&nntp_data->newsrc_ent); /* count number of entries */ b = p; while (*b) if (*b++ == ',') j++; nntp_data->newsrc_ent = mutt_mem_calloc(j, sizeof(struct NewsrcEntry)); nntp_data->subscribed = subs; /* parse entries */ j = 0; while (p) { b = p; /* find end of entry */ p = strchr(p, ','); if (p) *p++ = '\0'; /* first-last or single number */ h = strchr(b, '-'); if (h) *h++ = '\0'; else h = b; if (sscanf(b, ANUM, &nntp_data->newsrc_ent[j].first) == 1 && sscanf(h, ANUM, &nntp_data->newsrc_ent[j].last) == 1) { j++; } } if (j == 0) { nntp_data->newsrc_ent[j].first = 1; nntp_data->newsrc_ent[j].last = 0; j++; } if (nntp_data->last_message == 0) nntp_data->last_message = nntp_data->newsrc_ent[j - 1].last; nntp_data->newsrc_len = j; mutt_mem_realloc(&nntp_data->newsrc_ent, j * sizeof(struct NewsrcEntry)); nntp_group_unread_stat(nntp_data); mutt_debug(2, "%s\n", nntp_data->group); } FREE(&line); return 1; } /** * nntp_newsrc_gen_entries - Generate array of .newsrc entries * @param ctx Mailbox */ void nntp_newsrc_gen_entries(struct Context *ctx) { struct NntpData *nntp_data = ctx->data; anum_t last = 0, first = 1; bool series; int save_sort = SORT_ORDER; unsigned int entries; if (Sort != SORT_ORDER) { save_sort = Sort; Sort = SORT_ORDER; mutt_sort_headers(ctx, 0); } entries = nntp_data->newsrc_len; if (!entries) { entries = 5; nntp_data->newsrc_ent = mutt_mem_calloc(entries, sizeof(struct NewsrcEntry)); } /* Set up to fake initial sequence from 1 to the article before the * first article in our list */ nntp_data->newsrc_len = 0; series = true; for (int i = 0; i < ctx->msgcount; i++) { /* search for first unread */ if (series) { /* We don't actually check sequential order, since we mark * "missing" entries as read/deleted */ last = NHDR(ctx->hdrs[i])->article_num; if (last >= nntp_data->first_message && !ctx->hdrs[i]->deleted && !ctx->hdrs[i]->read) { if (nntp_data->newsrc_len >= entries) { entries *= 2; mutt_mem_realloc(&nntp_data->newsrc_ent, entries * sizeof(struct NewsrcEntry)); } nntp_data->newsrc_ent[nntp_data->newsrc_len].first = first; nntp_data->newsrc_ent[nntp_data->newsrc_len].last = last - 1; nntp_data->newsrc_len++; series = false; } } /* search for first read */ else { if (ctx->hdrs[i]->deleted || ctx->hdrs[i]->read) { first = last + 1; series = true; } last = NHDR(ctx->hdrs[i])->article_num; } } if (series && first <= nntp_data->last_loaded) { if (nntp_data->newsrc_len >= entries) { entries++; mutt_mem_realloc(&nntp_data->newsrc_ent, entries * sizeof(struct NewsrcEntry)); } nntp_data->newsrc_ent[nntp_data->newsrc_len].first = first; nntp_data->newsrc_ent[nntp_data->newsrc_len].last = nntp_data->last_loaded; nntp_data->newsrc_len++; } mutt_mem_realloc(&nntp_data->newsrc_ent, nntp_data->newsrc_len * sizeof(struct NewsrcEntry)); if (save_sort != Sort) { Sort = save_sort; mutt_sort_headers(ctx, 0); } } /** * update_file - Update file with new contents * @param filename File to update * @param buf New context * @retval 0 Success * @retval -1 Failure */ static int update_file(char *filename, char *buf) { FILE *fp = NULL; char tmpfile[PATH_MAX]; int rc = -1; while (true) { snprintf(tmpfile, sizeof(tmpfile), "%s.tmp", filename); fp = mutt_file_fopen(tmpfile, "w"); if (!fp) { mutt_perror(tmpfile); *tmpfile = '\0'; break; } if (fputs(buf, fp) == EOF) { mutt_perror(tmpfile); break; } if (mutt_file_fclose(&fp) == EOF) { mutt_perror(tmpfile); fp = NULL; break; } fp = NULL; if (rename(tmpfile, filename) < 0) { mutt_perror(filename); break; } *tmpfile = '\0'; rc = 0; break; } if (fp) mutt_file_fclose(&fp); if (*tmpfile) unlink(tmpfile); return rc; } /** * nntp_newsrc_update - Update .newsrc file * @param nserv NNTP server * @retval 0 Success * @retval -1 Failure */ int nntp_newsrc_update(struct NntpServer *nserv) { char *buf = NULL; size_t buflen, off; int rc = -1; if (!nserv) return -1; buflen = 10 * LONG_STRING; buf = mutt_mem_calloc(1, buflen); off = 0; /* we will generate full newsrc here */ for (unsigned int i = 0; i < nserv->groups_num; i++) { struct NntpData *nntp_data = nserv->groups_list[i]; if (!nntp_data || !nntp_data->newsrc_ent) continue; /* write newsgroup name */ if (off + strlen(nntp_data->group) + 3 > buflen) { buflen *= 2; mutt_mem_realloc(&buf, buflen); } snprintf(buf + off, buflen - off, "%s%c ", nntp_data->group, nntp_data->subscribed ? ':' : '!'); off += strlen(buf + off); /* write entries */ for (unsigned int j = 0; j < nntp_data->newsrc_len; j++) { if (off + LONG_STRING > buflen) { buflen *= 2; mutt_mem_realloc(&buf, buflen); } if (j) buf[off++] = ','; if (nntp_data->newsrc_ent[j].first == nntp_data->newsrc_ent[j].last) snprintf(buf + off, buflen - off, "%u", nntp_data->newsrc_ent[j].first); else if (nntp_data->newsrc_ent[j].first < nntp_data->newsrc_ent[j].last) { snprintf(buf + off, buflen - off, "%u-%u", nntp_data->newsrc_ent[j].first, nntp_data->newsrc_ent[j].last); } off += strlen(buf + off); } buf[off++] = '\n'; } buf[off] = '\0'; /* newrc being fully rewritten */ mutt_debug(1, "Updating %s\n", nserv->newsrc_file); if (nserv->newsrc_file && update_file(nserv->newsrc_file, buf) == 0) { struct stat sb; rc = stat(nserv->newsrc_file, &sb); if (rc == 0) { nserv->size = sb.st_size; nserv->mtime = sb.st_mtime; } else { mutt_perror(nserv->newsrc_file); } } FREE(&buf); return rc; } /** * cache_expand - Make fully qualified cache file name * @param dst Buffer for filename * @param dstlen Length of buffer * @param acct Account * @param src Path to add to the URL */ static void cache_expand(char *dst, size_t dstlen, struct Account *acct, char *src) { char *c = NULL; char file[PATH_MAX]; /* server subdirectory */ if (acct) { struct Url url; mutt_account_tourl(acct, &url); url.path = src; url_tostring(&url, file, sizeof(file), U_PATH); } else mutt_str_strfcpy(file, src ? src : "", sizeof(file)); snprintf(dst, dstlen, "%s/%s", NewsCacheDir, file); /* remove trailing slash */ c = dst + strlen(dst) - 1; if (*c == '/') *c = '\0'; mutt_expand_path(dst, dstlen); mutt_encode_path(dst, dstlen, dst); } /** * nntp_expand_path - Make fully qualified url from newsgroup name * @param line String containing newsgroup name * @param len Length of string * @param acct Account to save result */ void nntp_expand_path(char *line, size_t len, struct Account *acct) { struct Url url; mutt_account_tourl(acct, &url); url.path = mutt_str_strdup(line); url_tostring(&url, line, len, 0); FREE(&url.path); } /** * nntp_add_group - Parse newsgroup * @param line String to parse * @param data NNTP data * @retval 0 Always */ int nntp_add_group(char *line, void *data) { struct NntpServer *nserv = data; struct NntpData *nntp_data = NULL; char group[LONG_STRING] = ""; char desc[HUGE_STRING] = ""; char mod; anum_t first, last; if (!nserv || !line) return 0; /* These sscanf limits must match the sizes of the group and desc arrays */ if (sscanf(line, "%1023s " ANUM " " ANUM " %c %8191[^\n]", group, &last, &first, &mod, desc) < 4) { mutt_debug(4, "Cannot parse server line: %s\n", line); return 0; } nntp_data = nntp_data_find(nserv, group); nntp_data->deleted = false; nntp_data->first_message = first; nntp_data->last_message = last; nntp_data->allowed = (mod == 'y') || (mod == 'm'); mutt_str_replace(&nntp_data->desc, desc); if (nntp_data->newsrc_ent || nntp_data->last_cached) nntp_group_unread_stat(nntp_data); else if (nntp_data->last_message && nntp_data->first_message <= nntp_data->last_message) nntp_data->unread = nntp_data->last_message - nntp_data->first_message + 1; else nntp_data->unread = 0; return 0; } /** * active_get_cache - Load list of all newsgroups from cache * @param nserv NNTP server * @retval 0 Success * @retval -1 Failure */ static int active_get_cache(struct NntpServer *nserv) { char buf[HUGE_STRING]; char file[PATH_MAX]; time_t t; cache_expand(file, sizeof(file), &nserv->conn->account, ".active"); mutt_debug(1, "Parsing %s\n", file); FILE *fp = mutt_file_fopen(file, "r"); if (!fp) return -1; if (fgets(buf, sizeof(buf), fp) == NULL || sscanf(buf, "%ld%s", &t, file) != 1 || t == 0) { mutt_file_fclose(&fp); return -1; } nserv->newgroups_time = t; mutt_message(_("Loading list of groups from cache...")); while (fgets(buf, sizeof(buf), fp)) nntp_add_group(buf, nserv); nntp_add_group(NULL, NULL); mutt_file_fclose(&fp); mutt_clear_error(); return 0; } /** * nntp_active_save_cache - Save list of all newsgroups to cache * @param nserv NNTP server * @retval 0 Success * @retval -1 Failure */ int nntp_active_save_cache(struct NntpServer *nserv) { char file[PATH_MAX]; char *buf = NULL; size_t buflen, off; int rc; if (!nserv->cacheable) return 0; buflen = 10 * LONG_STRING; buf = mutt_mem_calloc(1, buflen); snprintf(buf, buflen, "%lu\n", (unsigned long) nserv->newgroups_time); off = strlen(buf); for (unsigned int i = 0; i < nserv->groups_num; i++) { struct NntpData *nntp_data = nserv->groups_list[i]; if (!nntp_data || nntp_data->deleted) continue; if (off + strlen(nntp_data->group) + (nntp_data->desc ? strlen(nntp_data->desc) : 0) + 50 > buflen) { buflen *= 2; mutt_mem_realloc(&buf, buflen); } snprintf(buf + off, buflen - off, "%s %u %u %c%s%s\n", nntp_data->group, nntp_data->last_message, nntp_data->first_message, nntp_data->allowed ? 'y' : 'n', nntp_data->desc ? " " : "", nntp_data->desc ? nntp_data->desc : ""); off += strlen(buf + off); } cache_expand(file, sizeof(file), &nserv->conn->account, ".active"); mutt_debug(1, "Updating %s\n", file); rc = update_file(file, buf); FREE(&buf); return rc; } #ifdef USE_HCACHE /** * nntp_hcache_namer - Compose hcache file names * @param path Path of message * @param dest Buffer for filename * @param destlen Length of buffer * @retval num Characters written to buffer * * Used by mutt_hcache_open() to compose hcache file name */ static int nntp_hcache_namer(const char *path, char *dest, size_t destlen) { int count = snprintf(dest, destlen, "%s.hcache", path); /* Strip out any directories in the path */ char *first = strchr(dest, '/'); char *last = strrchr(dest, '/'); if (first && last && (last > first)) { memmove(first, last, strlen(last) + 1); count -= (last - first); } return count; } /** * nntp_hcache_open - Open newsgroup hcache * @param nntp_data NNTP data * @retval ptr Header cache * @retval NULL Error */ header_cache_t *nntp_hcache_open(struct NntpData *nntp_data) { struct Url url; char file[PATH_MAX]; if (!nntp_data->nserv || !nntp_data->nserv->cacheable || !nntp_data->nserv->conn || !nntp_data->group || !(nntp_data->newsrc_ent || nntp_data->subscribed || SaveUnsubscribed)) { return NULL; } mutt_account_tourl(&nntp_data->nserv->conn->account, &url); url.path = nntp_data->group; url_tostring(&url, file, sizeof(file), U_PATH); return mutt_hcache_open(NewsCacheDir, file, nntp_hcache_namer); } /** * nntp_hcache_update - Remove stale cached headers * @param nntp_data NNTP data * @param hc Header cache */ void nntp_hcache_update(struct NntpData *nntp_data, header_cache_t *hc) { char buf[16]; bool old = false; void *hdata = NULL; anum_t first = 0, last = 0; if (!hc) return; /* fetch previous values of first and last */ hdata = mutt_hcache_fetch_raw(hc, "index", 5); if (hdata) { mutt_debug(2, "mutt_hcache_fetch index: %s\n", (char *) hdata); if (sscanf(hdata, ANUM " " ANUM, &first, &last) == 2) { old = true; nntp_data->last_cached = last; /* clean removed headers from cache */ for (anum_t current = first; current <= last; current++) { if (current >= nntp_data->first_message && current <= nntp_data->last_message) continue; snprintf(buf, sizeof(buf), "%u", current); mutt_debug(2, "mutt_hcache_delete %s\n", buf); mutt_hcache_delete(hc, buf, strlen(buf)); } } mutt_hcache_free(hc, &hdata); } /* store current values of first and last */ if (!old || nntp_data->first_message != first || nntp_data->last_message != last) { snprintf(buf, sizeof(buf), "%u %u", nntp_data->first_message, nntp_data->last_message); mutt_debug(2, "mutt_hcache_store index: %s\n", buf); mutt_hcache_store_raw(hc, "index", 5, buf, strlen(buf)); } } #endif /** * nntp_bcache_delete - Remove bcache file * @param id Body cache ID * @param bcache Body cache * @param data NNTP data * @retval 0 Always */ static int nntp_bcache_delete(const char *id, struct BodyCache *bcache, void *data) { struct NntpData *nntp_data = data; anum_t anum; char c; if (!nntp_data || sscanf(id, ANUM "%c", &anum, &c) != 1 || anum < nntp_data->first_message || anum > nntp_data->last_message) { if (nntp_data) mutt_debug(2, "mutt_bcache_del %s\n", id); mutt_bcache_del(bcache, id); } return 0; } /** * nntp_bcache_update - Remove stale cached messages * @param nntp_data NNTP data */ void nntp_bcache_update(struct NntpData *nntp_data) { mutt_bcache_list(nntp_data->bcache, nntp_bcache_delete, nntp_data); } /** * nntp_delete_group_cache - Remove hcache and bcache of newsgroup * @param nntp_data NNTP data */ void nntp_delete_group_cache(struct NntpData *nntp_data) { if (!nntp_data || !nntp_data->nserv || !nntp_data->nserv->cacheable) return; #ifdef USE_HCACHE char file[PATH_MAX]; nntp_hcache_namer(nntp_data->group, file, sizeof(file)); cache_expand(file, sizeof(file), &nntp_data->nserv->conn->account, file); unlink(file); nntp_data->last_cached = 0; mutt_debug(2, "%s\n", file); #endif if (!nntp_data->bcache) { nntp_data->bcache = mutt_bcache_open(&nntp_data->nserv->conn->account, nntp_data->group); } if (nntp_data->bcache) { mutt_debug(2, "%s/*\n", nntp_data->group); mutt_bcache_list(nntp_data->bcache, nntp_bcache_delete, NULL); mutt_bcache_close(&nntp_data->bcache); } } /** * nntp_clear_cache - Clear the NNTP cache * @param nserv NNTP server * * Remove hcache and bcache of all unexistent and unsubscribed newsgroups */ void nntp_clear_cache(struct NntpServer *nserv) { char file[PATH_MAX]; char *fp = NULL; struct dirent *entry = NULL; DIR *dp = NULL; if (!nserv || !nserv->cacheable) return; cache_expand(file, sizeof(file), &nserv->conn->account, NULL); dp = opendir(file); if (dp) { mutt_str_strncat(file, sizeof(file), "/", 1); fp = file + strlen(file); while ((entry = readdir(dp))) { char *group = entry->d_name; struct stat sb; struct NntpData *nntp_data = NULL; struct NntpData nntp_tmp; if ((mutt_str_strcmp(group, ".") == 0) || (mutt_str_strcmp(group, "..") == 0)) continue; *fp = '\0'; mutt_str_strncat(file, sizeof(file), group, strlen(group)); if (stat(file, &sb)) continue; #ifdef USE_HCACHE if (S_ISREG(sb.st_mode)) { char *ext = group + strlen(group) - 7; if (strlen(group) < 8 || (mutt_str_strcmp(ext, ".hcache") != 0)) continue; *ext = '\0'; } else #endif if (!S_ISDIR(sb.st_mode)) continue; nntp_data = mutt_hash_find(nserv->groups_hash, group); if (!nntp_data) { nntp_data = &nntp_tmp; nntp_data->nserv = nserv; nntp_data->group = group; nntp_data->bcache = NULL; } else if (nntp_data->newsrc_ent || nntp_data->subscribed || SaveUnsubscribed) continue; nntp_delete_group_cache(nntp_data); if (S_ISDIR(sb.st_mode)) { rmdir(file); mutt_debug(2, "%s\n", file); } } closedir(dp); } } /** * nntp_format_str - Expand the newsrc filename * @param[out] buf Buffer in which to save string * @param[in] buflen Buffer length * @param[in] col Starting column * @param[in] cols Number of screen columns * @param[in] op printf-like operator, e.g. 't' * @param[in] src printf-like format string * @param[in] prec Field precision, e.g. "-3.4" * @param[in] if_str If condition is met, display this string * @param[in] else_str Otherwise, display this string * @param[in] data Pointer to the mailbox Context * @param[in] flags Format flags * @retval src (unchanged) * * nntp_format_str() is a callback function for mutt_expando_format(). * * | Expando | Description * |:--------|:-------------------------------------------------------- * | \%a | Account url * | \%p | Port * | \%P | Port if specified * | \%s | News server name * | \%S | Url schema * | \%u | Username */ const char *nntp_format_str(char *buf, size_t buflen, size_t col, int cols, char op, const char *src, const char *prec, const char *if_str, const char *else_str, unsigned long data, enum FormatFlag flags) { struct NntpServer *nserv = (struct NntpServer *) data; struct Account *acct = &nserv->conn->account; struct Url url; char fn[SHORT_STRING], fmt[SHORT_STRING], *p = NULL; switch (op) { case 'a': mutt_account_tourl(acct, &url); url_tostring(&url, fn, sizeof(fn), U_PATH); p = strchr(fn, '/'); if (p) *p = '\0'; snprintf(fmt, sizeof(fmt), "%%%ss", prec); snprintf(buf, buflen, fmt, fn); break; case 'p': snprintf(fmt, sizeof(fmt), "%%%su", prec); snprintf(buf, buflen, fmt, acct->port); break; case 'P': *buf = '\0'; if (acct->flags & MUTT_ACCT_PORT) { snprintf(fmt, sizeof(fmt), "%%%su", prec); snprintf(buf, buflen, fmt, acct->port); } break; case 's': strncpy(fn, acct->host, sizeof(fn) - 1); mutt_str_strlower(fn); snprintf(fmt, sizeof(fmt), "%%%ss", prec); snprintf(buf, buflen, fmt, fn); break; case 'S': mutt_account_tourl(acct, &url); url_tostring(&url, fn, sizeof(fn), U_PATH); p = strchr(fn, ':'); if (p) *p = '\0'; snprintf(fmt, sizeof(fmt), "%%%ss", prec); snprintf(buf, buflen, fmt, fn); break; case 'u': snprintf(fmt, sizeof(fmt), "%%%ss", prec); snprintf(buf, buflen, fmt, acct->user); break; } return src; } /** * nntp_select_server - Open a connection to an NNTP server * @param server Server URI * @param leave_lock Leave the server locked? * @retval ptr NNTP server * @retval NULL Error * * Automatically loads a newsrc into memory, if necessary. Checks the * size/mtime of a newsrc file, if it doesn't match, load again. Hmm, if a * system has broken mtimes, this might mean the file is reloaded every time, * which we'd have to fix. */ struct NntpServer *nntp_select_server(char *server, bool leave_lock) { char file[PATH_MAX]; #ifdef USE_HCACHE char *p = NULL; #endif int rc; struct Account acct; struct NntpServer *nserv = NULL; struct NntpData *nntp_data = NULL; struct Connection *conn = NULL; struct Url url; if (!server || !*server) { mutt_error(_("No news server defined!")); return NULL; } /* create account from news server url */ acct.flags = 0; acct.port = NNTP_PORT; acct.type = MUTT_ACCT_TYPE_NNTP; snprintf(file, sizeof(file), "%s%s", strstr(server, "://") ? "" : "news://", server); if (url_parse(&url, file) < 0 || (url.path && *url.path) || !(url.scheme == U_NNTP || url.scheme == U_NNTPS) || !url.host || mutt_account_fromurl(&acct, &url) < 0) { url_free(&url); mutt_error(_("%s is an invalid news server specification!"), server); return NULL; } if (url.scheme == U_NNTPS) { acct.flags |= MUTT_ACCT_SSL; acct.port = NNTP_SSL_PORT; } url_free(&url); /* find connection by account */ conn = mutt_conn_find(NULL, &acct); if (!conn) return NULL; if (!(conn->account.flags & MUTT_ACCT_USER) && acct.flags & MUTT_ACCT_USER) { conn->account.flags |= MUTT_ACCT_USER; conn->account.user[0] = '\0'; } /* news server already exists */ nserv = conn->data; if (nserv) { if (nserv->status == NNTP_BYE) nserv->status = NNTP_NONE; if (nntp_open_connection(nserv) < 0) return NULL; rc = nntp_newsrc_parse(nserv); if (rc < 0) return NULL; /* check for new newsgroups */ if (!leave_lock && nntp_check_new_groups(nserv) < 0) rc = -1; /* .newsrc has been externally modified */ if (rc > 0) nntp_clear_cache(nserv); if (rc < 0 || !leave_lock) nntp_newsrc_close(nserv); return (rc < 0) ? NULL : nserv; } /* new news server */ nserv = mutt_mem_calloc(1, sizeof(struct NntpServer)); nserv->conn = conn; nserv->groups_hash = mutt_hash_create(1009, 0); mutt_hash_set_destructor(nserv->groups_hash, nntp_hash_destructor, 0); nserv->groups_max = 16; nserv->groups_list = mutt_mem_malloc(nserv->groups_max * sizeof(nntp_data)); rc = nntp_open_connection(nserv); /* try to create cache directory and enable caching */ nserv->cacheable = false; if (rc >= 0 && NewsCacheDir && *NewsCacheDir) { cache_expand(file, sizeof(file), &conn->account, NULL); if (mutt_file_mkdir(file, S_IRWXU) < 0) { mutt_error(_("Can't create %s: %s."), file, strerror(errno)); } nserv->cacheable = true; } /* load .newsrc */ if (rc >= 0) { mutt_expando_format(file, sizeof(file), 0, MuttIndexWindow->cols, NONULL(Newsrc), nntp_format_str, (unsigned long) nserv, 0); mutt_expand_path(file, sizeof(file)); nserv->newsrc_file = mutt_str_strdup(file); rc = nntp_newsrc_parse(nserv); } if (rc >= 0) { /* try to load list of newsgroups from cache */ if (nserv->cacheable && active_get_cache(nserv) == 0) rc = nntp_check_new_groups(nserv); /* load list of newsgroups from server */ else rc = nntp_active_fetch(nserv, false); } if (rc >= 0) nntp_clear_cache(nserv); #ifdef USE_HCACHE /* check cache files */ if (rc >= 0 && nserv->cacheable) { struct dirent *entry = NULL; DIR *dp = opendir(file); if (dp) { while ((entry = readdir(dp))) { header_cache_t *hc = NULL; void *hdata = NULL; char *group = entry->d_name; p = group + strlen(group) - 7; if (strlen(group) < 8 || (strcmp(p, ".hcache") != 0)) continue; *p = '\0'; nntp_data = mutt_hash_find(nserv->groups_hash, group); if (!nntp_data) continue; hc = nntp_hcache_open(nntp_data); if (!hc) continue; /* fetch previous values of first and last */ hdata = mutt_hcache_fetch_raw(hc, "index", 5); if (hdata) { anum_t first, last; if (sscanf(hdata, ANUM " " ANUM, &first, &last) == 2) { if (nntp_data->deleted) { nntp_data->first_message = first; nntp_data->last_message = last; } if (last >= nntp_data->first_message && last <= nntp_data->last_message) { nntp_data->last_cached = last; mutt_debug(2, "%s last_cached=%u\n", nntp_data->group, last); } } mutt_hcache_free(hc, &hdata); } mutt_hcache_close(hc); } closedir(dp); } } #endif if (rc < 0 || !leave_lock) nntp_newsrc_close(nserv); if (rc < 0) { mutt_hash_destroy(&nserv->groups_hash); FREE(&nserv->groups_list); FREE(&nserv->newsrc_file); FREE(&nserv->authenticators); FREE(&nserv); mutt_socket_close(conn); mutt_socket_free(conn); return NULL; } conn->data = nserv; return nserv; } /** * nntp_article_status - Get status of articles from .newsrc * @param ctx Mailbox * @param hdr Email Header * @param group Newsgroup * @param anum Article number * * Full status flags are not supported by nntp, but we can fake some of them: * Read = a read message number is in the .newsrc * New = not read and not cached * Old = not read but cached */ void nntp_article_status(struct Context *ctx, struct Header *hdr, char *group, anum_t anum) { struct NntpData *nntp_data = ctx->data; if (group) nntp_data = mutt_hash_find(nntp_data->nserv->groups_hash, group); if (!nntp_data) return; for (unsigned int i = 0; i < nntp_data->newsrc_len; i++) { if ((anum >= nntp_data->newsrc_ent[i].first) && (anum <= nntp_data->newsrc_ent[i].last)) { /* can't use mutt_set_flag() because mx_update_context() didn't called yet */ hdr->read = true; return; } } /* article was not cached yet, it's new */ if (anum > nntp_data->last_cached) return; /* article isn't read but cached, it's old */ if (MarkOld) hdr->old = true; } /** * mutt_newsgroup_subscribe - Subscribe newsgroup * @param nserv NNTP server * @param group Newsgroup * @retval ptr NNTP data * @retval NULL Error */ struct NntpData *mutt_newsgroup_subscribe(struct NntpServer *nserv, char *group) { struct NntpData *nntp_data = NULL; if (!nserv || !nserv->groups_hash || !group || !*group) return NULL; nntp_data = nntp_data_find(nserv, group); nntp_data->subscribed = true; if (!nntp_data->newsrc_ent) { nntp_data->newsrc_ent = mutt_mem_calloc(1, sizeof(struct NewsrcEntry)); nntp_data->newsrc_len = 1; nntp_data->newsrc_ent[0].first = 1; nntp_data->newsrc_ent[0].last = 0; } return nntp_data; } /** * mutt_newsgroup_unsubscribe - Unsubscribe newsgroup * @param nserv NNTP server * @param group Newsgroup * @retval ptr NNTP data * @retval NULL Error */ struct NntpData *mutt_newsgroup_unsubscribe(struct NntpServer *nserv, char *group) { struct NntpData *nntp_data = NULL; if (!nserv || !nserv->groups_hash || !group || !*group) return NULL; nntp_data = mutt_hash_find(nserv->groups_hash, group); if (!nntp_data) return NULL; nntp_data->subscribed = false; if (!SaveUnsubscribed) { nntp_data->newsrc_len = 0; FREE(&nntp_data->newsrc_ent); } return nntp_data; } /** * mutt_newsgroup_catchup - Catchup newsgroup * @param nserv NNTP server * @param group Newsgroup * @retval ptr NNTP data * @retval NULL Error */ struct NntpData *mutt_newsgroup_catchup(struct NntpServer *nserv, char *group) { struct NntpData *nntp_data = NULL; if (!nserv || !nserv->groups_hash || !group || !*group) return NULL; nntp_data = mutt_hash_find(nserv->groups_hash, group); if (!nntp_data) return NULL; if (nntp_data->newsrc_ent) { mutt_mem_realloc(&nntp_data->newsrc_ent, sizeof(struct NewsrcEntry)); nntp_data->newsrc_len = 1; nntp_data->newsrc_ent[0].first = 1; nntp_data->newsrc_ent[0].last = nntp_data->last_message; } nntp_data->unread = 0; if (Context && Context->data == nntp_data) { for (unsigned int i = 0; i < Context->msgcount; i++) mutt_set_flag(Context, Context->hdrs[i], MUTT_READ, 1); } return nntp_data; } /** * mutt_newsgroup_uncatchup - Uncatchup newsgroup * @param nserv NNTP server * @param group Newsgroup * @retval ptr NNTP data * @retval NULL Error */ struct NntpData *mutt_newsgroup_uncatchup(struct NntpServer *nserv, char *group) { struct NntpData *nntp_data = NULL; if (!nserv || !nserv->groups_hash || !group || !*group) return NULL; nntp_data = mutt_hash_find(nserv->groups_hash, group); if (!nntp_data) return NULL; if (nntp_data->newsrc_ent) { mutt_mem_realloc(&nntp_data->newsrc_ent, sizeof(struct NewsrcEntry)); nntp_data->newsrc_len = 1; nntp_data->newsrc_ent[0].first = 1; nntp_data->newsrc_ent[0].last = nntp_data->first_message - 1; } if (Context && Context->data == nntp_data) { nntp_data->unread = Context->msgcount; for (unsigned int i = 0; i < Context->msgcount; i++) mutt_set_flag(Context, Context->hdrs[i], MUTT_READ, 0); } else { nntp_data->unread = nntp_data->last_message; if (nntp_data->newsrc_ent) nntp_data->unread -= nntp_data->newsrc_ent[0].last; } return nntp_data; } /** * nntp_buffy - Get first newsgroup with new messages * @param buf Buffer for result * @param len Length of buffer */ void nntp_buffy(char *buf, size_t len) { for (unsigned int i = 0; i < CurrentNewsSrv->groups_num; i++) { struct NntpData *nntp_data = CurrentNewsSrv->groups_list[i]; if (!nntp_data || !nntp_data->subscribed || !nntp_data->unread) continue; if (Context && Context->magic == MUTT_NNTP && (mutt_str_strcmp(nntp_data->group, ((struct NntpData *) Context->data)->group) == 0)) { unsigned int unread = 0; for (unsigned int j = 0; j < Context->msgcount; j++) if (!Context->hdrs[j]->read && !Context->hdrs[j]->deleted) unread++; if (!unread) continue; } mutt_str_strfcpy(buf, nntp_data->group, len); break; } }
./CrossVul/dataset_final_sorted/CWE-119/c/good_255_0
crossvul-cpp_data_bad_3020_1
/* * Copyright (c) 2014-2015 Hisilicon Limited. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/platform_device.h> #include <linux/of.h> #include <linux/of_address.h> #include <linux/of_platform.h> #include "hns_dsaf_ppe.h" void hns_ppe_set_tso_enable(struct hns_ppe_cb *ppe_cb, u32 value) { dsaf_set_dev_bit(ppe_cb, PPEV2_CFG_TSO_EN_REG, 0, !!value); } void hns_ppe_set_rss_key(struct hns_ppe_cb *ppe_cb, const u32 rss_key[HNS_PPEV2_RSS_KEY_NUM]) { u32 key_item; for (key_item = 0; key_item < HNS_PPEV2_RSS_KEY_NUM; key_item++) dsaf_write_dev(ppe_cb, PPEV2_RSS_KEY_REG + key_item * 0x4, rss_key[key_item]); } void hns_ppe_set_indir_table(struct hns_ppe_cb *ppe_cb, const u32 rss_tab[HNS_PPEV2_RSS_IND_TBL_SIZE]) { int i; int reg_value; for (i = 0; i < (HNS_PPEV2_RSS_IND_TBL_SIZE / 4); i++) { reg_value = dsaf_read_dev(ppe_cb, PPEV2_INDRECTION_TBL_REG + i * 0x4); dsaf_set_field(reg_value, PPEV2_CFG_RSS_TBL_4N0_M, PPEV2_CFG_RSS_TBL_4N0_S, rss_tab[i * 4 + 0] & 0x1F); dsaf_set_field(reg_value, PPEV2_CFG_RSS_TBL_4N1_M, PPEV2_CFG_RSS_TBL_4N1_S, rss_tab[i * 4 + 1] & 0x1F); dsaf_set_field(reg_value, PPEV2_CFG_RSS_TBL_4N2_M, PPEV2_CFG_RSS_TBL_4N2_S, rss_tab[i * 4 + 2] & 0x1F); dsaf_set_field(reg_value, PPEV2_CFG_RSS_TBL_4N3_M, PPEV2_CFG_RSS_TBL_4N3_S, rss_tab[i * 4 + 3] & 0x1F); dsaf_write_dev( ppe_cb, PPEV2_INDRECTION_TBL_REG + i * 0x4, reg_value); } } static void __iomem * hns_ppe_common_get_ioaddr(struct ppe_common_cb *ppe_common) { return ppe_common->dsaf_dev->ppe_base + PPE_COMMON_REG_OFFSET; } /** * hns_ppe_common_get_cfg - get ppe common config * @dsaf_dev: dasf device * comm_index: common index * retuen 0 - success , negative --fail */ int hns_ppe_common_get_cfg(struct dsaf_device *dsaf_dev, int comm_index) { struct ppe_common_cb *ppe_common; int ppe_num; if (!HNS_DSAF_IS_DEBUG(dsaf_dev)) ppe_num = HNS_PPE_SERVICE_NW_ENGINE_NUM; else ppe_num = HNS_PPE_DEBUG_NW_ENGINE_NUM; ppe_common = devm_kzalloc(dsaf_dev->dev, sizeof(*ppe_common) + ppe_num * sizeof(struct hns_ppe_cb), GFP_KERNEL); if (!ppe_common) return -ENOMEM; ppe_common->ppe_num = ppe_num; ppe_common->dsaf_dev = dsaf_dev; ppe_common->comm_index = comm_index; if (!HNS_DSAF_IS_DEBUG(dsaf_dev)) ppe_common->ppe_mode = PPE_COMMON_MODE_SERVICE; else ppe_common->ppe_mode = PPE_COMMON_MODE_DEBUG; ppe_common->dev = dsaf_dev->dev; ppe_common->io_base = hns_ppe_common_get_ioaddr(ppe_common); dsaf_dev->ppe_common[comm_index] = ppe_common; return 0; } void hns_ppe_common_free_cfg(struct dsaf_device *dsaf_dev, u32 comm_index) { dsaf_dev->ppe_common[comm_index] = NULL; } static void __iomem *hns_ppe_get_iobase(struct ppe_common_cb *ppe_common, int ppe_idx) { return ppe_common->dsaf_dev->ppe_base + ppe_idx * PPE_REG_OFFSET; } static void hns_ppe_get_cfg(struct ppe_common_cb *ppe_common) { u32 i; struct hns_ppe_cb *ppe_cb; u32 ppe_num = ppe_common->ppe_num; for (i = 0; i < ppe_num; i++) { ppe_cb = &ppe_common->ppe_cb[i]; ppe_cb->dev = ppe_common->dev; ppe_cb->next = NULL; ppe_cb->ppe_common_cb = ppe_common; ppe_cb->index = i; ppe_cb->io_base = hns_ppe_get_iobase(ppe_common, i); ppe_cb->virq = 0; } } static void hns_ppe_cnt_clr_ce(struct hns_ppe_cb *ppe_cb) { dsaf_set_dev_bit(ppe_cb, PPE_TNL_0_5_CNT_CLR_CE_REG, PPE_CNT_CLR_CE_B, 1); } static void hns_ppe_set_vlan_strip(struct hns_ppe_cb *ppe_cb, int en) { dsaf_write_dev(ppe_cb, PPEV2_VLAN_STRIP_EN_REG, en); } /** * hns_ppe_checksum_hw - set ppe checksum caculate * @ppe_device: ppe device * @value: value */ static void hns_ppe_checksum_hw(struct hns_ppe_cb *ppe_cb, u32 value) { dsaf_set_dev_field(ppe_cb, PPE_CFG_PRO_CHECK_EN_REG, 0xfffffff, 0, value); } static void hns_ppe_set_qid_mode(struct ppe_common_cb *ppe_common, enum ppe_qid_mode qid_mdoe) { dsaf_set_dev_field(ppe_common, PPE_COM_CFG_QID_MODE_REG, PPE_CFG_QID_MODE_CF_QID_MODE_M, PPE_CFG_QID_MODE_CF_QID_MODE_S, qid_mdoe); } /** * hns_ppe_set_qid - set ppe qid * @ppe_common: ppe common device * @qid: queue id */ static void hns_ppe_set_qid(struct ppe_common_cb *ppe_common, u32 qid) { u32 qid_mod = dsaf_read_dev(ppe_common, PPE_COM_CFG_QID_MODE_REG); if (!dsaf_get_field(qid_mod, PPE_CFG_QID_MODE_DEF_QID_M, PPE_CFG_QID_MODE_DEF_QID_S)) { dsaf_set_field(qid_mod, PPE_CFG_QID_MODE_DEF_QID_M, PPE_CFG_QID_MODE_DEF_QID_S, qid); dsaf_write_dev(ppe_common, PPE_COM_CFG_QID_MODE_REG, qid_mod); } } /** * hns_ppe_set_port_mode - set port mode * @ppe_device: ppe device * @mode: port mode */ static void hns_ppe_set_port_mode(struct hns_ppe_cb *ppe_cb, enum ppe_port_mode mode) { dsaf_write_dev(ppe_cb, PPE_CFG_XGE_MODE_REG, mode); } /** * hns_ppe_common_init_hw - init ppe common device * @ppe_common: ppe common device * * Return 0 on success, negative on failure */ static int hns_ppe_common_init_hw(struct ppe_common_cb *ppe_common) { enum ppe_qid_mode qid_mode; struct dsaf_device *dsaf_dev = ppe_common->dsaf_dev; enum dsaf_mode dsaf_mode = dsaf_dev->dsaf_mode; dsaf_dev->misc_op->ppe_comm_srst(dsaf_dev, 0); mdelay(100); dsaf_dev->misc_op->ppe_comm_srst(dsaf_dev, 1); mdelay(100); if (ppe_common->ppe_mode == PPE_COMMON_MODE_SERVICE) { switch (dsaf_mode) { case DSAF_MODE_ENABLE_FIX: case DSAF_MODE_DISABLE_FIX: qid_mode = PPE_QID_MODE0; hns_ppe_set_qid(ppe_common, 0); break; case DSAF_MODE_ENABLE_0VM: case DSAF_MODE_DISABLE_2PORT_64VM: qid_mode = PPE_QID_MODE3; break; case DSAF_MODE_ENABLE_8VM: case DSAF_MODE_DISABLE_2PORT_16VM: qid_mode = PPE_QID_MODE4; break; case DSAF_MODE_ENABLE_16VM: case DSAF_MODE_DISABLE_6PORT_0VM: qid_mode = PPE_QID_MODE5; break; case DSAF_MODE_ENABLE_32VM: case DSAF_MODE_DISABLE_6PORT_16VM: qid_mode = PPE_QID_MODE2; break; case DSAF_MODE_ENABLE_128VM: case DSAF_MODE_DISABLE_6PORT_4VM: qid_mode = PPE_QID_MODE1; break; case DSAF_MODE_DISABLE_2PORT_8VM: qid_mode = PPE_QID_MODE7; break; case DSAF_MODE_DISABLE_6PORT_2VM: qid_mode = PPE_QID_MODE6; break; default: dev_err(ppe_common->dev, "get ppe queue mode failed! dsaf_mode=%d\n", dsaf_mode); return -EINVAL; } hns_ppe_set_qid_mode(ppe_common, qid_mode); } dsaf_set_dev_bit(ppe_common, PPE_COM_COMMON_CNT_CLR_CE_REG, PPE_COMMON_CNT_CLR_CE_B, 1); return 0; } /*clr ppe exception irq*/ static void hns_ppe_exc_irq_en(struct hns_ppe_cb *ppe_cb, int en) { u32 clr_vlue = 0xfffffffful; u32 msk_vlue = en ? 0xfffffffful : 0; /*1 is en, 0 is dis*/ u32 vld_msk = 0; /*only care bit 0,1,7*/ dsaf_set_bit(vld_msk, 0, 1); dsaf_set_bit(vld_msk, 1, 1); dsaf_set_bit(vld_msk, 7, 1); /*clr sts**/ dsaf_write_dev(ppe_cb, PPE_RINT_REG, clr_vlue); /*for some reserved bits, so set 0**/ dsaf_write_dev(ppe_cb, PPE_INTEN_REG, msk_vlue & vld_msk); } /** * ppe_init_hw - init ppe * @ppe_cb: ppe device */ static void hns_ppe_init_hw(struct hns_ppe_cb *ppe_cb) { struct ppe_common_cb *ppe_common_cb = ppe_cb->ppe_common_cb; u32 port = ppe_cb->index; struct dsaf_device *dsaf_dev = ppe_common_cb->dsaf_dev; int i; /* get default RSS key */ netdev_rss_key_fill(ppe_cb->rss_key, HNS_PPEV2_RSS_KEY_SIZE); dsaf_dev->misc_op->ppe_srst(dsaf_dev, port, 0); mdelay(10); dsaf_dev->misc_op->ppe_srst(dsaf_dev, port, 1); /* clr and msk except irq*/ hns_ppe_exc_irq_en(ppe_cb, 0); if (ppe_common_cb->ppe_mode == PPE_COMMON_MODE_DEBUG) { hns_ppe_set_port_mode(ppe_cb, PPE_MODE_GE); dsaf_write_dev(ppe_cb, PPE_CFG_PAUSE_IDLE_CNT_REG, 0); } else { hns_ppe_set_port_mode(ppe_cb, PPE_MODE_XGE); } hns_ppe_checksum_hw(ppe_cb, 0xffffffff); hns_ppe_cnt_clr_ce(ppe_cb); if (!AE_IS_VER1(dsaf_dev->dsaf_ver)) { hns_ppe_set_vlan_strip(ppe_cb, 0); dsaf_write_dev(ppe_cb, PPE_CFG_MAX_FRAME_LEN_REG, HNS_PPEV2_MAX_FRAME_LEN); /* set default RSS key in h/w */ hns_ppe_set_rss_key(ppe_cb, ppe_cb->rss_key); /* Set default indrection table in h/w */ for (i = 0; i < HNS_PPEV2_RSS_IND_TBL_SIZE; i++) ppe_cb->rss_indir_table[i] = i; hns_ppe_set_indir_table(ppe_cb, ppe_cb->rss_indir_table); } } /** * ppe_uninit_hw - uninit ppe * @ppe_device: ppe device */ static void hns_ppe_uninit_hw(struct hns_ppe_cb *ppe_cb) { u32 port; if (ppe_cb->ppe_common_cb) { struct dsaf_device *dsaf_dev = ppe_cb->ppe_common_cb->dsaf_dev; port = ppe_cb->index; dsaf_dev->misc_op->ppe_srst(dsaf_dev, port, 0); } } void hns_ppe_uninit_ex(struct ppe_common_cb *ppe_common) { u32 i; for (i = 0; i < ppe_common->ppe_num; i++) { if (ppe_common->dsaf_dev->mac_cb[i]) hns_ppe_uninit_hw(&ppe_common->ppe_cb[i]); memset(&ppe_common->ppe_cb[i], 0, sizeof(struct hns_ppe_cb)); } } void hns_ppe_uninit(struct dsaf_device *dsaf_dev) { u32 i; for (i = 0; i < HNS_PPE_COM_NUM; i++) { if (dsaf_dev->ppe_common[i]) hns_ppe_uninit_ex(dsaf_dev->ppe_common[i]); hns_rcb_common_free_cfg(dsaf_dev, i); hns_ppe_common_free_cfg(dsaf_dev, i); } } /** * hns_ppe_reset - reinit ppe/rcb hw * @dsaf_dev: dasf device * retuen void */ void hns_ppe_reset_common(struct dsaf_device *dsaf_dev, u8 ppe_common_index) { u32 i; int ret; struct ppe_common_cb *ppe_common; ppe_common = dsaf_dev->ppe_common[ppe_common_index]; ret = hns_ppe_common_init_hw(ppe_common); if (ret) return; for (i = 0; i < ppe_common->ppe_num; i++) { /* We only need to initiate ppe when the port exists */ if (dsaf_dev->mac_cb[i]) hns_ppe_init_hw(&ppe_common->ppe_cb[i]); } ret = hns_rcb_common_init_hw(dsaf_dev->rcb_common[ppe_common_index]); if (ret) return; hns_rcb_common_init_commit_hw(dsaf_dev->rcb_common[ppe_common_index]); } void hns_ppe_update_stats(struct hns_ppe_cb *ppe_cb) { struct hns_ppe_hw_stats *hw_stats = &ppe_cb->hw_stats; hw_stats->rx_pkts_from_sw += dsaf_read_dev(ppe_cb, PPE_HIS_RX_SW_PKT_CNT_REG); hw_stats->rx_pkts += dsaf_read_dev(ppe_cb, PPE_HIS_RX_WR_BD_OK_PKT_CNT_REG); hw_stats->rx_drop_no_bd += dsaf_read_dev(ppe_cb, PPE_HIS_RX_PKT_NO_BUF_CNT_REG); hw_stats->rx_alloc_buf_fail += dsaf_read_dev(ppe_cb, PPE_HIS_RX_APP_BUF_FAIL_CNT_REG); hw_stats->rx_alloc_buf_wait += dsaf_read_dev(ppe_cb, PPE_HIS_RX_APP_BUF_WAIT_CNT_REG); hw_stats->rx_drop_no_buf += dsaf_read_dev(ppe_cb, PPE_HIS_RX_PKT_DROP_FUL_CNT_REG); hw_stats->rx_err_fifo_full += dsaf_read_dev(ppe_cb, PPE_HIS_RX_PKT_DROP_PRT_CNT_REG); hw_stats->tx_bd_form_rcb += dsaf_read_dev(ppe_cb, PPE_HIS_TX_BD_CNT_REG); hw_stats->tx_pkts_from_rcb += dsaf_read_dev(ppe_cb, PPE_HIS_TX_PKT_CNT_REG); hw_stats->tx_pkts += dsaf_read_dev(ppe_cb, PPE_HIS_TX_PKT_OK_CNT_REG); hw_stats->tx_err_fifo_empty += dsaf_read_dev(ppe_cb, PPE_HIS_TX_PKT_EPT_CNT_REG); hw_stats->tx_err_checksum += dsaf_read_dev(ppe_cb, PPE_HIS_TX_PKT_CS_FAIL_CNT_REG); } int hns_ppe_get_sset_count(int stringset) { if (stringset == ETH_SS_STATS) return ETH_PPE_STATIC_NUM; return 0; } int hns_ppe_get_regs_count(void) { return ETH_PPE_DUMP_NUM; } /** * ppe_get_strings - get ppe srting * @ppe_device: ppe device * @stringset: string set type * @data: output string */ void hns_ppe_get_strings(struct hns_ppe_cb *ppe_cb, int stringset, u8 *data) { char *buff = (char *)data; int index = ppe_cb->index; snprintf(buff, ETH_GSTRING_LEN, "ppe%d_rx_sw_pkt", index); buff = buff + ETH_GSTRING_LEN; snprintf(buff, ETH_GSTRING_LEN, "ppe%d_rx_pkt_ok", index); buff = buff + ETH_GSTRING_LEN; snprintf(buff, ETH_GSTRING_LEN, "ppe%d_rx_drop_pkt_no_bd", index); buff = buff + ETH_GSTRING_LEN; snprintf(buff, ETH_GSTRING_LEN, "ppe%d_rx_alloc_buf_fail", index); buff = buff + ETH_GSTRING_LEN; snprintf(buff, ETH_GSTRING_LEN, "ppe%d_rx_alloc_buf_wait", index); buff = buff + ETH_GSTRING_LEN; snprintf(buff, ETH_GSTRING_LEN, "ppe%d_rx_pkt_drop_no_buf", index); buff = buff + ETH_GSTRING_LEN; snprintf(buff, ETH_GSTRING_LEN, "ppe%d_rx_pkt_err_fifo_full", index); buff = buff + ETH_GSTRING_LEN; snprintf(buff, ETH_GSTRING_LEN, "ppe%d_tx_bd", index); buff = buff + ETH_GSTRING_LEN; snprintf(buff, ETH_GSTRING_LEN, "ppe%d_tx_pkt", index); buff = buff + ETH_GSTRING_LEN; snprintf(buff, ETH_GSTRING_LEN, "ppe%d_tx_pkt_ok", index); buff = buff + ETH_GSTRING_LEN; snprintf(buff, ETH_GSTRING_LEN, "ppe%d_tx_pkt_err_fifo_empty", index); buff = buff + ETH_GSTRING_LEN; snprintf(buff, ETH_GSTRING_LEN, "ppe%d_tx_pkt_err_csum_fail", index); } void hns_ppe_get_stats(struct hns_ppe_cb *ppe_cb, u64 *data) { u64 *regs_buff = data; struct hns_ppe_hw_stats *hw_stats = &ppe_cb->hw_stats; regs_buff[0] = hw_stats->rx_pkts_from_sw; regs_buff[1] = hw_stats->rx_pkts; regs_buff[2] = hw_stats->rx_drop_no_bd; regs_buff[3] = hw_stats->rx_alloc_buf_fail; regs_buff[4] = hw_stats->rx_alloc_buf_wait; regs_buff[5] = hw_stats->rx_drop_no_buf; regs_buff[6] = hw_stats->rx_err_fifo_full; regs_buff[7] = hw_stats->tx_bd_form_rcb; regs_buff[8] = hw_stats->tx_pkts_from_rcb; regs_buff[9] = hw_stats->tx_pkts; regs_buff[10] = hw_stats->tx_err_fifo_empty; regs_buff[11] = hw_stats->tx_err_checksum; } /** * hns_ppe_init - init ppe device * @dsaf_dev: dasf device * retuen 0 - success , negative --fail */ int hns_ppe_init(struct dsaf_device *dsaf_dev) { int ret; int i; for (i = 0; i < HNS_PPE_COM_NUM; i++) { ret = hns_ppe_common_get_cfg(dsaf_dev, i); if (ret) goto get_cfg_fail; ret = hns_rcb_common_get_cfg(dsaf_dev, i); if (ret) goto get_cfg_fail; hns_ppe_get_cfg(dsaf_dev->ppe_common[i]); ret = hns_rcb_get_cfg(dsaf_dev->rcb_common[i]); if (ret) goto get_cfg_fail; } for (i = 0; i < HNS_PPE_COM_NUM; i++) hns_ppe_reset_common(dsaf_dev, i); return 0; get_cfg_fail: for (i = 0; i < HNS_PPE_COM_NUM; i++) { hns_rcb_common_free_cfg(dsaf_dev, i); hns_ppe_common_free_cfg(dsaf_dev, i); } return ret; } void hns_ppe_get_regs(struct hns_ppe_cb *ppe_cb, void *data) { struct ppe_common_cb *ppe_common = ppe_cb->ppe_common_cb; u32 *regs = data; u32 i; u32 offset; /* ppe common registers */ regs[0] = dsaf_read_dev(ppe_common, PPE_COM_CFG_QID_MODE_REG); regs[1] = dsaf_read_dev(ppe_common, PPE_COM_INTEN_REG); regs[2] = dsaf_read_dev(ppe_common, PPE_COM_RINT_REG); regs[3] = dsaf_read_dev(ppe_common, PPE_COM_INTSTS_REG); regs[4] = dsaf_read_dev(ppe_common, PPE_COM_COMMON_CNT_CLR_CE_REG); for (i = 0; i < DSAF_TOTAL_QUEUE_NUM; i++) { offset = PPE_COM_HIS_RX_PKT_QID_DROP_CNT_REG + 0x4 * i; regs[5 + i] = dsaf_read_dev(ppe_common, offset); offset = PPE_COM_HIS_RX_PKT_QID_OK_CNT_REG + 0x4 * i; regs[5 + i + DSAF_TOTAL_QUEUE_NUM] = dsaf_read_dev(ppe_common, offset); offset = PPE_COM_HIS_TX_PKT_QID_ERR_CNT_REG + 0x4 * i; regs[5 + i + DSAF_TOTAL_QUEUE_NUM * 2] = dsaf_read_dev(ppe_common, offset); offset = PPE_COM_HIS_TX_PKT_QID_OK_CNT_REG + 0x4 * i; regs[5 + i + DSAF_TOTAL_QUEUE_NUM * 3] = dsaf_read_dev(ppe_common, offset); } /* mark end of ppe regs */ for (i = 521; i < 524; i++) regs[i] = 0xeeeeeeee; /* ppe channel registers */ regs[525] = dsaf_read_dev(ppe_cb, PPE_CFG_TX_FIFO_THRSLD_REG); regs[526] = dsaf_read_dev(ppe_cb, PPE_CFG_RX_FIFO_THRSLD_REG); regs[527] = dsaf_read_dev(ppe_cb, PPE_CFG_RX_FIFO_PAUSE_THRSLD_REG); regs[528] = dsaf_read_dev(ppe_cb, PPE_CFG_RX_FIFO_SW_BP_THRSLD_REG); regs[529] = dsaf_read_dev(ppe_cb, PPE_CFG_PAUSE_IDLE_CNT_REG); regs[530] = dsaf_read_dev(ppe_cb, PPE_CFG_BUS_CTRL_REG); regs[531] = dsaf_read_dev(ppe_cb, PPE_CFG_TNL_TO_BE_RST_REG); regs[532] = dsaf_read_dev(ppe_cb, PPE_CURR_TNL_CAN_RST_REG); regs[533] = dsaf_read_dev(ppe_cb, PPE_CFG_XGE_MODE_REG); regs[534] = dsaf_read_dev(ppe_cb, PPE_CFG_MAX_FRAME_LEN_REG); regs[535] = dsaf_read_dev(ppe_cb, PPE_CFG_RX_PKT_MODE_REG); regs[536] = dsaf_read_dev(ppe_cb, PPE_CFG_RX_VLAN_TAG_REG); regs[537] = dsaf_read_dev(ppe_cb, PPE_CFG_TAG_GEN_REG); regs[538] = dsaf_read_dev(ppe_cb, PPE_CFG_PARSE_TAG_REG); regs[539] = dsaf_read_dev(ppe_cb, PPE_CFG_PRO_CHECK_EN_REG); regs[540] = dsaf_read_dev(ppe_cb, PPE_INTEN_REG); regs[541] = dsaf_read_dev(ppe_cb, PPE_RINT_REG); regs[542] = dsaf_read_dev(ppe_cb, PPE_INTSTS_REG); regs[543] = dsaf_read_dev(ppe_cb, PPE_CFG_RX_PKT_INT_REG); regs[544] = dsaf_read_dev(ppe_cb, PPE_CFG_HEAT_DECT_TIME0_REG); regs[545] = dsaf_read_dev(ppe_cb, PPE_CFG_HEAT_DECT_TIME1_REG); /* ppe static */ regs[546] = dsaf_read_dev(ppe_cb, PPE_HIS_RX_SW_PKT_CNT_REG); regs[547] = dsaf_read_dev(ppe_cb, PPE_HIS_RX_WR_BD_OK_PKT_CNT_REG); regs[548] = dsaf_read_dev(ppe_cb, PPE_HIS_RX_PKT_NO_BUF_CNT_REG); regs[549] = dsaf_read_dev(ppe_cb, PPE_HIS_TX_BD_CNT_REG); regs[550] = dsaf_read_dev(ppe_cb, PPE_HIS_TX_PKT_CNT_REG); regs[551] = dsaf_read_dev(ppe_cb, PPE_HIS_TX_PKT_OK_CNT_REG); regs[552] = dsaf_read_dev(ppe_cb, PPE_HIS_TX_PKT_EPT_CNT_REG); regs[553] = dsaf_read_dev(ppe_cb, PPE_HIS_TX_PKT_CS_FAIL_CNT_REG); regs[554] = dsaf_read_dev(ppe_cb, PPE_HIS_RX_APP_BUF_FAIL_CNT_REG); regs[555] = dsaf_read_dev(ppe_cb, PPE_HIS_RX_APP_BUF_WAIT_CNT_REG); regs[556] = dsaf_read_dev(ppe_cb, PPE_HIS_RX_PKT_DROP_FUL_CNT_REG); regs[557] = dsaf_read_dev(ppe_cb, PPE_HIS_RX_PKT_DROP_PRT_CNT_REG); regs[558] = dsaf_read_dev(ppe_cb, PPE_TNL_0_5_CNT_CLR_CE_REG); regs[559] = dsaf_read_dev(ppe_cb, PPE_CFG_AXI_DBG_REG); regs[560] = dsaf_read_dev(ppe_cb, PPE_HIS_PRO_ERR_REG); regs[561] = dsaf_read_dev(ppe_cb, PPE_HIS_TNL_FIFO_ERR_REG); regs[562] = dsaf_read_dev(ppe_cb, PPE_CURR_CFF_DATA_NUM_REG); regs[563] = dsaf_read_dev(ppe_cb, PPE_CURR_RX_ST_REG); regs[564] = dsaf_read_dev(ppe_cb, PPE_CURR_TX_ST_REG); regs[565] = dsaf_read_dev(ppe_cb, PPE_CURR_RX_FIFO0_REG); regs[566] = dsaf_read_dev(ppe_cb, PPE_CURR_RX_FIFO1_REG); regs[567] = dsaf_read_dev(ppe_cb, PPE_CURR_TX_FIFO0_REG); regs[568] = dsaf_read_dev(ppe_cb, PPE_CURR_TX_FIFO1_REG); regs[569] = dsaf_read_dev(ppe_cb, PPE_ECO0_REG); regs[570] = dsaf_read_dev(ppe_cb, PPE_ECO1_REG); regs[571] = dsaf_read_dev(ppe_cb, PPE_ECO2_REG); /* mark end of ppe regs */ for (i = 572; i < 576; i++) regs[i] = 0xeeeeeeee; }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_3020_1
crossvul-cpp_data_bad_2984_0
/* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com * Copyright (c) 2016 Facebook * * This program is free software; you can redistribute it and/or * modify it under the terms of version 2 of the GNU General Public * License as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. */ #include <linux/kernel.h> #include <linux/types.h> #include <linux/slab.h> #include <linux/bpf.h> #include <linux/bpf_verifier.h> #include <linux/filter.h> #include <net/netlink.h> #include <linux/file.h> #include <linux/vmalloc.h> #include <linux/stringify.h> #include "disasm.h" static const struct bpf_verifier_ops * const bpf_verifier_ops[] = { #define BPF_PROG_TYPE(_id, _name) \ [_id] = & _name ## _verifier_ops, #define BPF_MAP_TYPE(_id, _ops) #include <linux/bpf_types.h> #undef BPF_PROG_TYPE #undef BPF_MAP_TYPE }; /* bpf_check() is a static code analyzer that walks eBPF program * instruction by instruction and updates register/stack state. * All paths of conditional branches are analyzed until 'bpf_exit' insn. * * The first pass is depth-first-search to check that the program is a DAG. * It rejects the following programs: * - larger than BPF_MAXINSNS insns * - if loop is present (detected via back-edge) * - unreachable insns exist (shouldn't be a forest. program = one function) * - out of bounds or malformed jumps * The second pass is all possible path descent from the 1st insn. * Since it's analyzing all pathes through the program, the length of the * analysis is limited to 64k insn, which may be hit even if total number of * insn is less then 4K, but there are too many branches that change stack/regs. * Number of 'branches to be analyzed' is limited to 1k * * On entry to each instruction, each register has a type, and the instruction * changes the types of the registers depending on instruction semantics. * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is * copied to R1. * * All registers are 64-bit. * R0 - return register * R1-R5 argument passing registers * R6-R9 callee saved registers * R10 - frame pointer read-only * * At the start of BPF program the register R1 contains a pointer to bpf_context * and has type PTR_TO_CTX. * * Verifier tracks arithmetic operations on pointers in case: * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10), * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20), * 1st insn copies R10 (which has FRAME_PTR) type into R1 * and 2nd arithmetic instruction is pattern matched to recognize * that it wants to construct a pointer to some element within stack. * So after 2nd insn, the register R1 has type PTR_TO_STACK * (and -20 constant is saved for further stack bounds checking). * Meaning that this reg is a pointer to stack plus known immediate constant. * * Most of the time the registers have SCALAR_VALUE type, which * means the register has some value, but it's not a valid pointer. * (like pointer plus pointer becomes SCALAR_VALUE type) * * When verifier sees load or store instructions the type of base register * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK. These are three pointer * types recognized by check_mem_access() function. * * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value' * and the range of [ptr, ptr + map's value_size) is accessible. * * registers used to pass values to function calls are checked against * function argument constraints. * * ARG_PTR_TO_MAP_KEY is one of such argument constraints. * It means that the register type passed to this function must be * PTR_TO_STACK and it will be used inside the function as * 'pointer to map element key' * * For example the argument constraints for bpf_map_lookup_elem(): * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL, * .arg1_type = ARG_CONST_MAP_PTR, * .arg2_type = ARG_PTR_TO_MAP_KEY, * * ret_type says that this function returns 'pointer to map elem value or null' * function expects 1st argument to be a const pointer to 'struct bpf_map' and * 2nd argument should be a pointer to stack, which will be used inside * the helper function as a pointer to map element key. * * On the kernel side the helper function looks like: * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5) * { * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1; * void *key = (void *) (unsigned long) r2; * void *value; * * here kernel can access 'key' and 'map' pointers safely, knowing that * [key, key + map->key_size) bytes are valid and were initialized on * the stack of eBPF program. * } * * Corresponding eBPF program may look like: * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem), * here verifier looks at prototype of map_lookup_elem() and sees: * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok, * Now verifier knows that this map has key of R1->map_ptr->key_size bytes * * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far, * Now verifier checks that [R2, R2 + map's key_size) are within stack limits * and were initialized prior to this call. * If it's ok, then verifier allows this BPF_CALL insn and looks at * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function * returns ether pointer to map value or NULL. * * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off' * insn, the register holding that pointer in the true branch changes state to * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false * branch. See check_cond_jmp_op(). * * After the call R0 is set to return type of the function and registers R1-R5 * are set to NOT_INIT to indicate that they are no longer readable. */ /* verifier_state + insn_idx are pushed to stack when branch is encountered */ struct bpf_verifier_stack_elem { /* verifer state is 'st' * before processing instruction 'insn_idx' * and after processing instruction 'prev_insn_idx' */ struct bpf_verifier_state st; int insn_idx; int prev_insn_idx; struct bpf_verifier_stack_elem *next; }; #define BPF_COMPLEXITY_LIMIT_INSNS 131072 #define BPF_COMPLEXITY_LIMIT_STACK 1024 #define BPF_MAP_PTR_POISON ((void *)0xeB9F + POISON_POINTER_DELTA) struct bpf_call_arg_meta { struct bpf_map *map_ptr; bool raw_mode; bool pkt_access; int regno; int access_size; }; static DEFINE_MUTEX(bpf_verifier_lock); /* log_level controls verbosity level of eBPF verifier. * verbose() is used to dump the verification trace to the log, so the user * can figure out what's wrong with the program */ static __printf(2, 3) void verbose(struct bpf_verifier_env *env, const char *fmt, ...) { struct bpf_verifer_log *log = &env->log; unsigned int n; va_list args; if (!log->level || !log->ubuf || bpf_verifier_log_full(log)) return; va_start(args, fmt); n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args); va_end(args); WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1, "verifier log line truncated - local buffer too short\n"); n = min(log->len_total - log->len_used - 1, n); log->kbuf[n] = '\0'; if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1)) log->len_used += n; else log->ubuf = NULL; } static bool type_is_pkt_pointer(enum bpf_reg_type type) { return type == PTR_TO_PACKET || type == PTR_TO_PACKET_META; } /* string representation of 'enum bpf_reg_type' */ static const char * const reg_type_str[] = { [NOT_INIT] = "?", [SCALAR_VALUE] = "inv", [PTR_TO_CTX] = "ctx", [CONST_PTR_TO_MAP] = "map_ptr", [PTR_TO_MAP_VALUE] = "map_value", [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null", [PTR_TO_STACK] = "fp", [PTR_TO_PACKET] = "pkt", [PTR_TO_PACKET_META] = "pkt_meta", [PTR_TO_PACKET_END] = "pkt_end", }; static void print_verifier_state(struct bpf_verifier_env *env, struct bpf_verifier_state *state) { struct bpf_reg_state *reg; enum bpf_reg_type t; int i; for (i = 0; i < MAX_BPF_REG; i++) { reg = &state->regs[i]; t = reg->type; if (t == NOT_INIT) continue; verbose(env, " R%d=%s", i, reg_type_str[t]); if ((t == SCALAR_VALUE || t == PTR_TO_STACK) && tnum_is_const(reg->var_off)) { /* reg->off should be 0 for SCALAR_VALUE */ verbose(env, "%lld", reg->var_off.value + reg->off); } else { verbose(env, "(id=%d", reg->id); if (t != SCALAR_VALUE) verbose(env, ",off=%d", reg->off); if (type_is_pkt_pointer(t)) verbose(env, ",r=%d", reg->range); else if (t == CONST_PTR_TO_MAP || t == PTR_TO_MAP_VALUE || t == PTR_TO_MAP_VALUE_OR_NULL) verbose(env, ",ks=%d,vs=%d", reg->map_ptr->key_size, reg->map_ptr->value_size); if (tnum_is_const(reg->var_off)) { /* Typically an immediate SCALAR_VALUE, but * could be a pointer whose offset is too big * for reg->off */ verbose(env, ",imm=%llx", reg->var_off.value); } else { if (reg->smin_value != reg->umin_value && reg->smin_value != S64_MIN) verbose(env, ",smin_value=%lld", (long long)reg->smin_value); if (reg->smax_value != reg->umax_value && reg->smax_value != S64_MAX) verbose(env, ",smax_value=%lld", (long long)reg->smax_value); if (reg->umin_value != 0) verbose(env, ",umin_value=%llu", (unsigned long long)reg->umin_value); if (reg->umax_value != U64_MAX) verbose(env, ",umax_value=%llu", (unsigned long long)reg->umax_value); if (!tnum_is_unknown(reg->var_off)) { char tn_buf[48]; tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); verbose(env, ",var_off=%s", tn_buf); } } verbose(env, ")"); } } for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { if (state->stack[i].slot_type[0] == STACK_SPILL) verbose(env, " fp%d=%s", -MAX_BPF_STACK + i * BPF_REG_SIZE, reg_type_str[state->stack[i].spilled_ptr.type]); } verbose(env, "\n"); } static int copy_stack_state(struct bpf_verifier_state *dst, const struct bpf_verifier_state *src) { if (!src->stack) return 0; if (WARN_ON_ONCE(dst->allocated_stack < src->allocated_stack)) { /* internal bug, make state invalid to reject the program */ memset(dst, 0, sizeof(*dst)); return -EFAULT; } memcpy(dst->stack, src->stack, sizeof(*src->stack) * (src->allocated_stack / BPF_REG_SIZE)); return 0; } /* do_check() starts with zero-sized stack in struct bpf_verifier_state to * make it consume minimal amount of memory. check_stack_write() access from * the program calls into realloc_verifier_state() to grow the stack size. * Note there is a non-zero 'parent' pointer inside bpf_verifier_state * which this function copies over. It points to previous bpf_verifier_state * which is never reallocated */ static int realloc_verifier_state(struct bpf_verifier_state *state, int size, bool copy_old) { u32 old_size = state->allocated_stack; struct bpf_stack_state *new_stack; int slot = size / BPF_REG_SIZE; if (size <= old_size || !size) { if (copy_old) return 0; state->allocated_stack = slot * BPF_REG_SIZE; if (!size && old_size) { kfree(state->stack); state->stack = NULL; } return 0; } new_stack = kmalloc_array(slot, sizeof(struct bpf_stack_state), GFP_KERNEL); if (!new_stack) return -ENOMEM; if (copy_old) { if (state->stack) memcpy(new_stack, state->stack, sizeof(*new_stack) * (old_size / BPF_REG_SIZE)); memset(new_stack + old_size / BPF_REG_SIZE, 0, sizeof(*new_stack) * (size - old_size) / BPF_REG_SIZE); } state->allocated_stack = slot * BPF_REG_SIZE; kfree(state->stack); state->stack = new_stack; return 0; } static void free_verifier_state(struct bpf_verifier_state *state, bool free_self) { kfree(state->stack); if (free_self) kfree(state); } /* copy verifier state from src to dst growing dst stack space * when necessary to accommodate larger src stack */ static int copy_verifier_state(struct bpf_verifier_state *dst, const struct bpf_verifier_state *src) { int err; err = realloc_verifier_state(dst, src->allocated_stack, false); if (err) return err; memcpy(dst, src, offsetof(struct bpf_verifier_state, allocated_stack)); return copy_stack_state(dst, src); } static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx, int *insn_idx) { struct bpf_verifier_state *cur = env->cur_state; struct bpf_verifier_stack_elem *elem, *head = env->head; int err; if (env->head == NULL) return -ENOENT; if (cur) { err = copy_verifier_state(cur, &head->st); if (err) return err; } if (insn_idx) *insn_idx = head->insn_idx; if (prev_insn_idx) *prev_insn_idx = head->prev_insn_idx; elem = head->next; free_verifier_state(&head->st, false); kfree(head); env->head = elem; env->stack_size--; return 0; } static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env, int insn_idx, int prev_insn_idx) { struct bpf_verifier_state *cur = env->cur_state; struct bpf_verifier_stack_elem *elem; int err; elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); if (!elem) goto err; elem->insn_idx = insn_idx; elem->prev_insn_idx = prev_insn_idx; elem->next = env->head; env->head = elem; env->stack_size++; err = copy_verifier_state(&elem->st, cur); if (err) goto err; if (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) { verbose(env, "BPF program is too complex\n"); goto err; } return &elem->st; err: /* pop all elements and return */ while (!pop_stack(env, NULL, NULL)); return NULL; } #define CALLER_SAVED_REGS 6 static const int caller_saved[CALLER_SAVED_REGS] = { BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5 }; static void __mark_reg_not_init(struct bpf_reg_state *reg); /* Mark the unknown part of a register (variable offset or scalar value) as * known to have the value @imm. */ static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm) { reg->id = 0; reg->var_off = tnum_const(imm); reg->smin_value = (s64)imm; reg->smax_value = (s64)imm; reg->umin_value = imm; reg->umax_value = imm; } /* Mark the 'variable offset' part of a register as zero. This should be * used only on registers holding a pointer type. */ static void __mark_reg_known_zero(struct bpf_reg_state *reg) { __mark_reg_known(reg, 0); } static void mark_reg_known_zero(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno) { if (WARN_ON(regno >= MAX_BPF_REG)) { verbose(env, "mark_reg_known_zero(regs, %u)\n", regno); /* Something bad happened, let's kill all regs */ for (regno = 0; regno < MAX_BPF_REG; regno++) __mark_reg_not_init(regs + regno); return; } __mark_reg_known_zero(regs + regno); } static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg) { return type_is_pkt_pointer(reg->type); } static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg) { return reg_is_pkt_pointer(reg) || reg->type == PTR_TO_PACKET_END; } /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */ static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg, enum bpf_reg_type which) { /* The register can already have a range from prior markings. * This is fine as long as it hasn't been advanced from its * origin. */ return reg->type == which && reg->id == 0 && reg->off == 0 && tnum_equals_const(reg->var_off, 0); } /* Attempts to improve min/max values based on var_off information */ static void __update_reg_bounds(struct bpf_reg_state *reg) { /* min signed is max(sign bit) | min(other bits) */ reg->smin_value = max_t(s64, reg->smin_value, reg->var_off.value | (reg->var_off.mask & S64_MIN)); /* max signed is min(sign bit) | max(other bits) */ reg->smax_value = min_t(s64, reg->smax_value, reg->var_off.value | (reg->var_off.mask & S64_MAX)); reg->umin_value = max(reg->umin_value, reg->var_off.value); reg->umax_value = min(reg->umax_value, reg->var_off.value | reg->var_off.mask); } /* Uses signed min/max values to inform unsigned, and vice-versa */ static void __reg_deduce_bounds(struct bpf_reg_state *reg) { /* Learn sign from signed bounds. * If we cannot cross the sign boundary, then signed and unsigned bounds * are the same, so combine. This works even in the negative case, e.g. * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. */ if (reg->smin_value >= 0 || reg->smax_value < 0) { reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value); reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value); return; } /* Learn sign from unsigned bounds. Signed bounds cross the sign * boundary, so we must be careful. */ if ((s64)reg->umax_value >= 0) { /* Positive. We can't learn anything from the smin, but smax * is positive, hence safe. */ reg->smin_value = reg->umin_value; reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value); } else if ((s64)reg->umin_value < 0) { /* Negative. We can't learn anything from the smax, but smin * is negative, hence safe. */ reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value); reg->smax_value = reg->umax_value; } } /* Attempts to improve var_off based on unsigned min/max information */ static void __reg_bound_offset(struct bpf_reg_state *reg) { reg->var_off = tnum_intersect(reg->var_off, tnum_range(reg->umin_value, reg->umax_value)); } /* Reset the min/max bounds of a register */ static void __mark_reg_unbounded(struct bpf_reg_state *reg) { reg->smin_value = S64_MIN; reg->smax_value = S64_MAX; reg->umin_value = 0; reg->umax_value = U64_MAX; } /* Mark a register as having a completely unknown (scalar) value. */ static void __mark_reg_unknown(struct bpf_reg_state *reg) { reg->type = SCALAR_VALUE; reg->id = 0; reg->off = 0; reg->var_off = tnum_unknown; __mark_reg_unbounded(reg); } static void mark_reg_unknown(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno) { if (WARN_ON(regno >= MAX_BPF_REG)) { verbose(env, "mark_reg_unknown(regs, %u)\n", regno); /* Something bad happened, let's kill all regs */ for (regno = 0; regno < MAX_BPF_REG; regno++) __mark_reg_not_init(regs + regno); return; } __mark_reg_unknown(regs + regno); } static void __mark_reg_not_init(struct bpf_reg_state *reg) { __mark_reg_unknown(reg); reg->type = NOT_INIT; } static void mark_reg_not_init(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno) { if (WARN_ON(regno >= MAX_BPF_REG)) { verbose(env, "mark_reg_not_init(regs, %u)\n", regno); /* Something bad happened, let's kill all regs */ for (regno = 0; regno < MAX_BPF_REG; regno++) __mark_reg_not_init(regs + regno); return; } __mark_reg_not_init(regs + regno); } static void init_reg_state(struct bpf_verifier_env *env, struct bpf_reg_state *regs) { int i; for (i = 0; i < MAX_BPF_REG; i++) { mark_reg_not_init(env, regs, i); regs[i].live = REG_LIVE_NONE; } /* frame pointer */ regs[BPF_REG_FP].type = PTR_TO_STACK; mark_reg_known_zero(env, regs, BPF_REG_FP); /* 1st arg to a function */ regs[BPF_REG_1].type = PTR_TO_CTX; mark_reg_known_zero(env, regs, BPF_REG_1); } enum reg_arg_type { SRC_OP, /* register is used as source operand */ DST_OP, /* register is used as destination operand */ DST_OP_NO_MARK /* same as above, check only, don't mark */ }; static void mark_reg_read(const struct bpf_verifier_state *state, u32 regno) { struct bpf_verifier_state *parent = state->parent; if (regno == BPF_REG_FP) /* We don't need to worry about FP liveness because it's read-only */ return; while (parent) { /* if read wasn't screened by an earlier write ... */ if (state->regs[regno].live & REG_LIVE_WRITTEN) break; /* ... then we depend on parent's value */ parent->regs[regno].live |= REG_LIVE_READ; state = parent; parent = state->parent; } } static int check_reg_arg(struct bpf_verifier_env *env, u32 regno, enum reg_arg_type t) { struct bpf_reg_state *regs = env->cur_state->regs; if (regno >= MAX_BPF_REG) { verbose(env, "R%d is invalid\n", regno); return -EINVAL; } if (t == SRC_OP) { /* check whether register used as source operand can be read */ if (regs[regno].type == NOT_INIT) { verbose(env, "R%d !read_ok\n", regno); return -EACCES; } mark_reg_read(env->cur_state, regno); } else { /* check whether register used as dest operand can be written to */ if (regno == BPF_REG_FP) { verbose(env, "frame pointer is read only\n"); return -EACCES; } regs[regno].live |= REG_LIVE_WRITTEN; if (t == DST_OP) mark_reg_unknown(env, regs, regno); } return 0; } static bool is_spillable_regtype(enum bpf_reg_type type) { switch (type) { case PTR_TO_MAP_VALUE: case PTR_TO_MAP_VALUE_OR_NULL: case PTR_TO_STACK: case PTR_TO_CTX: case PTR_TO_PACKET: case PTR_TO_PACKET_META: case PTR_TO_PACKET_END: case CONST_PTR_TO_MAP: return true; default: return false; } } /* check_stack_read/write functions track spill/fill of registers, * stack boundary and alignment are checked in check_mem_access() */ static int check_stack_write(struct bpf_verifier_env *env, struct bpf_verifier_state *state, int off, int size, int value_regno) { int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err; err = realloc_verifier_state(state, round_up(slot + 1, BPF_REG_SIZE), true); if (err) return err; /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0, * so it's aligned access and [off, off + size) are within stack limits */ if (!env->allow_ptr_leaks && state->stack[spi].slot_type[0] == STACK_SPILL && size != BPF_REG_SIZE) { verbose(env, "attempt to corrupt spilled pointer on stack\n"); return -EACCES; } if (value_regno >= 0 && is_spillable_regtype(state->regs[value_regno].type)) { /* register containing pointer is being spilled into stack */ if (size != BPF_REG_SIZE) { verbose(env, "invalid size of register spill\n"); return -EACCES; } /* save register state */ state->stack[spi].spilled_ptr = state->regs[value_regno]; state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; for (i = 0; i < BPF_REG_SIZE; i++) state->stack[spi].slot_type[i] = STACK_SPILL; } else { /* regular write of data into stack */ state->stack[spi].spilled_ptr = (struct bpf_reg_state) {}; for (i = 0; i < size; i++) state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = STACK_MISC; } return 0; } static void mark_stack_slot_read(const struct bpf_verifier_state *state, int slot) { struct bpf_verifier_state *parent = state->parent; while (parent) { /* if read wasn't screened by an earlier write ... */ if (state->stack[slot].spilled_ptr.live & REG_LIVE_WRITTEN) break; /* ... then we depend on parent's value */ parent->stack[slot].spilled_ptr.live |= REG_LIVE_READ; state = parent; parent = state->parent; } } static int check_stack_read(struct bpf_verifier_env *env, struct bpf_verifier_state *state, int off, int size, int value_regno) { int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; u8 *stype; if (state->allocated_stack <= slot) { verbose(env, "invalid read from stack off %d+0 size %d\n", off, size); return -EACCES; } stype = state->stack[spi].slot_type; if (stype[0] == STACK_SPILL) { if (size != BPF_REG_SIZE) { verbose(env, "invalid size of register spill\n"); return -EACCES; } for (i = 1; i < BPF_REG_SIZE; i++) { if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) { verbose(env, "corrupted spill memory\n"); return -EACCES; } } if (value_regno >= 0) { /* restore register state from stack */ state->regs[value_regno] = state->stack[spi].spilled_ptr; mark_stack_slot_read(state, spi); } return 0; } else { for (i = 0; i < size; i++) { if (stype[(slot - i) % BPF_REG_SIZE] != STACK_MISC) { verbose(env, "invalid read from stack off %d+%d size %d\n", off, i, size); return -EACCES; } } if (value_regno >= 0) /* have read misc data from the stack */ mark_reg_unknown(env, state->regs, value_regno); return 0; } } /* check read/write into map element returned by bpf_map_lookup_elem() */ static int __check_map_access(struct bpf_verifier_env *env, u32 regno, int off, int size, bool zero_size_allowed) { struct bpf_reg_state *regs = cur_regs(env); struct bpf_map *map = regs[regno].map_ptr; if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) || off + size > map->value_size) { verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", map->value_size, off, size); return -EACCES; } return 0; } /* check read/write into a map element with possible variable offset */ static int check_map_access(struct bpf_verifier_env *env, u32 regno, int off, int size, bool zero_size_allowed) { struct bpf_verifier_state *state = env->cur_state; struct bpf_reg_state *reg = &state->regs[regno]; int err; /* We may have adjusted the register to this map value, so we * need to try adding each of min_value and max_value to off * to make sure our theoretical access will be safe. */ if (env->log.level) print_verifier_state(env, state); /* The minimum value is only important with signed * comparisons where we can't assume the floor of a * value is 0. If we are using signed variables for our * index'es we need to make sure that whatever we use * will have a set floor within our range. */ if (reg->smin_value < 0) { verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", regno); return -EACCES; } err = __check_map_access(env, regno, reg->smin_value + off, size, zero_size_allowed); if (err) { verbose(env, "R%d min value is outside of the array range\n", regno); return err; } /* If we haven't set a max value then we need to bail since we can't be * sure we won't do bad things. * If reg->umax_value + off could overflow, treat that as unbounded too. */ if (reg->umax_value >= BPF_MAX_VAR_OFF) { verbose(env, "R%d unbounded memory access, make sure to bounds check any array access into a map\n", regno); return -EACCES; } err = __check_map_access(env, regno, reg->umax_value + off, size, zero_size_allowed); if (err) verbose(env, "R%d max value is outside of the array range\n", regno); return err; } #define MAX_PACKET_OFF 0xffff static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, const struct bpf_call_arg_meta *meta, enum bpf_access_type t) { switch (env->prog->type) { case BPF_PROG_TYPE_LWT_IN: case BPF_PROG_TYPE_LWT_OUT: /* dst_input() and dst_output() can't write for now */ if (t == BPF_WRITE) return false; /* fallthrough */ case BPF_PROG_TYPE_SCHED_CLS: case BPF_PROG_TYPE_SCHED_ACT: case BPF_PROG_TYPE_XDP: case BPF_PROG_TYPE_LWT_XMIT: case BPF_PROG_TYPE_SK_SKB: if (meta) return meta->pkt_access; env->seen_direct_write = true; return true; default: return false; } } static int __check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, int size, bool zero_size_allowed) { struct bpf_reg_state *regs = cur_regs(env); struct bpf_reg_state *reg = &regs[regno]; if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) || (u64)off + size > reg->range) { verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n", off, size, regno, reg->id, reg->off, reg->range); return -EACCES; } return 0; } static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, int size, bool zero_size_allowed) { struct bpf_reg_state *regs = cur_regs(env); struct bpf_reg_state *reg = &regs[regno]; int err; /* We may have added a variable offset to the packet pointer; but any * reg->range we have comes after that. We are only checking the fixed * offset. */ /* We don't allow negative numbers, because we aren't tracking enough * detail to prove they're safe. */ if (reg->smin_value < 0) { verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", regno); return -EACCES; } err = __check_packet_access(env, regno, off, size, zero_size_allowed); if (err) { verbose(env, "R%d offset is outside of the packet\n", regno); return err; } return err; } /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, enum bpf_access_type t, enum bpf_reg_type *reg_type) { struct bpf_insn_access_aux info = { .reg_type = *reg_type, }; if (env->ops->is_valid_access && env->ops->is_valid_access(off, size, t, &info)) { /* A non zero info.ctx_field_size indicates that this field is a * candidate for later verifier transformation to load the whole * field and then apply a mask when accessed with a narrower * access than actual ctx access size. A zero info.ctx_field_size * will only allow for whole field access and rejects any other * type of narrower access. */ *reg_type = info.reg_type; env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size; /* remember the offset of last byte accessed in ctx */ if (env->prog->aux->max_ctx_offset < off + size) env->prog->aux->max_ctx_offset = off + size; return 0; } verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); return -EACCES; } static bool __is_pointer_value(bool allow_ptr_leaks, const struct bpf_reg_state *reg) { if (allow_ptr_leaks) return false; return reg->type != SCALAR_VALUE; } static bool is_pointer_value(struct bpf_verifier_env *env, int regno) { return __is_pointer_value(env->allow_ptr_leaks, cur_regs(env) + regno); } static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, const struct bpf_reg_state *reg, int off, int size, bool strict) { struct tnum reg_off; int ip_align; /* Byte size accesses are always allowed. */ if (!strict || size == 1) return 0; /* For platforms that do not have a Kconfig enabling * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of * NET_IP_ALIGN is universally set to '2'. And on platforms * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get * to this code only in strict mode where we want to emulate * the NET_IP_ALIGN==2 checking. Therefore use an * unconditional IP align value of '2'. */ ip_align = 2; reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off)); if (!tnum_is_aligned(reg_off, size)) { char tn_buf[48]; tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); verbose(env, "misaligned packet access off %d+%s+%d+%d size %d\n", ip_align, tn_buf, reg->off, off, size); return -EACCES; } return 0; } static int check_generic_ptr_alignment(struct bpf_verifier_env *env, const struct bpf_reg_state *reg, const char *pointer_desc, int off, int size, bool strict) { struct tnum reg_off; /* Byte size accesses are always allowed. */ if (!strict || size == 1) return 0; reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off)); if (!tnum_is_aligned(reg_off, size)) { char tn_buf[48]; tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); verbose(env, "misaligned %saccess off %s+%d+%d size %d\n", pointer_desc, tn_buf, reg->off, off, size); return -EACCES; } return 0; } static int check_ptr_alignment(struct bpf_verifier_env *env, const struct bpf_reg_state *reg, int off, int size) { bool strict = env->strict_alignment; const char *pointer_desc = ""; switch (reg->type) { case PTR_TO_PACKET: case PTR_TO_PACKET_META: /* Special case, because of NET_IP_ALIGN. Given metadata sits * right in front, treat it the very same way. */ return check_pkt_ptr_alignment(env, reg, off, size, strict); case PTR_TO_MAP_VALUE: pointer_desc = "value "; break; case PTR_TO_CTX: pointer_desc = "context "; break; case PTR_TO_STACK: pointer_desc = "stack "; break; default: break; } return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, strict); } /* check whether memory at (regno + off) is accessible for t = (read | write) * if t==write, value_regno is a register which value is stored into memory * if t==read, value_regno is a register which will receive the value from memory * if t==write && value_regno==-1, some unknown value is stored into memory * if t==read && value_regno==-1, don't care what we read from memory */ static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, int off, int bpf_size, enum bpf_access_type t, int value_regno) { struct bpf_verifier_state *state = env->cur_state; struct bpf_reg_state *regs = cur_regs(env); struct bpf_reg_state *reg = regs + regno; int size, err = 0; size = bpf_size_to_bytes(bpf_size); if (size < 0) return size; /* alignment checks will add in reg->off themselves */ err = check_ptr_alignment(env, reg, off, size); if (err) return err; /* for access checks, reg->off is just part of off */ off += reg->off; if (reg->type == PTR_TO_MAP_VALUE) { if (t == BPF_WRITE && value_regno >= 0 && is_pointer_value(env, value_regno)) { verbose(env, "R%d leaks addr into map\n", value_regno); return -EACCES; } err = check_map_access(env, regno, off, size, false); if (!err && t == BPF_READ && value_regno >= 0) mark_reg_unknown(env, regs, value_regno); } else if (reg->type == PTR_TO_CTX) { enum bpf_reg_type reg_type = SCALAR_VALUE; if (t == BPF_WRITE && value_regno >= 0 && is_pointer_value(env, value_regno)) { verbose(env, "R%d leaks addr into ctx\n", value_regno); return -EACCES; } /* ctx accesses must be at a fixed offset, so that we can * determine what type of data were returned. */ if (reg->off) { verbose(env, "dereference of modified ctx ptr R%d off=%d+%d, ctx+const is allowed, ctx+const+const is not\n", regno, reg->off, off - reg->off); return -EACCES; } if (!tnum_is_const(reg->var_off) || reg->var_off.value) { char tn_buf[48]; tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); verbose(env, "variable ctx access var_off=%s off=%d size=%d", tn_buf, off, size); return -EACCES; } err = check_ctx_access(env, insn_idx, off, size, t, &reg_type); if (!err && t == BPF_READ && value_regno >= 0) { /* ctx access returns either a scalar, or a * PTR_TO_PACKET[_META,_END]. In the latter * case, we know the offset is zero. */ if (reg_type == SCALAR_VALUE) mark_reg_unknown(env, regs, value_regno); else mark_reg_known_zero(env, regs, value_regno); regs[value_regno].id = 0; regs[value_regno].off = 0; regs[value_regno].range = 0; regs[value_regno].type = reg_type; } } else if (reg->type == PTR_TO_STACK) { /* stack accesses must be at a fixed offset, so that we can * determine what type of data were returned. * See check_stack_read(). */ if (!tnum_is_const(reg->var_off)) { char tn_buf[48]; tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); verbose(env, "variable stack access var_off=%s off=%d size=%d", tn_buf, off, size); return -EACCES; } off += reg->var_off.value; if (off >= 0 || off < -MAX_BPF_STACK) { verbose(env, "invalid stack off=%d size=%d\n", off, size); return -EACCES; } if (env->prog->aux->stack_depth < -off) env->prog->aux->stack_depth = -off; if (t == BPF_WRITE) err = check_stack_write(env, state, off, size, value_regno); else err = check_stack_read(env, state, off, size, value_regno); } else if (reg_is_pkt_pointer(reg)) { if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { verbose(env, "cannot write into packet\n"); return -EACCES; } if (t == BPF_WRITE && value_regno >= 0 && is_pointer_value(env, value_regno)) { verbose(env, "R%d leaks addr into packet\n", value_regno); return -EACCES; } err = check_packet_access(env, regno, off, size, false); if (!err && t == BPF_READ && value_regno >= 0) mark_reg_unknown(env, regs, value_regno); } else { verbose(env, "R%d invalid mem access '%s'\n", regno, reg_type_str[reg->type]); return -EACCES; } if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && regs[value_regno].type == SCALAR_VALUE) { /* b/h/w load zero-extends, mark upper bits as known 0 */ regs[value_regno].var_off = tnum_cast(regs[value_regno].var_off, size); __update_reg_bounds(&regs[value_regno]); } return err; } static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn) { int err; if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) || insn->imm != 0) { verbose(env, "BPF_XADD uses reserved fields\n"); return -EINVAL; } /* check src1 operand */ err = check_reg_arg(env, insn->src_reg, SRC_OP); if (err) return err; /* check src2 operand */ err = check_reg_arg(env, insn->dst_reg, SRC_OP); if (err) return err; if (is_pointer_value(env, insn->src_reg)) { verbose(env, "R%d leaks addr into mem\n", insn->src_reg); return -EACCES; } /* check whether atomic_add can read the memory */ err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, BPF_SIZE(insn->code), BPF_READ, -1); if (err) return err; /* check whether atomic_add can write into the same memory */ return check_mem_access(env, insn_idx, insn->dst_reg, insn->off, BPF_SIZE(insn->code), BPF_WRITE, -1); } /* Does this register contain a constant zero? */ static bool register_is_null(struct bpf_reg_state reg) { return reg.type == SCALAR_VALUE && tnum_equals_const(reg.var_off, 0); } /* when register 'regno' is passed into function that will read 'access_size' * bytes from that pointer, make sure that it's within stack boundary * and all elements of stack are initialized. * Unlike most pointer bounds-checking functions, this one doesn't take an * 'off' argument, so it has to add in reg->off itself. */ static int check_stack_boundary(struct bpf_verifier_env *env, int regno, int access_size, bool zero_size_allowed, struct bpf_call_arg_meta *meta) { struct bpf_verifier_state *state = env->cur_state; struct bpf_reg_state *regs = state->regs; int off, i, slot, spi; if (regs[regno].type != PTR_TO_STACK) { /* Allow zero-byte read from NULL, regardless of pointer type */ if (zero_size_allowed && access_size == 0 && register_is_null(regs[regno])) return 0; verbose(env, "R%d type=%s expected=%s\n", regno, reg_type_str[regs[regno].type], reg_type_str[PTR_TO_STACK]); return -EACCES; } /* Only allow fixed-offset stack reads */ if (!tnum_is_const(regs[regno].var_off)) { char tn_buf[48]; tnum_strn(tn_buf, sizeof(tn_buf), regs[regno].var_off); verbose(env, "invalid variable stack read R%d var_off=%s\n", regno, tn_buf); } off = regs[regno].off + regs[regno].var_off.value; if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 || access_size < 0 || (access_size == 0 && !zero_size_allowed)) { verbose(env, "invalid stack type R%d off=%d access_size=%d\n", regno, off, access_size); return -EACCES; } if (env->prog->aux->stack_depth < -off) env->prog->aux->stack_depth = -off; if (meta && meta->raw_mode) { meta->access_size = access_size; meta->regno = regno; return 0; } for (i = 0; i < access_size; i++) { slot = -(off + i) - 1; spi = slot / BPF_REG_SIZE; if (state->allocated_stack <= slot || state->stack[spi].slot_type[slot % BPF_REG_SIZE] != STACK_MISC) { verbose(env, "invalid indirect read from stack off %d+%d size %d\n", off, i, access_size); return -EACCES; } } return 0; } static int check_helper_mem_access(struct bpf_verifier_env *env, int regno, int access_size, bool zero_size_allowed, struct bpf_call_arg_meta *meta) { struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno]; switch (reg->type) { case PTR_TO_PACKET: case PTR_TO_PACKET_META: return check_packet_access(env, regno, reg->off, access_size, zero_size_allowed); case PTR_TO_MAP_VALUE: return check_map_access(env, regno, reg->off, access_size, zero_size_allowed); default: /* scalar_value|ptr_to_stack or invalid ptr */ return check_stack_boundary(env, regno, access_size, zero_size_allowed, meta); } } static int check_func_arg(struct bpf_verifier_env *env, u32 regno, enum bpf_arg_type arg_type, struct bpf_call_arg_meta *meta) { struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno]; enum bpf_reg_type expected_type, type = reg->type; int err = 0; if (arg_type == ARG_DONTCARE) return 0; err = check_reg_arg(env, regno, SRC_OP); if (err) return err; if (arg_type == ARG_ANYTHING) { if (is_pointer_value(env, regno)) { verbose(env, "R%d leaks addr into helper function\n", regno); return -EACCES; } return 0; } if (type_is_pkt_pointer(type) && !may_access_direct_pkt_data(env, meta, BPF_READ)) { verbose(env, "helper access to the packet is not allowed\n"); return -EACCES; } if (arg_type == ARG_PTR_TO_MAP_KEY || arg_type == ARG_PTR_TO_MAP_VALUE) { expected_type = PTR_TO_STACK; if (!type_is_pkt_pointer(type) && type != expected_type) goto err_type; } else if (arg_type == ARG_CONST_SIZE || arg_type == ARG_CONST_SIZE_OR_ZERO) { expected_type = SCALAR_VALUE; if (type != expected_type) goto err_type; } else if (arg_type == ARG_CONST_MAP_PTR) { expected_type = CONST_PTR_TO_MAP; if (type != expected_type) goto err_type; } else if (arg_type == ARG_PTR_TO_CTX) { expected_type = PTR_TO_CTX; if (type != expected_type) goto err_type; } else if (arg_type == ARG_PTR_TO_MEM || arg_type == ARG_PTR_TO_MEM_OR_NULL || arg_type == ARG_PTR_TO_UNINIT_MEM) { expected_type = PTR_TO_STACK; /* One exception here. In case function allows for NULL to be * passed in as argument, it's a SCALAR_VALUE type. Final test * happens during stack boundary checking. */ if (register_is_null(*reg) && arg_type == ARG_PTR_TO_MEM_OR_NULL) /* final test in check_stack_boundary() */; else if (!type_is_pkt_pointer(type) && type != PTR_TO_MAP_VALUE && type != expected_type) goto err_type; meta->raw_mode = arg_type == ARG_PTR_TO_UNINIT_MEM; } else { verbose(env, "unsupported arg_type %d\n", arg_type); return -EFAULT; } if (arg_type == ARG_CONST_MAP_PTR) { /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ meta->map_ptr = reg->map_ptr; } else if (arg_type == ARG_PTR_TO_MAP_KEY) { /* bpf_map_xxx(..., map_ptr, ..., key) call: * check that [key, key + map->key_size) are within * stack limits and initialized */ if (!meta->map_ptr) { /* in function declaration map_ptr must come before * map_key, so that it's verified and known before * we have to check map_key here. Otherwise it means * that kernel subsystem misconfigured verifier */ verbose(env, "invalid map_ptr to access map->key\n"); return -EACCES; } if (type_is_pkt_pointer(type)) err = check_packet_access(env, regno, reg->off, meta->map_ptr->key_size, false); else err = check_stack_boundary(env, regno, meta->map_ptr->key_size, false, NULL); } else if (arg_type == ARG_PTR_TO_MAP_VALUE) { /* bpf_map_xxx(..., map_ptr, ..., value) call: * check [value, value + map->value_size) validity */ if (!meta->map_ptr) { /* kernel subsystem misconfigured verifier */ verbose(env, "invalid map_ptr to access map->value\n"); return -EACCES; } if (type_is_pkt_pointer(type)) err = check_packet_access(env, regno, reg->off, meta->map_ptr->value_size, false); else err = check_stack_boundary(env, regno, meta->map_ptr->value_size, false, NULL); } else if (arg_type == ARG_CONST_SIZE || arg_type == ARG_CONST_SIZE_OR_ZERO) { bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO); /* bpf_xxx(..., buf, len) call will access 'len' bytes * from stack pointer 'buf'. Check it * note: regno == len, regno - 1 == buf */ if (regno == 0) { /* kernel subsystem misconfigured verifier */ verbose(env, "ARG_CONST_SIZE cannot be first argument\n"); return -EACCES; } /* The register is SCALAR_VALUE; the access check * happens using its boundaries. */ if (!tnum_is_const(reg->var_off)) /* For unprivileged variable accesses, disable raw * mode so that the program is required to * initialize all the memory that the helper could * just partially fill up. */ meta = NULL; if (reg->smin_value < 0) { verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n", regno); return -EACCES; } if (reg->umin_value == 0) { err = check_helper_mem_access(env, regno - 1, 0, zero_size_allowed, meta); if (err) return err; } if (reg->umax_value >= BPF_MAX_VAR_SIZ) { verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n", regno); return -EACCES; } err = check_helper_mem_access(env, regno - 1, reg->umax_value, zero_size_allowed, meta); } return err; err_type: verbose(env, "R%d type=%s expected=%s\n", regno, reg_type_str[type], reg_type_str[expected_type]); return -EACCES; } static int check_map_func_compatibility(struct bpf_verifier_env *env, struct bpf_map *map, int func_id) { if (!map) return 0; /* We need a two way check, first is from map perspective ... */ switch (map->map_type) { case BPF_MAP_TYPE_PROG_ARRAY: if (func_id != BPF_FUNC_tail_call) goto error; break; case BPF_MAP_TYPE_PERF_EVENT_ARRAY: if (func_id != BPF_FUNC_perf_event_read && func_id != BPF_FUNC_perf_event_output && func_id != BPF_FUNC_perf_event_read_value) goto error; break; case BPF_MAP_TYPE_STACK_TRACE: if (func_id != BPF_FUNC_get_stackid) goto error; break; case BPF_MAP_TYPE_CGROUP_ARRAY: if (func_id != BPF_FUNC_skb_under_cgroup && func_id != BPF_FUNC_current_task_under_cgroup) goto error; break; /* devmap returns a pointer to a live net_device ifindex that we cannot * allow to be modified from bpf side. So do not allow lookup elements * for now. */ case BPF_MAP_TYPE_DEVMAP: if (func_id != BPF_FUNC_redirect_map) goto error; break; /* Restrict bpf side of cpumap, open when use-cases appear */ case BPF_MAP_TYPE_CPUMAP: if (func_id != BPF_FUNC_redirect_map) goto error; break; case BPF_MAP_TYPE_ARRAY_OF_MAPS: case BPF_MAP_TYPE_HASH_OF_MAPS: if (func_id != BPF_FUNC_map_lookup_elem) goto error; break; case BPF_MAP_TYPE_SOCKMAP: if (func_id != BPF_FUNC_sk_redirect_map && func_id != BPF_FUNC_sock_map_update && func_id != BPF_FUNC_map_delete_elem) goto error; break; default: break; } /* ... and second from the function itself. */ switch (func_id) { case BPF_FUNC_tail_call: if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) goto error; break; case BPF_FUNC_perf_event_read: case BPF_FUNC_perf_event_output: case BPF_FUNC_perf_event_read_value: if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) goto error; break; case BPF_FUNC_get_stackid: if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) goto error; break; case BPF_FUNC_current_task_under_cgroup: case BPF_FUNC_skb_under_cgroup: if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) goto error; break; case BPF_FUNC_redirect_map: if (map->map_type != BPF_MAP_TYPE_DEVMAP && map->map_type != BPF_MAP_TYPE_CPUMAP) goto error; break; case BPF_FUNC_sk_redirect_map: if (map->map_type != BPF_MAP_TYPE_SOCKMAP) goto error; break; case BPF_FUNC_sock_map_update: if (map->map_type != BPF_MAP_TYPE_SOCKMAP) goto error; break; default: break; } return 0; error: verbose(env, "cannot pass map_type %d into func %s#%d\n", map->map_type, func_id_name(func_id), func_id); return -EINVAL; } static int check_raw_mode(const struct bpf_func_proto *fn) { int count = 0; if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM) count++; if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM) count++; if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM) count++; if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM) count++; if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM) count++; return count > 1 ? -EINVAL : 0; } /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] * are now invalid, so turn them into unknown SCALAR_VALUE. */ static void clear_all_pkt_pointers(struct bpf_verifier_env *env) { struct bpf_verifier_state *state = env->cur_state; struct bpf_reg_state *regs = state->regs, *reg; int i; for (i = 0; i < MAX_BPF_REG; i++) if (reg_is_pkt_pointer_any(&regs[i])) mark_reg_unknown(env, regs, i); for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { if (state->stack[i].slot_type[0] != STACK_SPILL) continue; reg = &state->stack[i].spilled_ptr; if (reg_is_pkt_pointer_any(reg)) __mark_reg_unknown(reg); } } static int check_call(struct bpf_verifier_env *env, int func_id, int insn_idx) { const struct bpf_func_proto *fn = NULL; struct bpf_reg_state *regs; struct bpf_call_arg_meta meta; bool changes_data; int i, err; /* find function prototype */ if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) { verbose(env, "invalid func %s#%d\n", func_id_name(func_id), func_id); return -EINVAL; } if (env->ops->get_func_proto) fn = env->ops->get_func_proto(func_id); if (!fn) { verbose(env, "unknown func %s#%d\n", func_id_name(func_id), func_id); return -EINVAL; } /* eBPF programs must be GPL compatible to use GPL-ed functions */ if (!env->prog->gpl_compatible && fn->gpl_only) { verbose(env, "cannot call GPL only function from proprietary program\n"); return -EINVAL; } /* With LD_ABS/IND some JITs save/restore skb from r1. */ changes_data = bpf_helper_changes_pkt_data(fn->func); if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n", func_id_name(func_id), func_id); return -EINVAL; } memset(&meta, 0, sizeof(meta)); meta.pkt_access = fn->pkt_access; /* We only support one arg being in raw mode at the moment, which * is sufficient for the helper functions we have right now. */ err = check_raw_mode(fn); if (err) { verbose(env, "kernel subsystem misconfigured func %s#%d\n", func_id_name(func_id), func_id); return err; } /* check args */ err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta); if (err) return err; err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta); if (err) return err; err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta); if (err) return err; err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta); if (err) return err; err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta); if (err) return err; /* Mark slots with STACK_MISC in case of raw mode, stack offset * is inferred from register state. */ for (i = 0; i < meta.access_size; i++) { err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, BPF_WRITE, -1); if (err) return err; } regs = cur_regs(env); /* reset caller saved regs */ for (i = 0; i < CALLER_SAVED_REGS; i++) { mark_reg_not_init(env, regs, caller_saved[i]); check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); } /* update return register (already marked as written above) */ if (fn->ret_type == RET_INTEGER) { /* sets type to SCALAR_VALUE */ mark_reg_unknown(env, regs, BPF_REG_0); } else if (fn->ret_type == RET_VOID) { regs[BPF_REG_0].type = NOT_INIT; } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL) { struct bpf_insn_aux_data *insn_aux; regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL; /* There is no offset yet applied, variable or fixed */ mark_reg_known_zero(env, regs, BPF_REG_0); regs[BPF_REG_0].off = 0; /* remember map_ptr, so that check_map_access() * can check 'value_size' boundary of memory access * to map element returned from bpf_map_lookup_elem() */ if (meta.map_ptr == NULL) { verbose(env, "kernel subsystem misconfigured verifier\n"); return -EINVAL; } regs[BPF_REG_0].map_ptr = meta.map_ptr; regs[BPF_REG_0].id = ++env->id_gen; insn_aux = &env->insn_aux_data[insn_idx]; if (!insn_aux->map_ptr) insn_aux->map_ptr = meta.map_ptr; else if (insn_aux->map_ptr != meta.map_ptr) insn_aux->map_ptr = BPF_MAP_PTR_POISON; } else { verbose(env, "unknown return type %d of func %s#%d\n", fn->ret_type, func_id_name(func_id), func_id); return -EINVAL; } err = check_map_func_compatibility(env, meta.map_ptr, func_id); if (err) return err; if (changes_data) clear_all_pkt_pointers(env); return 0; } static void coerce_reg_to_32(struct bpf_reg_state *reg) { /* clear high 32 bits */ reg->var_off = tnum_cast(reg->var_off, 4); /* Update bounds */ __update_reg_bounds(reg); } static bool signed_add_overflows(s64 a, s64 b) { /* Do the add in u64, where overflow is well-defined */ s64 res = (s64)((u64)a + (u64)b); if (b < 0) return res > a; return res < a; } static bool signed_sub_overflows(s64 a, s64 b) { /* Do the sub in u64, where overflow is well-defined */ s64 res = (s64)((u64)a - (u64)b); if (b < 0) return res < a; return res > a; } /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. * Caller should also handle BPF_MOV case separately. * If we return -EACCES, caller may want to try again treating pointer as a * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. */ static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn *insn, const struct bpf_reg_state *ptr_reg, const struct bpf_reg_state *off_reg) { struct bpf_reg_state *regs = cur_regs(env), *dst_reg; bool known = tnum_is_const(off_reg->var_off); s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; u8 opcode = BPF_OP(insn->code); u32 dst = insn->dst_reg; dst_reg = &regs[dst]; if (WARN_ON_ONCE(known && (smin_val != smax_val))) { print_verifier_state(env, env->cur_state); verbose(env, "verifier internal error: known but bad sbounds\n"); return -EINVAL; } if (WARN_ON_ONCE(known && (umin_val != umax_val))) { print_verifier_state(env, env->cur_state); verbose(env, "verifier internal error: known but bad ubounds\n"); return -EINVAL; } if (BPF_CLASS(insn->code) != BPF_ALU64) { /* 32-bit ALU ops on pointers produce (meaningless) scalars */ if (!env->allow_ptr_leaks) verbose(env, "R%d 32-bit pointer arithmetic prohibited\n", dst); return -EACCES; } if (ptr_reg->type == PTR_TO_MAP_VALUE_OR_NULL) { if (!env->allow_ptr_leaks) verbose(env, "R%d pointer arithmetic on PTR_TO_MAP_VALUE_OR_NULL prohibited, null-check it first\n", dst); return -EACCES; } if (ptr_reg->type == CONST_PTR_TO_MAP) { if (!env->allow_ptr_leaks) verbose(env, "R%d pointer arithmetic on CONST_PTR_TO_MAP prohibited\n", dst); return -EACCES; } if (ptr_reg->type == PTR_TO_PACKET_END) { if (!env->allow_ptr_leaks) verbose(env, "R%d pointer arithmetic on PTR_TO_PACKET_END prohibited\n", dst); return -EACCES; } /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. * The id may be overwritten later if we create a new variable offset. */ dst_reg->type = ptr_reg->type; dst_reg->id = ptr_reg->id; switch (opcode) { case BPF_ADD: /* We can take a fixed offset as long as it doesn't overflow * the s32 'off' field */ if (known && (ptr_reg->off + smin_val == (s64)(s32)(ptr_reg->off + smin_val))) { /* pointer += K. Accumulate it into fixed offset */ dst_reg->smin_value = smin_ptr; dst_reg->smax_value = smax_ptr; dst_reg->umin_value = umin_ptr; dst_reg->umax_value = umax_ptr; dst_reg->var_off = ptr_reg->var_off; dst_reg->off = ptr_reg->off + smin_val; dst_reg->range = ptr_reg->range; break; } /* A new variable offset is created. Note that off_reg->off * == 0, since it's a scalar. * dst_reg gets the pointer type and since some positive * integer value was added to the pointer, give it a new 'id' * if it's a PTR_TO_PACKET. * this creates a new 'base' pointer, off_reg (variable) gets * added into the variable offset, and we copy the fixed offset * from ptr_reg. */ if (signed_add_overflows(smin_ptr, smin_val) || signed_add_overflows(smax_ptr, smax_val)) { dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value = smin_ptr + smin_val; dst_reg->smax_value = smax_ptr + smax_val; } if (umin_ptr + umin_val < umin_ptr || umax_ptr + umax_val < umax_ptr) { dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { dst_reg->umin_value = umin_ptr + umin_val; dst_reg->umax_value = umax_ptr + umax_val; } dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); dst_reg->off = ptr_reg->off; if (reg_is_pkt_pointer(ptr_reg)) { dst_reg->id = ++env->id_gen; /* something was added to pkt_ptr, set range to zero */ dst_reg->range = 0; } break; case BPF_SUB: if (dst_reg == off_reg) { /* scalar -= pointer. Creates an unknown scalar */ if (!env->allow_ptr_leaks) verbose(env, "R%d tried to subtract pointer from scalar\n", dst); return -EACCES; } /* We don't allow subtraction from FP, because (according to * test_verifier.c test "invalid fp arithmetic", JITs might not * be able to deal with it. */ if (ptr_reg->type == PTR_TO_STACK) { if (!env->allow_ptr_leaks) verbose(env, "R%d subtraction from stack pointer prohibited\n", dst); return -EACCES; } if (known && (ptr_reg->off - smin_val == (s64)(s32)(ptr_reg->off - smin_val))) { /* pointer -= K. Subtract it from fixed offset */ dst_reg->smin_value = smin_ptr; dst_reg->smax_value = smax_ptr; dst_reg->umin_value = umin_ptr; dst_reg->umax_value = umax_ptr; dst_reg->var_off = ptr_reg->var_off; dst_reg->id = ptr_reg->id; dst_reg->off = ptr_reg->off - smin_val; dst_reg->range = ptr_reg->range; break; } /* A new variable offset is created. If the subtrahend is known * nonnegative, then any reg->range we had before is still good. */ if (signed_sub_overflows(smin_ptr, smax_val) || signed_sub_overflows(smax_ptr, smin_val)) { /* Overflow possible, we know nothing */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value = smin_ptr - smax_val; dst_reg->smax_value = smax_ptr - smin_val; } if (umin_ptr < umax_val) { /* Overflow possible, we know nothing */ dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { /* Cannot overflow (as long as bounds are consistent) */ dst_reg->umin_value = umin_ptr - umax_val; dst_reg->umax_value = umax_ptr - umin_val; } dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); dst_reg->off = ptr_reg->off; if (reg_is_pkt_pointer(ptr_reg)) { dst_reg->id = ++env->id_gen; /* something was added to pkt_ptr, set range to zero */ if (smin_val < 0) dst_reg->range = 0; } break; case BPF_AND: case BPF_OR: case BPF_XOR: /* bitwise ops on pointers are troublesome, prohibit for now. * (However, in principle we could allow some cases, e.g. * ptr &= ~3 which would reduce min_value by 3.) */ if (!env->allow_ptr_leaks) verbose(env, "R%d bitwise operator %s on pointer prohibited\n", dst, bpf_alu_string[opcode >> 4]); return -EACCES; default: /* other operators (e.g. MUL,LSH) produce non-pointer results */ if (!env->allow_ptr_leaks) verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", dst, bpf_alu_string[opcode >> 4]); return -EACCES; } __update_reg_bounds(dst_reg); __reg_deduce_bounds(dst_reg); __reg_bound_offset(dst_reg); return 0; } static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn *insn, struct bpf_reg_state *dst_reg, struct bpf_reg_state src_reg) { struct bpf_reg_state *regs = cur_regs(env); u8 opcode = BPF_OP(insn->code); bool src_known, dst_known; s64 smin_val, smax_val; u64 umin_val, umax_val; if (BPF_CLASS(insn->code) != BPF_ALU64) { /* 32-bit ALU ops are (32,32)->64 */ coerce_reg_to_32(dst_reg); coerce_reg_to_32(&src_reg); } smin_val = src_reg.smin_value; smax_val = src_reg.smax_value; umin_val = src_reg.umin_value; umax_val = src_reg.umax_value; src_known = tnum_is_const(src_reg.var_off); dst_known = tnum_is_const(dst_reg->var_off); switch (opcode) { case BPF_ADD: if (signed_add_overflows(dst_reg->smin_value, smin_val) || signed_add_overflows(dst_reg->smax_value, smax_val)) { dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value += smin_val; dst_reg->smax_value += smax_val; } if (dst_reg->umin_value + umin_val < umin_val || dst_reg->umax_value + umax_val < umax_val) { dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { dst_reg->umin_value += umin_val; dst_reg->umax_value += umax_val; } dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); break; case BPF_SUB: if (signed_sub_overflows(dst_reg->smin_value, smax_val) || signed_sub_overflows(dst_reg->smax_value, smin_val)) { /* Overflow possible, we know nothing */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value -= smax_val; dst_reg->smax_value -= smin_val; } if (dst_reg->umin_value < umax_val) { /* Overflow possible, we know nothing */ dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { /* Cannot overflow (as long as bounds are consistent) */ dst_reg->umin_value -= umax_val; dst_reg->umax_value -= umin_val; } dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); break; case BPF_MUL: dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); if (smin_val < 0 || dst_reg->smin_value < 0) { /* Ain't nobody got time to multiply that sign */ __mark_reg_unbounded(dst_reg); __update_reg_bounds(dst_reg); break; } /* Both values are positive, so we can work with unsigned and * copy the result to signed (unless it exceeds S64_MAX). */ if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { /* Potential overflow, we know nothing */ __mark_reg_unbounded(dst_reg); /* (except what we can learn from the var_off) */ __update_reg_bounds(dst_reg); break; } dst_reg->umin_value *= umin_val; dst_reg->umax_value *= umax_val; if (dst_reg->umax_value > S64_MAX) { /* Overflow possible, we know nothing */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value = dst_reg->umin_value; dst_reg->smax_value = dst_reg->umax_value; } break; case BPF_AND: if (src_known && dst_known) { __mark_reg_known(dst_reg, dst_reg->var_off.value & src_reg.var_off.value); break; } /* We get our minimum from the var_off, since that's inherently * bitwise. Our maximum is the minimum of the operands' maxima. */ dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); dst_reg->umin_value = dst_reg->var_off.value; dst_reg->umax_value = min(dst_reg->umax_value, umax_val); if (dst_reg->smin_value < 0 || smin_val < 0) { /* Lose signed bounds when ANDing negative numbers, * ain't nobody got time for that. */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { /* ANDing two positives gives a positive, so safe to * cast result into s64. */ dst_reg->smin_value = dst_reg->umin_value; dst_reg->smax_value = dst_reg->umax_value; } /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_OR: if (src_known && dst_known) { __mark_reg_known(dst_reg, dst_reg->var_off.value | src_reg.var_off.value); break; } /* We get our maximum from the var_off, and our minimum is the * maximum of the operands' minima */ dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); dst_reg->umin_value = max(dst_reg->umin_value, umin_val); dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; if (dst_reg->smin_value < 0 || smin_val < 0) { /* Lose signed bounds when ORing negative numbers, * ain't nobody got time for that. */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { /* ORing two positives gives a positive, so safe to * cast result into s64. */ dst_reg->smin_value = dst_reg->umin_value; dst_reg->smax_value = dst_reg->umax_value; } /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_LSH: if (umax_val > 63) { /* Shifts greater than 63 are undefined. This includes * shifts by a negative number. */ mark_reg_unknown(env, regs, insn->dst_reg); break; } /* We lose all sign bit information (except what we can pick * up from var_off) */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; /* If we might shift our top bit out, then we know nothing */ if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { dst_reg->umin_value <<= umin_val; dst_reg->umax_value <<= umax_val; } if (src_known) dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); else dst_reg->var_off = tnum_lshift(tnum_unknown, umin_val); /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_RSH: if (umax_val > 63) { /* Shifts greater than 63 are undefined. This includes * shifts by a negative number. */ mark_reg_unknown(env, regs, insn->dst_reg); break; } /* BPF_RSH is an unsigned shift, so make the appropriate casts */ if (dst_reg->smin_value < 0) { if (umin_val) { /* Sign bit will be cleared */ dst_reg->smin_value = 0; } else { /* Lost sign bit information */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } } else { dst_reg->smin_value = (u64)(dst_reg->smin_value) >> umax_val; } if (src_known) dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); else dst_reg->var_off = tnum_rshift(tnum_unknown, umin_val); dst_reg->umin_value >>= umax_val; dst_reg->umax_value >>= umin_val; /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; default: mark_reg_unknown(env, regs, insn->dst_reg); break; } __reg_deduce_bounds(dst_reg); __reg_bound_offset(dst_reg); return 0; } /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max * and var_off. */ static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn *insn) { struct bpf_reg_state *regs = cur_regs(env), *dst_reg, *src_reg; struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; u8 opcode = BPF_OP(insn->code); int rc; dst_reg = &regs[insn->dst_reg]; src_reg = NULL; if (dst_reg->type != SCALAR_VALUE) ptr_reg = dst_reg; if (BPF_SRC(insn->code) == BPF_X) { src_reg = &regs[insn->src_reg]; if (src_reg->type != SCALAR_VALUE) { if (dst_reg->type != SCALAR_VALUE) { /* Combining two pointers by any ALU op yields * an arbitrary scalar. */ if (!env->allow_ptr_leaks) { verbose(env, "R%d pointer %s pointer prohibited\n", insn->dst_reg, bpf_alu_string[opcode >> 4]); return -EACCES; } mark_reg_unknown(env, regs, insn->dst_reg); return 0; } else { /* scalar += pointer * This is legal, but we have to reverse our * src/dest handling in computing the range */ rc = adjust_ptr_min_max_vals(env, insn, src_reg, dst_reg); if (rc == -EACCES && env->allow_ptr_leaks) { /* scalar += unknown scalar */ __mark_reg_unknown(&off_reg); return adjust_scalar_min_max_vals( env, insn, dst_reg, off_reg); } return rc; } } else if (ptr_reg) { /* pointer += scalar */ rc = adjust_ptr_min_max_vals(env, insn, dst_reg, src_reg); if (rc == -EACCES && env->allow_ptr_leaks) { /* unknown scalar += scalar */ __mark_reg_unknown(dst_reg); return adjust_scalar_min_max_vals( env, insn, dst_reg, *src_reg); } return rc; } } else { /* Pretend the src is a reg with a known value, since we only * need to be able to read from this state. */ off_reg.type = SCALAR_VALUE; __mark_reg_known(&off_reg, insn->imm); src_reg = &off_reg; if (ptr_reg) { /* pointer += K */ rc = adjust_ptr_min_max_vals(env, insn, ptr_reg, src_reg); if (rc == -EACCES && env->allow_ptr_leaks) { /* unknown scalar += K */ __mark_reg_unknown(dst_reg); return adjust_scalar_min_max_vals( env, insn, dst_reg, off_reg); } return rc; } } /* Got here implies adding two SCALAR_VALUEs */ if (WARN_ON_ONCE(ptr_reg)) { print_verifier_state(env, env->cur_state); verbose(env, "verifier internal error: unexpected ptr_reg\n"); return -EINVAL; } if (WARN_ON(!src_reg)) { print_verifier_state(env, env->cur_state); verbose(env, "verifier internal error: no src_reg\n"); return -EINVAL; } return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); } /* check validity of 32-bit and 64-bit arithmetic operations */ static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) { struct bpf_reg_state *regs = cur_regs(env); u8 opcode = BPF_OP(insn->code); int err; if (opcode == BPF_END || opcode == BPF_NEG) { if (opcode == BPF_NEG) { if (BPF_SRC(insn->code) != 0 || insn->src_reg != BPF_REG_0 || insn->off != 0 || insn->imm != 0) { verbose(env, "BPF_NEG uses reserved fields\n"); return -EINVAL; } } else { if (insn->src_reg != BPF_REG_0 || insn->off != 0 || (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || BPF_CLASS(insn->code) == BPF_ALU64) { verbose(env, "BPF_END uses reserved fields\n"); return -EINVAL; } } /* check src operand */ err = check_reg_arg(env, insn->dst_reg, SRC_OP); if (err) return err; if (is_pointer_value(env, insn->dst_reg)) { verbose(env, "R%d pointer arithmetic prohibited\n", insn->dst_reg); return -EACCES; } /* check dest operand */ err = check_reg_arg(env, insn->dst_reg, DST_OP); if (err) return err; } else if (opcode == BPF_MOV) { if (BPF_SRC(insn->code) == BPF_X) { if (insn->imm != 0 || insn->off != 0) { verbose(env, "BPF_MOV uses reserved fields\n"); return -EINVAL; } /* check src operand */ err = check_reg_arg(env, insn->src_reg, SRC_OP); if (err) return err; } else { if (insn->src_reg != BPF_REG_0 || insn->off != 0) { verbose(env, "BPF_MOV uses reserved fields\n"); return -EINVAL; } } /* check dest operand */ err = check_reg_arg(env, insn->dst_reg, DST_OP); if (err) return err; if (BPF_SRC(insn->code) == BPF_X) { if (BPF_CLASS(insn->code) == BPF_ALU64) { /* case: R1 = R2 * copy register state to dest reg */ regs[insn->dst_reg] = regs[insn->src_reg]; regs[insn->dst_reg].live |= REG_LIVE_WRITTEN; } else { /* R1 = (u32) R2 */ if (is_pointer_value(env, insn->src_reg)) { verbose(env, "R%d partial copy of pointer\n", insn->src_reg); return -EACCES; } mark_reg_unknown(env, regs, insn->dst_reg); /* high 32 bits are known zero. */ regs[insn->dst_reg].var_off = tnum_cast( regs[insn->dst_reg].var_off, 4); __update_reg_bounds(&regs[insn->dst_reg]); } } else { /* case: R = imm * remember the value we stored into this reg */ regs[insn->dst_reg].type = SCALAR_VALUE; __mark_reg_known(regs + insn->dst_reg, insn->imm); } } else if (opcode > BPF_END) { verbose(env, "invalid BPF_ALU opcode %x\n", opcode); return -EINVAL; } else { /* all other ALU ops: and, sub, xor, add, ... */ if (BPF_SRC(insn->code) == BPF_X) { if (insn->imm != 0 || insn->off != 0) { verbose(env, "BPF_ALU uses reserved fields\n"); return -EINVAL; } /* check src1 operand */ err = check_reg_arg(env, insn->src_reg, SRC_OP); if (err) return err; } else { if (insn->src_reg != BPF_REG_0 || insn->off != 0) { verbose(env, "BPF_ALU uses reserved fields\n"); return -EINVAL; } } /* check src2 operand */ err = check_reg_arg(env, insn->dst_reg, SRC_OP); if (err) return err; if ((opcode == BPF_MOD || opcode == BPF_DIV) && BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { verbose(env, "div by zero\n"); return -EINVAL; } if ((opcode == BPF_LSH || opcode == BPF_RSH || opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; if (insn->imm < 0 || insn->imm >= size) { verbose(env, "invalid shift %d\n", insn->imm); return -EINVAL; } } /* check dest operand */ err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); if (err) return err; return adjust_reg_min_max_vals(env, insn); } return 0; } static void find_good_pkt_pointers(struct bpf_verifier_state *state, struct bpf_reg_state *dst_reg, enum bpf_reg_type type, bool range_right_open) { struct bpf_reg_state *regs = state->regs, *reg; u16 new_range; int i; if (dst_reg->off < 0 || (dst_reg->off == 0 && range_right_open)) /* This doesn't give us any range */ return; if (dst_reg->umax_value > MAX_PACKET_OFF || dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF) /* Risk of overflow. For instance, ptr + (1<<63) may be less * than pkt_end, but that's because it's also less than pkt. */ return; new_range = dst_reg->off; if (range_right_open) new_range--; /* Examples for register markings: * * pkt_data in dst register: * * r2 = r3; * r2 += 8; * if (r2 > pkt_end) goto <handle exception> * <access okay> * * r2 = r3; * r2 += 8; * if (r2 < pkt_end) goto <access okay> * <handle exception> * * Where: * r2 == dst_reg, pkt_end == src_reg * r2=pkt(id=n,off=8,r=0) * r3=pkt(id=n,off=0,r=0) * * pkt_data in src register: * * r2 = r3; * r2 += 8; * if (pkt_end >= r2) goto <access okay> * <handle exception> * * r2 = r3; * r2 += 8; * if (pkt_end <= r2) goto <handle exception> * <access okay> * * Where: * pkt_end == dst_reg, r2 == src_reg * r2=pkt(id=n,off=8,r=0) * r3=pkt(id=n,off=0,r=0) * * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) * and [r3, r3 + 8-1) respectively is safe to access depending on * the check. */ /* If our ids match, then we must have the same max_value. And we * don't care about the other reg's fixed offset, since if it's too big * the range won't allow anything. * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16. */ for (i = 0; i < MAX_BPF_REG; i++) if (regs[i].type == type && regs[i].id == dst_reg->id) /* keep the maximum range already checked */ regs[i].range = max(regs[i].range, new_range); for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { if (state->stack[i].slot_type[0] != STACK_SPILL) continue; reg = &state->stack[i].spilled_ptr; if (reg->type == type && reg->id == dst_reg->id) reg->range = max(reg->range, new_range); } } /* Adjusts the register min/max values in the case that the dst_reg is the * variable register that we are working on, and src_reg is a constant or we're * simply doing a BPF_K check. * In JEQ/JNE cases we also adjust the var_off values. */ static void reg_set_min_max(struct bpf_reg_state *true_reg, struct bpf_reg_state *false_reg, u64 val, u8 opcode) { /* If the dst_reg is a pointer, we can't learn anything about its * variable offset from the compare (unless src_reg were a pointer into * the same object, but we don't bother with that. * Since false_reg and true_reg have the same type by construction, we * only need to check one of them for pointerness. */ if (__is_pointer_value(false, false_reg)) return; switch (opcode) { case BPF_JEQ: /* If this is false then we know nothing Jon Snow, but if it is * true then we know for sure. */ __mark_reg_known(true_reg, val); break; case BPF_JNE: /* If this is true we know nothing Jon Snow, but if it is false * we know the value for sure; */ __mark_reg_known(false_reg, val); break; case BPF_JGT: false_reg->umax_value = min(false_reg->umax_value, val); true_reg->umin_value = max(true_reg->umin_value, val + 1); break; case BPF_JSGT: false_reg->smax_value = min_t(s64, false_reg->smax_value, val); true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1); break; case BPF_JLT: false_reg->umin_value = max(false_reg->umin_value, val); true_reg->umax_value = min(true_reg->umax_value, val - 1); break; case BPF_JSLT: false_reg->smin_value = max_t(s64, false_reg->smin_value, val); true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1); break; case BPF_JGE: false_reg->umax_value = min(false_reg->umax_value, val - 1); true_reg->umin_value = max(true_reg->umin_value, val); break; case BPF_JSGE: false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1); true_reg->smin_value = max_t(s64, true_reg->smin_value, val); break; case BPF_JLE: false_reg->umin_value = max(false_reg->umin_value, val + 1); true_reg->umax_value = min(true_reg->umax_value, val); break; case BPF_JSLE: false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1); true_reg->smax_value = min_t(s64, true_reg->smax_value, val); break; default: break; } __reg_deduce_bounds(false_reg); __reg_deduce_bounds(true_reg); /* We might have learned some bits from the bounds. */ __reg_bound_offset(false_reg); __reg_bound_offset(true_reg); /* Intersecting with the old var_off might have improved our bounds * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), * then new var_off is (0; 0x7f...fc) which improves our umax. */ __update_reg_bounds(false_reg); __update_reg_bounds(true_reg); } /* Same as above, but for the case that dst_reg holds a constant and src_reg is * the variable reg. */ static void reg_set_min_max_inv(struct bpf_reg_state *true_reg, struct bpf_reg_state *false_reg, u64 val, u8 opcode) { if (__is_pointer_value(false, false_reg)) return; switch (opcode) { case BPF_JEQ: /* If this is false then we know nothing Jon Snow, but if it is * true then we know for sure. */ __mark_reg_known(true_reg, val); break; case BPF_JNE: /* If this is true we know nothing Jon Snow, but if it is false * we know the value for sure; */ __mark_reg_known(false_reg, val); break; case BPF_JGT: true_reg->umax_value = min(true_reg->umax_value, val - 1); false_reg->umin_value = max(false_reg->umin_value, val); break; case BPF_JSGT: true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1); false_reg->smin_value = max_t(s64, false_reg->smin_value, val); break; case BPF_JLT: true_reg->umin_value = max(true_reg->umin_value, val + 1); false_reg->umax_value = min(false_reg->umax_value, val); break; case BPF_JSLT: true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1); false_reg->smax_value = min_t(s64, false_reg->smax_value, val); break; case BPF_JGE: true_reg->umax_value = min(true_reg->umax_value, val); false_reg->umin_value = max(false_reg->umin_value, val + 1); break; case BPF_JSGE: true_reg->smax_value = min_t(s64, true_reg->smax_value, val); false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1); break; case BPF_JLE: true_reg->umin_value = max(true_reg->umin_value, val); false_reg->umax_value = min(false_reg->umax_value, val - 1); break; case BPF_JSLE: true_reg->smin_value = max_t(s64, true_reg->smin_value, val); false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1); break; default: break; } __reg_deduce_bounds(false_reg); __reg_deduce_bounds(true_reg); /* We might have learned some bits from the bounds. */ __reg_bound_offset(false_reg); __reg_bound_offset(true_reg); /* Intersecting with the old var_off might have improved our bounds * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), * then new var_off is (0; 0x7f...fc) which improves our umax. */ __update_reg_bounds(false_reg); __update_reg_bounds(true_reg); } /* Regs are known to be equal, so intersect their min/max/var_off */ static void __reg_combine_min_max(struct bpf_reg_state *src_reg, struct bpf_reg_state *dst_reg) { src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value, dst_reg->umin_value); src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value, dst_reg->umax_value); src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value, dst_reg->smin_value); src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value, dst_reg->smax_value); src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off, dst_reg->var_off); /* We might have learned new bounds from the var_off. */ __update_reg_bounds(src_reg); __update_reg_bounds(dst_reg); /* We might have learned something about the sign bit. */ __reg_deduce_bounds(src_reg); __reg_deduce_bounds(dst_reg); /* We might have learned some bits from the bounds. */ __reg_bound_offset(src_reg); __reg_bound_offset(dst_reg); /* Intersecting with the old var_off might have improved our bounds * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), * then new var_off is (0; 0x7f...fc) which improves our umax. */ __update_reg_bounds(src_reg); __update_reg_bounds(dst_reg); } static void reg_combine_min_max(struct bpf_reg_state *true_src, struct bpf_reg_state *true_dst, struct bpf_reg_state *false_src, struct bpf_reg_state *false_dst, u8 opcode) { switch (opcode) { case BPF_JEQ: __reg_combine_min_max(true_src, true_dst); break; case BPF_JNE: __reg_combine_min_max(false_src, false_dst); break; } } static void mark_map_reg(struct bpf_reg_state *regs, u32 regno, u32 id, bool is_null) { struct bpf_reg_state *reg = &regs[regno]; if (reg->type == PTR_TO_MAP_VALUE_OR_NULL && reg->id == id) { /* Old offset (both fixed and variable parts) should * have been known-zero, because we don't allow pointer * arithmetic on pointers that might be NULL. */ if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0) || reg->off)) { __mark_reg_known_zero(reg); reg->off = 0; } if (is_null) { reg->type = SCALAR_VALUE; } else if (reg->map_ptr->inner_map_meta) { reg->type = CONST_PTR_TO_MAP; reg->map_ptr = reg->map_ptr->inner_map_meta; } else { reg->type = PTR_TO_MAP_VALUE; } /* We don't need id from this point onwards anymore, thus we * should better reset it, so that state pruning has chances * to take effect. */ reg->id = 0; } } /* The logic is similar to find_good_pkt_pointers(), both could eventually * be folded together at some point. */ static void mark_map_regs(struct bpf_verifier_state *state, u32 regno, bool is_null) { struct bpf_reg_state *regs = state->regs; u32 id = regs[regno].id; int i; for (i = 0; i < MAX_BPF_REG; i++) mark_map_reg(regs, i, id, is_null); for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { if (state->stack[i].slot_type[0] != STACK_SPILL) continue; mark_map_reg(&state->stack[i].spilled_ptr, 0, id, is_null); } } static bool try_match_pkt_pointers(const struct bpf_insn *insn, struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg, struct bpf_verifier_state *this_branch, struct bpf_verifier_state *other_branch) { if (BPF_SRC(insn->code) != BPF_X) return false; switch (BPF_OP(insn->code)) { case BPF_JGT: if ((dst_reg->type == PTR_TO_PACKET && src_reg->type == PTR_TO_PACKET_END) || (dst_reg->type == PTR_TO_PACKET_META && reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ find_good_pkt_pointers(this_branch, dst_reg, dst_reg->type, false); } else if ((dst_reg->type == PTR_TO_PACKET_END && src_reg->type == PTR_TO_PACKET) || (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && src_reg->type == PTR_TO_PACKET_META)) { /* pkt_end > pkt_data', pkt_data > pkt_meta' */ find_good_pkt_pointers(other_branch, src_reg, src_reg->type, true); } else { return false; } break; case BPF_JLT: if ((dst_reg->type == PTR_TO_PACKET && src_reg->type == PTR_TO_PACKET_END) || (dst_reg->type == PTR_TO_PACKET_META && reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ find_good_pkt_pointers(other_branch, dst_reg, dst_reg->type, true); } else if ((dst_reg->type == PTR_TO_PACKET_END && src_reg->type == PTR_TO_PACKET) || (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && src_reg->type == PTR_TO_PACKET_META)) { /* pkt_end < pkt_data', pkt_data > pkt_meta' */ find_good_pkt_pointers(this_branch, src_reg, src_reg->type, false); } else { return false; } break; case BPF_JGE: if ((dst_reg->type == PTR_TO_PACKET && src_reg->type == PTR_TO_PACKET_END) || (dst_reg->type == PTR_TO_PACKET_META && reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ find_good_pkt_pointers(this_branch, dst_reg, dst_reg->type, true); } else if ((dst_reg->type == PTR_TO_PACKET_END && src_reg->type == PTR_TO_PACKET) || (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && src_reg->type == PTR_TO_PACKET_META)) { /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ find_good_pkt_pointers(other_branch, src_reg, src_reg->type, false); } else { return false; } break; case BPF_JLE: if ((dst_reg->type == PTR_TO_PACKET && src_reg->type == PTR_TO_PACKET_END) || (dst_reg->type == PTR_TO_PACKET_META && reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ find_good_pkt_pointers(other_branch, dst_reg, dst_reg->type, false); } else if ((dst_reg->type == PTR_TO_PACKET_END && src_reg->type == PTR_TO_PACKET) || (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && src_reg->type == PTR_TO_PACKET_META)) { /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ find_good_pkt_pointers(this_branch, src_reg, src_reg->type, true); } else { return false; } break; default: return false; } return true; } static int check_cond_jmp_op(struct bpf_verifier_env *env, struct bpf_insn *insn, int *insn_idx) { struct bpf_verifier_state *other_branch, *this_branch = env->cur_state; struct bpf_reg_state *regs = this_branch->regs, *dst_reg; u8 opcode = BPF_OP(insn->code); int err; if (opcode > BPF_JSLE) { verbose(env, "invalid BPF_JMP opcode %x\n", opcode); return -EINVAL; } if (BPF_SRC(insn->code) == BPF_X) { if (insn->imm != 0) { verbose(env, "BPF_JMP uses reserved fields\n"); return -EINVAL; } /* check src1 operand */ err = check_reg_arg(env, insn->src_reg, SRC_OP); if (err) return err; if (is_pointer_value(env, insn->src_reg)) { verbose(env, "R%d pointer comparison prohibited\n", insn->src_reg); return -EACCES; } } else { if (insn->src_reg != BPF_REG_0) { verbose(env, "BPF_JMP uses reserved fields\n"); return -EINVAL; } } /* check src2 operand */ err = check_reg_arg(env, insn->dst_reg, SRC_OP); if (err) return err; dst_reg = &regs[insn->dst_reg]; /* detect if R == 0 where R was initialized to zero earlier */ if (BPF_SRC(insn->code) == BPF_K && (opcode == BPF_JEQ || opcode == BPF_JNE) && dst_reg->type == SCALAR_VALUE && tnum_equals_const(dst_reg->var_off, insn->imm)) { if (opcode == BPF_JEQ) { /* if (imm == imm) goto pc+off; * only follow the goto, ignore fall-through */ *insn_idx += insn->off; return 0; } else { /* if (imm != imm) goto pc+off; * only follow fall-through branch, since * that's where the program will go */ return 0; } } other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx); if (!other_branch) return -EFAULT; /* detect if we are comparing against a constant value so we can adjust * our min/max values for our dst register. * this is only legit if both are scalars (or pointers to the same * object, I suppose, but we don't support that right now), because * otherwise the different base pointers mean the offsets aren't * comparable. */ if (BPF_SRC(insn->code) == BPF_X) { if (dst_reg->type == SCALAR_VALUE && regs[insn->src_reg].type == SCALAR_VALUE) { if (tnum_is_const(regs[insn->src_reg].var_off)) reg_set_min_max(&other_branch->regs[insn->dst_reg], dst_reg, regs[insn->src_reg].var_off.value, opcode); else if (tnum_is_const(dst_reg->var_off)) reg_set_min_max_inv(&other_branch->regs[insn->src_reg], &regs[insn->src_reg], dst_reg->var_off.value, opcode); else if (opcode == BPF_JEQ || opcode == BPF_JNE) /* Comparing for equality, we can combine knowledge */ reg_combine_min_max(&other_branch->regs[insn->src_reg], &other_branch->regs[insn->dst_reg], &regs[insn->src_reg], &regs[insn->dst_reg], opcode); } } else if (dst_reg->type == SCALAR_VALUE) { reg_set_min_max(&other_branch->regs[insn->dst_reg], dst_reg, insn->imm, opcode); } /* detect if R == 0 where R is returned from bpf_map_lookup_elem() */ if (BPF_SRC(insn->code) == BPF_K && insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && dst_reg->type == PTR_TO_MAP_VALUE_OR_NULL) { /* Mark all identical map registers in each branch as either * safe or unknown depending R == 0 or R != 0 conditional. */ mark_map_regs(this_branch, insn->dst_reg, opcode == BPF_JNE); mark_map_regs(other_branch, insn->dst_reg, opcode == BPF_JEQ); } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg], this_branch, other_branch) && is_pointer_value(env, insn->dst_reg)) { verbose(env, "R%d pointer comparison prohibited\n", insn->dst_reg); return -EACCES; } if (env->log.level) print_verifier_state(env, this_branch); return 0; } /* return the map pointer stored inside BPF_LD_IMM64 instruction */ static struct bpf_map *ld_imm64_to_map_ptr(struct bpf_insn *insn) { u64 imm64 = ((u64) (u32) insn[0].imm) | ((u64) (u32) insn[1].imm) << 32; return (struct bpf_map *) (unsigned long) imm64; } /* verify BPF_LD_IMM64 instruction */ static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) { struct bpf_reg_state *regs = cur_regs(env); int err; if (BPF_SIZE(insn->code) != BPF_DW) { verbose(env, "invalid BPF_LD_IMM insn\n"); return -EINVAL; } if (insn->off != 0) { verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); return -EINVAL; } err = check_reg_arg(env, insn->dst_reg, DST_OP); if (err) return err; if (insn->src_reg == 0) { u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; regs[insn->dst_reg].type = SCALAR_VALUE; __mark_reg_known(&regs[insn->dst_reg], imm); return 0; } /* replace_map_fd_with_map_ptr() should have caught bad ld_imm64 */ BUG_ON(insn->src_reg != BPF_PSEUDO_MAP_FD); regs[insn->dst_reg].type = CONST_PTR_TO_MAP; regs[insn->dst_reg].map_ptr = ld_imm64_to_map_ptr(insn); return 0; } static bool may_access_skb(enum bpf_prog_type type) { switch (type) { case BPF_PROG_TYPE_SOCKET_FILTER: case BPF_PROG_TYPE_SCHED_CLS: case BPF_PROG_TYPE_SCHED_ACT: return true; default: return false; } } /* verify safety of LD_ABS|LD_IND instructions: * - they can only appear in the programs where ctx == skb * - since they are wrappers of function calls, they scratch R1-R5 registers, * preserve R6-R9, and store return value into R0 * * Implicit input: * ctx == skb == R6 == CTX * * Explicit input: * SRC == any register * IMM == 32-bit immediate * * Output: * R0 - 8/16/32-bit skb data converted to cpu endianness */ static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) { struct bpf_reg_state *regs = cur_regs(env); u8 mode = BPF_MODE(insn->code); int i, err; if (!may_access_skb(env->prog->type)) { verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); return -EINVAL; } if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || BPF_SIZE(insn->code) == BPF_DW || (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); return -EINVAL; } /* check whether implicit source operand (register R6) is readable */ err = check_reg_arg(env, BPF_REG_6, SRC_OP); if (err) return err; if (regs[BPF_REG_6].type != PTR_TO_CTX) { verbose(env, "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); return -EINVAL; } if (mode == BPF_IND) { /* check explicit source operand */ err = check_reg_arg(env, insn->src_reg, SRC_OP); if (err) return err; } /* reset caller saved regs to unreadable */ for (i = 0; i < CALLER_SAVED_REGS; i++) { mark_reg_not_init(env, regs, caller_saved[i]); check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); } /* mark destination R0 register as readable, since it contains * the value fetched from the packet. * Already marked as written above. */ mark_reg_unknown(env, regs, BPF_REG_0); return 0; } static int check_return_code(struct bpf_verifier_env *env) { struct bpf_reg_state *reg; struct tnum range = tnum_range(0, 1); switch (env->prog->type) { case BPF_PROG_TYPE_CGROUP_SKB: case BPF_PROG_TYPE_CGROUP_SOCK: case BPF_PROG_TYPE_SOCK_OPS: case BPF_PROG_TYPE_CGROUP_DEVICE: break; default: return 0; } reg = cur_regs(env) + BPF_REG_0; if (reg->type != SCALAR_VALUE) { verbose(env, "At program exit the register R0 is not a known value (%s)\n", reg_type_str[reg->type]); return -EINVAL; } if (!tnum_in(range, reg->var_off)) { verbose(env, "At program exit the register R0 "); if (!tnum_is_unknown(reg->var_off)) { char tn_buf[48]; tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); verbose(env, "has value %s", tn_buf); } else { verbose(env, "has unknown scalar value"); } verbose(env, " should have been 0 or 1\n"); return -EINVAL; } return 0; } /* non-recursive DFS pseudo code * 1 procedure DFS-iterative(G,v): * 2 label v as discovered * 3 let S be a stack * 4 S.push(v) * 5 while S is not empty * 6 t <- S.pop() * 7 if t is what we're looking for: * 8 return t * 9 for all edges e in G.adjacentEdges(t) do * 10 if edge e is already labelled * 11 continue with the next edge * 12 w <- G.adjacentVertex(t,e) * 13 if vertex w is not discovered and not explored * 14 label e as tree-edge * 15 label w as discovered * 16 S.push(w) * 17 continue at 5 * 18 else if vertex w is discovered * 19 label e as back-edge * 20 else * 21 // vertex w is explored * 22 label e as forward- or cross-edge * 23 label t as explored * 24 S.pop() * * convention: * 0x10 - discovered * 0x11 - discovered and fall-through edge labelled * 0x12 - discovered and fall-through and branch edges labelled * 0x20 - explored */ enum { DISCOVERED = 0x10, EXPLORED = 0x20, FALLTHROUGH = 1, BRANCH = 2, }; #define STATE_LIST_MARK ((struct bpf_verifier_state_list *) -1L) static int *insn_stack; /* stack of insns to process */ static int cur_stack; /* current stack index */ static int *insn_state; /* t, w, e - match pseudo-code above: * t - index of current instruction * w - next instruction * e - edge */ static int push_insn(int t, int w, int e, struct bpf_verifier_env *env) { if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH)) return 0; if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH)) return 0; if (w < 0 || w >= env->prog->len) { verbose(env, "jump out of range from insn %d to %d\n", t, w); return -EINVAL; } if (e == BRANCH) /* mark branch target for state pruning */ env->explored_states[w] = STATE_LIST_MARK; if (insn_state[w] == 0) { /* tree-edge */ insn_state[t] = DISCOVERED | e; insn_state[w] = DISCOVERED; if (cur_stack >= env->prog->len) return -E2BIG; insn_stack[cur_stack++] = w; return 1; } else if ((insn_state[w] & 0xF0) == DISCOVERED) { verbose(env, "back-edge from insn %d to %d\n", t, w); return -EINVAL; } else if (insn_state[w] == EXPLORED) { /* forward- or cross-edge */ insn_state[t] = DISCOVERED | e; } else { verbose(env, "insn state internal bug\n"); return -EFAULT; } return 0; } /* non-recursive depth-first-search to detect loops in BPF program * loop == back-edge in directed graph */ static int check_cfg(struct bpf_verifier_env *env) { struct bpf_insn *insns = env->prog->insnsi; int insn_cnt = env->prog->len; int ret = 0; int i, t; insn_state = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL); if (!insn_state) return -ENOMEM; insn_stack = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL); if (!insn_stack) { kfree(insn_state); return -ENOMEM; } insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */ insn_stack[0] = 0; /* 0 is the first instruction */ cur_stack = 1; peek_stack: if (cur_stack == 0) goto check_state; t = insn_stack[cur_stack - 1]; if (BPF_CLASS(insns[t].code) == BPF_JMP) { u8 opcode = BPF_OP(insns[t].code); if (opcode == BPF_EXIT) { goto mark_explored; } else if (opcode == BPF_CALL) { ret = push_insn(t, t + 1, FALLTHROUGH, env); if (ret == 1) goto peek_stack; else if (ret < 0) goto err_free; if (t + 1 < insn_cnt) env->explored_states[t + 1] = STATE_LIST_MARK; } else if (opcode == BPF_JA) { if (BPF_SRC(insns[t].code) != BPF_K) { ret = -EINVAL; goto err_free; } /* unconditional jump with single edge */ ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env); if (ret == 1) goto peek_stack; else if (ret < 0) goto err_free; /* tell verifier to check for equivalent states * after every call and jump */ if (t + 1 < insn_cnt) env->explored_states[t + 1] = STATE_LIST_MARK; } else { /* conditional jump with two edges */ env->explored_states[t] = STATE_LIST_MARK; ret = push_insn(t, t + 1, FALLTHROUGH, env); if (ret == 1) goto peek_stack; else if (ret < 0) goto err_free; ret = push_insn(t, t + insns[t].off + 1, BRANCH, env); if (ret == 1) goto peek_stack; else if (ret < 0) goto err_free; } } else { /* all other non-branch instructions with single * fall-through edge */ ret = push_insn(t, t + 1, FALLTHROUGH, env); if (ret == 1) goto peek_stack; else if (ret < 0) goto err_free; } mark_explored: insn_state[t] = EXPLORED; if (cur_stack-- <= 0) { verbose(env, "pop stack internal bug\n"); ret = -EFAULT; goto err_free; } goto peek_stack; check_state: for (i = 0; i < insn_cnt; i++) { if (insn_state[i] != EXPLORED) { verbose(env, "unreachable insn %d\n", i); ret = -EINVAL; goto err_free; } } ret = 0; /* cfg looks good */ err_free: kfree(insn_state); kfree(insn_stack); return ret; } /* check %cur's range satisfies %old's */ static bool range_within(struct bpf_reg_state *old, struct bpf_reg_state *cur) { return old->umin_value <= cur->umin_value && old->umax_value >= cur->umax_value && old->smin_value <= cur->smin_value && old->smax_value >= cur->smax_value; } /* Maximum number of register states that can exist at once */ #define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE) struct idpair { u32 old; u32 cur; }; /* If in the old state two registers had the same id, then they need to have * the same id in the new state as well. But that id could be different from * the old state, so we need to track the mapping from old to new ids. * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent * regs with old id 5 must also have new id 9 for the new state to be safe. But * regs with a different old id could still have new id 9, we don't care about * that. * So we look through our idmap to see if this old id has been seen before. If * so, we require the new id to match; otherwise, we add the id pair to the map. */ static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap) { unsigned int i; for (i = 0; i < ID_MAP_SIZE; i++) { if (!idmap[i].old) { /* Reached an empty slot; haven't seen this id before */ idmap[i].old = old_id; idmap[i].cur = cur_id; return true; } if (idmap[i].old == old_id) return idmap[i].cur == cur_id; } /* We ran out of idmap slots, which should be impossible */ WARN_ON_ONCE(1); return false; } /* Returns true if (rold safe implies rcur safe) */ static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur, struct idpair *idmap) { if (!(rold->live & REG_LIVE_READ)) /* explored state didn't use this */ return true; if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, live)) == 0) return true; if (rold->type == NOT_INIT) /* explored state can't have used this */ return true; if (rcur->type == NOT_INIT) return false; switch (rold->type) { case SCALAR_VALUE: if (rcur->type == SCALAR_VALUE) { /* new val must satisfy old val knowledge */ return range_within(rold, rcur) && tnum_in(rold->var_off, rcur->var_off); } else { /* if we knew anything about the old value, we're not * equal, because we can't know anything about the * scalar value of the pointer in the new value. */ return rold->umin_value == 0 && rold->umax_value == U64_MAX && rold->smin_value == S64_MIN && rold->smax_value == S64_MAX && tnum_is_unknown(rold->var_off); } case PTR_TO_MAP_VALUE: /* If the new min/max/var_off satisfy the old ones and * everything else matches, we are OK. * We don't care about the 'id' value, because nothing * uses it for PTR_TO_MAP_VALUE (only for ..._OR_NULL) */ return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && range_within(rold, rcur) && tnum_in(rold->var_off, rcur->var_off); case PTR_TO_MAP_VALUE_OR_NULL: /* a PTR_TO_MAP_VALUE could be safe to use as a * PTR_TO_MAP_VALUE_OR_NULL into the same map. * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL- * checked, doing so could have affected others with the same * id, and we can't check for that because we lost the id when * we converted to a PTR_TO_MAP_VALUE. */ if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL) return false; if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id))) return false; /* Check our ids match any regs they're supposed to */ return check_ids(rold->id, rcur->id, idmap); case PTR_TO_PACKET_META: case PTR_TO_PACKET: if (rcur->type != rold->type) return false; /* We must have at least as much range as the old ptr * did, so that any accesses which were safe before are * still safe. This is true even if old range < old off, * since someone could have accessed through (ptr - k), or * even done ptr -= k in a register, to get a safe access. */ if (rold->range > rcur->range) return false; /* If the offsets don't match, we can't trust our alignment; * nor can we be sure that we won't fall out of range. */ if (rold->off != rcur->off) return false; /* id relations must be preserved */ if (rold->id && !check_ids(rold->id, rcur->id, idmap)) return false; /* new val must satisfy old val knowledge */ return range_within(rold, rcur) && tnum_in(rold->var_off, rcur->var_off); case PTR_TO_CTX: case CONST_PTR_TO_MAP: case PTR_TO_STACK: case PTR_TO_PACKET_END: /* Only valid matches are exact, which memcmp() above * would have accepted */ default: /* Don't know what's going on, just say it's not safe */ return false; } /* Shouldn't get here; if we do, say it's not safe */ WARN_ON_ONCE(1); return false; } static bool stacksafe(struct bpf_verifier_state *old, struct bpf_verifier_state *cur, struct idpair *idmap) { int i, spi; /* if explored stack has more populated slots than current stack * such stacks are not equivalent */ if (old->allocated_stack > cur->allocated_stack) return false; /* walk slots of the explored stack and ignore any additional * slots in the current stack, since explored(safe) state * didn't use them */ for (i = 0; i < old->allocated_stack; i++) { spi = i / BPF_REG_SIZE; if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID) continue; if (old->stack[spi].slot_type[i % BPF_REG_SIZE] != cur->stack[spi].slot_type[i % BPF_REG_SIZE]) /* Ex: old explored (safe) state has STACK_SPILL in * this stack slot, but current has has STACK_MISC -> * this verifier states are not equivalent, * return false to continue verification of this path */ return false; if (i % BPF_REG_SIZE) continue; if (old->stack[spi].slot_type[0] != STACK_SPILL) continue; if (!regsafe(&old->stack[spi].spilled_ptr, &cur->stack[spi].spilled_ptr, idmap)) /* when explored and current stack slot are both storing * spilled registers, check that stored pointers types * are the same as well. * Ex: explored safe path could have stored * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8} * but current path has stored: * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16} * such verifier states are not equivalent. * return false to continue verification of this path */ return false; } return true; } /* compare two verifier states * * all states stored in state_list are known to be valid, since * verifier reached 'bpf_exit' instruction through them * * this function is called when verifier exploring different branches of * execution popped from the state stack. If it sees an old state that has * more strict register state and more strict stack state then this execution * branch doesn't need to be explored further, since verifier already * concluded that more strict state leads to valid finish. * * Therefore two states are equivalent if register state is more conservative * and explored stack state is more conservative than the current one. * Example: * explored current * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) * * In other words if current stack state (one being explored) has more * valid slots than old one that already passed validation, it means * the verifier can stop exploring and conclude that current state is valid too * * Similarly with registers. If explored state has register type as invalid * whereas register type in current state is meaningful, it means that * the current state will reach 'bpf_exit' instruction safely */ static bool states_equal(struct bpf_verifier_env *env, struct bpf_verifier_state *old, struct bpf_verifier_state *cur) { struct idpair *idmap; bool ret = false; int i; idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL); /* If we failed to allocate the idmap, just say it's not safe */ if (!idmap) return false; for (i = 0; i < MAX_BPF_REG; i++) { if (!regsafe(&old->regs[i], &cur->regs[i], idmap)) goto out_free; } if (!stacksafe(old, cur, idmap)) goto out_free; ret = true; out_free: kfree(idmap); return ret; } /* A write screens off any subsequent reads; but write marks come from the * straight-line code between a state and its parent. When we arrive at a * jump target (in the first iteration of the propagate_liveness() loop), * we didn't arrive by the straight-line code, so read marks in state must * propagate to parent regardless of state's write marks. */ static bool do_propagate_liveness(const struct bpf_verifier_state *state, struct bpf_verifier_state *parent) { bool writes = parent == state->parent; /* Observe write marks */ bool touched = false; /* any changes made? */ int i; if (!parent) return touched; /* Propagate read liveness of registers... */ BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG); /* We don't need to worry about FP liveness because it's read-only */ for (i = 0; i < BPF_REG_FP; i++) { if (parent->regs[i].live & REG_LIVE_READ) continue; if (writes && (state->regs[i].live & REG_LIVE_WRITTEN)) continue; if (state->regs[i].live & REG_LIVE_READ) { parent->regs[i].live |= REG_LIVE_READ; touched = true; } } /* ... and stack slots */ for (i = 0; i < state->allocated_stack / BPF_REG_SIZE && i < parent->allocated_stack / BPF_REG_SIZE; i++) { if (parent->stack[i].slot_type[0] != STACK_SPILL) continue; if (state->stack[i].slot_type[0] != STACK_SPILL) continue; if (parent->stack[i].spilled_ptr.live & REG_LIVE_READ) continue; if (writes && (state->stack[i].spilled_ptr.live & REG_LIVE_WRITTEN)) continue; if (state->stack[i].spilled_ptr.live & REG_LIVE_READ) { parent->stack[i].spilled_ptr.live |= REG_LIVE_READ; touched = true; } } return touched; } /* "parent" is "a state from which we reach the current state", but initially * it is not the state->parent (i.e. "the state whose straight-line code leads * to the current state"), instead it is the state that happened to arrive at * a (prunable) equivalent of the current state. See comment above * do_propagate_liveness() for consequences of this. * This function is just a more efficient way of calling mark_reg_read() or * mark_stack_slot_read() on each reg in "parent" that is read in "state", * though it requires that parent != state->parent in the call arguments. */ static void propagate_liveness(const struct bpf_verifier_state *state, struct bpf_verifier_state *parent) { while (do_propagate_liveness(state, parent)) { /* Something changed, so we need to feed those changes onward */ state = parent; parent = state->parent; } } static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) { struct bpf_verifier_state_list *new_sl; struct bpf_verifier_state_list *sl; struct bpf_verifier_state *cur = env->cur_state; int i, err; sl = env->explored_states[insn_idx]; if (!sl) /* this 'insn_idx' instruction wasn't marked, so we will not * be doing state search here */ return 0; while (sl != STATE_LIST_MARK) { if (states_equal(env, &sl->state, cur)) { /* reached equivalent register/stack state, * prune the search. * Registers read by the continuation are read by us. * If we have any write marks in env->cur_state, they * will prevent corresponding reads in the continuation * from reaching our parent (an explored_state). Our * own state will get the read marks recorded, but * they'll be immediately forgotten as we're pruning * this state and will pop a new one. */ propagate_liveness(&sl->state, cur); return 1; } sl = sl->next; } /* there were no equivalent states, remember current one. * technically the current state is not proven to be safe yet, * but it will either reach bpf_exit (which means it's safe) or * it will be rejected. Since there are no loops, we won't be * seeing this 'insn_idx' instruction again on the way to bpf_exit */ new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL); if (!new_sl) return -ENOMEM; /* add new state to the head of linked list */ err = copy_verifier_state(&new_sl->state, cur); if (err) { free_verifier_state(&new_sl->state, false); kfree(new_sl); return err; } new_sl->next = env->explored_states[insn_idx]; env->explored_states[insn_idx] = new_sl; /* connect new state to parentage chain */ cur->parent = &new_sl->state; /* clear write marks in current state: the writes we did are not writes * our child did, so they don't screen off its reads from us. * (There are no read marks in current state, because reads always mark * their parent and current state never has children yet. Only * explored_states can get read marks.) */ for (i = 0; i < BPF_REG_FP; i++) cur->regs[i].live = REG_LIVE_NONE; for (i = 0; i < cur->allocated_stack / BPF_REG_SIZE; i++) if (cur->stack[i].slot_type[0] == STACK_SPILL) cur->stack[i].spilled_ptr.live = REG_LIVE_NONE; return 0; } static int ext_analyzer_insn_hook(struct bpf_verifier_env *env, int insn_idx, int prev_insn_idx) { if (env->dev_ops && env->dev_ops->insn_hook) return env->dev_ops->insn_hook(env, insn_idx, prev_insn_idx); return 0; } static int do_check(struct bpf_verifier_env *env) { struct bpf_verifier_state *state; struct bpf_insn *insns = env->prog->insnsi; struct bpf_reg_state *regs; int insn_cnt = env->prog->len; int insn_idx, prev_insn_idx = 0; int insn_processed = 0; bool do_print_state = false; state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL); if (!state) return -ENOMEM; env->cur_state = state; init_reg_state(env, state->regs); state->parent = NULL; insn_idx = 0; for (;;) { struct bpf_insn *insn; u8 class; int err; if (insn_idx >= insn_cnt) { verbose(env, "invalid insn idx %d insn_cnt %d\n", insn_idx, insn_cnt); return -EFAULT; } insn = &insns[insn_idx]; class = BPF_CLASS(insn->code); if (++insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { verbose(env, "BPF program is too large. Processed %d insn\n", insn_processed); return -E2BIG; } err = is_state_visited(env, insn_idx); if (err < 0) return err; if (err == 1) { /* found equivalent state, can prune the search */ if (env->log.level) { if (do_print_state) verbose(env, "\nfrom %d to %d: safe\n", prev_insn_idx, insn_idx); else verbose(env, "%d: safe\n", insn_idx); } goto process_bpf_exit; } if (need_resched()) cond_resched(); if (env->log.level > 1 || (env->log.level && do_print_state)) { if (env->log.level > 1) verbose(env, "%d:", insn_idx); else verbose(env, "\nfrom %d to %d:", prev_insn_idx, insn_idx); print_verifier_state(env, state); do_print_state = false; } if (env->log.level) { verbose(env, "%d: ", insn_idx); print_bpf_insn(verbose, env, insn, env->allow_ptr_leaks); } err = ext_analyzer_insn_hook(env, insn_idx, prev_insn_idx); if (err) return err; regs = cur_regs(env); env->insn_aux_data[insn_idx].seen = true; if (class == BPF_ALU || class == BPF_ALU64) { err = check_alu_op(env, insn); if (err) return err; } else if (class == BPF_LDX) { enum bpf_reg_type *prev_src_type, src_reg_type; /* check for reserved fields is already done */ /* check src operand */ err = check_reg_arg(env, insn->src_reg, SRC_OP); if (err) return err; err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); if (err) return err; src_reg_type = regs[insn->src_reg].type; /* check that memory (src_reg + off) is readable, * the state of dst_reg will be updated by this func */ err = check_mem_access(env, insn_idx, insn->src_reg, insn->off, BPF_SIZE(insn->code), BPF_READ, insn->dst_reg); if (err) return err; prev_src_type = &env->insn_aux_data[insn_idx].ptr_type; if (*prev_src_type == NOT_INIT) { /* saw a valid insn * dst_reg = *(u32 *)(src_reg + off) * save type to validate intersecting paths */ *prev_src_type = src_reg_type; } else if (src_reg_type != *prev_src_type && (src_reg_type == PTR_TO_CTX || *prev_src_type == PTR_TO_CTX)) { /* ABuser program is trying to use the same insn * dst_reg = *(u32*) (src_reg + off) * with different pointer types: * src_reg == ctx in one branch and * src_reg == stack|map in some other branch. * Reject it. */ verbose(env, "same insn cannot be used with different pointers\n"); return -EINVAL; } } else if (class == BPF_STX) { enum bpf_reg_type *prev_dst_type, dst_reg_type; if (BPF_MODE(insn->code) == BPF_XADD) { err = check_xadd(env, insn_idx, insn); if (err) return err; insn_idx++; continue; } /* check src1 operand */ err = check_reg_arg(env, insn->src_reg, SRC_OP); if (err) return err; /* check src2 operand */ err = check_reg_arg(env, insn->dst_reg, SRC_OP); if (err) return err; dst_reg_type = regs[insn->dst_reg].type; /* check that memory (dst_reg + off) is writeable */ err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, BPF_SIZE(insn->code), BPF_WRITE, insn->src_reg); if (err) return err; prev_dst_type = &env->insn_aux_data[insn_idx].ptr_type; if (*prev_dst_type == NOT_INIT) { *prev_dst_type = dst_reg_type; } else if (dst_reg_type != *prev_dst_type && (dst_reg_type == PTR_TO_CTX || *prev_dst_type == PTR_TO_CTX)) { verbose(env, "same insn cannot be used with different pointers\n"); return -EINVAL; } } else if (class == BPF_ST) { if (BPF_MODE(insn->code) != BPF_MEM || insn->src_reg != BPF_REG_0) { verbose(env, "BPF_ST uses reserved fields\n"); return -EINVAL; } /* check src operand */ err = check_reg_arg(env, insn->dst_reg, SRC_OP); if (err) return err; /* check that memory (dst_reg + off) is writeable */ err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, BPF_SIZE(insn->code), BPF_WRITE, -1); if (err) return err; } else if (class == BPF_JMP) { u8 opcode = BPF_OP(insn->code); if (opcode == BPF_CALL) { if (BPF_SRC(insn->code) != BPF_K || insn->off != 0 || insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0) { verbose(env, "BPF_CALL uses reserved fields\n"); return -EINVAL; } err = check_call(env, insn->imm, insn_idx); if (err) return err; } else if (opcode == BPF_JA) { if (BPF_SRC(insn->code) != BPF_K || insn->imm != 0 || insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0) { verbose(env, "BPF_JA uses reserved fields\n"); return -EINVAL; } insn_idx += insn->off + 1; continue; } else if (opcode == BPF_EXIT) { if (BPF_SRC(insn->code) != BPF_K || insn->imm != 0 || insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0) { verbose(env, "BPF_EXIT uses reserved fields\n"); return -EINVAL; } /* eBPF calling convetion is such that R0 is used * to return the value from eBPF program. * Make sure that it's readable at this time * of bpf_exit, which means that program wrote * something into it earlier */ err = check_reg_arg(env, BPF_REG_0, SRC_OP); if (err) return err; if (is_pointer_value(env, BPF_REG_0)) { verbose(env, "R0 leaks addr as return value\n"); return -EACCES; } err = check_return_code(env); if (err) return err; process_bpf_exit: err = pop_stack(env, &prev_insn_idx, &insn_idx); if (err < 0) { if (err != -ENOENT) return err; break; } else { do_print_state = true; continue; } } else { err = check_cond_jmp_op(env, insn, &insn_idx); if (err) return err; } } else if (class == BPF_LD) { u8 mode = BPF_MODE(insn->code); if (mode == BPF_ABS || mode == BPF_IND) { err = check_ld_abs(env, insn); if (err) return err; } else if (mode == BPF_IMM) { err = check_ld_imm(env, insn); if (err) return err; insn_idx++; env->insn_aux_data[insn_idx].seen = true; } else { verbose(env, "invalid BPF_LD mode\n"); return -EINVAL; } } else { verbose(env, "unknown insn class %d\n", class); return -EINVAL; } insn_idx++; } verbose(env, "processed %d insns, stack depth %d\n", insn_processed, env->prog->aux->stack_depth); return 0; } static int check_map_prealloc(struct bpf_map *map) { return (map->map_type != BPF_MAP_TYPE_HASH && map->map_type != BPF_MAP_TYPE_PERCPU_HASH && map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) || !(map->map_flags & BPF_F_NO_PREALLOC); } static int check_map_prog_compatibility(struct bpf_verifier_env *env, struct bpf_map *map, struct bpf_prog *prog) { /* Make sure that BPF_PROG_TYPE_PERF_EVENT programs only use * preallocated hash maps, since doing memory allocation * in overflow_handler can crash depending on where nmi got * triggered. */ if (prog->type == BPF_PROG_TYPE_PERF_EVENT) { if (!check_map_prealloc(map)) { verbose(env, "perf_event programs can only use preallocated hash map\n"); return -EINVAL; } if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta)) { verbose(env, "perf_event programs can only use preallocated inner hash map\n"); return -EINVAL; } } return 0; } /* look for pseudo eBPF instructions that access map FDs and * replace them with actual map pointers */ static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env) { struct bpf_insn *insn = env->prog->insnsi; int insn_cnt = env->prog->len; int i, j, err; err = bpf_prog_calc_tag(env->prog); if (err) return err; for (i = 0; i < insn_cnt; i++, insn++) { if (BPF_CLASS(insn->code) == BPF_LDX && (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) { verbose(env, "BPF_LDX uses reserved fields\n"); return -EINVAL; } if (BPF_CLASS(insn->code) == BPF_STX && ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) { verbose(env, "BPF_STX uses reserved fields\n"); return -EINVAL; } if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { struct bpf_map *map; struct fd f; if (i == insn_cnt - 1 || insn[1].code != 0 || insn[1].dst_reg != 0 || insn[1].src_reg != 0 || insn[1].off != 0) { verbose(env, "invalid bpf_ld_imm64 insn\n"); return -EINVAL; } if (insn->src_reg == 0) /* valid generic load 64-bit imm */ goto next_insn; if (insn->src_reg != BPF_PSEUDO_MAP_FD) { verbose(env, "unrecognized bpf_ld_imm64 insn\n"); return -EINVAL; } f = fdget(insn->imm); map = __bpf_map_get(f); if (IS_ERR(map)) { verbose(env, "fd %d is not pointing to valid bpf_map\n", insn->imm); return PTR_ERR(map); } err = check_map_prog_compatibility(env, map, env->prog); if (err) { fdput(f); return err; } /* store map pointer inside BPF_LD_IMM64 instruction */ insn[0].imm = (u32) (unsigned long) map; insn[1].imm = ((u64) (unsigned long) map) >> 32; /* check whether we recorded this map already */ for (j = 0; j < env->used_map_cnt; j++) if (env->used_maps[j] == map) { fdput(f); goto next_insn; } if (env->used_map_cnt >= MAX_USED_MAPS) { fdput(f); return -E2BIG; } /* hold the map. If the program is rejected by verifier, * the map will be released by release_maps() or it * will be used by the valid program until it's unloaded * and all maps are released in free_bpf_prog_info() */ map = bpf_map_inc(map, false); if (IS_ERR(map)) { fdput(f); return PTR_ERR(map); } env->used_maps[env->used_map_cnt++] = map; fdput(f); next_insn: insn++; i++; } } /* now all pseudo BPF_LD_IMM64 instructions load valid * 'struct bpf_map *' into a register instead of user map_fd. * These pointers will be used later by verifier to validate map access. */ return 0; } /* drop refcnt of maps used by the rejected program */ static void release_maps(struct bpf_verifier_env *env) { int i; for (i = 0; i < env->used_map_cnt; i++) bpf_map_put(env->used_maps[i]); } /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) { struct bpf_insn *insn = env->prog->insnsi; int insn_cnt = env->prog->len; int i; for (i = 0; i < insn_cnt; i++, insn++) if (insn->code == (BPF_LD | BPF_IMM | BPF_DW)) insn->src_reg = 0; } /* single env->prog->insni[off] instruction was replaced with the range * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying * [0, off) and [off, end) to new locations, so the patched range stays zero */ static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len, u32 off, u32 cnt) { struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data; int i; if (cnt == 1) return 0; new_data = vzalloc(sizeof(struct bpf_insn_aux_data) * prog_len); if (!new_data) return -ENOMEM; memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); memcpy(new_data + off + cnt - 1, old_data + off, sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); for (i = off; i < off + cnt - 1; i++) new_data[i].seen = true; env->insn_aux_data = new_data; vfree(old_data); return 0; } static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off, const struct bpf_insn *patch, u32 len) { struct bpf_prog *new_prog; new_prog = bpf_patch_insn_single(env->prog, off, patch, len); if (!new_prog) return NULL; if (adjust_insn_aux_data(env, new_prog->len, off, len)) return NULL; return new_prog; } /* The verifier does more data flow analysis than llvm and will not explore * branches that are dead at run time. Malicious programs can have dead code * too. Therefore replace all dead at-run-time code with nops. */ static void sanitize_dead_code(struct bpf_verifier_env *env) { struct bpf_insn_aux_data *aux_data = env->insn_aux_data; struct bpf_insn nop = BPF_MOV64_REG(BPF_REG_0, BPF_REG_0); struct bpf_insn *insn = env->prog->insnsi; const int insn_cnt = env->prog->len; int i; for (i = 0; i < insn_cnt; i++) { if (aux_data[i].seen) continue; memcpy(insn + i, &nop, sizeof(nop)); } } /* convert load instructions that access fields of 'struct __sk_buff' * into sequence of instructions that access fields of 'struct sk_buff' */ static int convert_ctx_accesses(struct bpf_verifier_env *env) { const struct bpf_verifier_ops *ops = env->ops; int i, cnt, size, ctx_field_size, delta = 0; const int insn_cnt = env->prog->len; struct bpf_insn insn_buf[16], *insn; struct bpf_prog *new_prog; enum bpf_access_type type; bool is_narrower_load; u32 target_size; if (ops->gen_prologue) { cnt = ops->gen_prologue(insn_buf, env->seen_direct_write, env->prog); if (cnt >= ARRAY_SIZE(insn_buf)) { verbose(env, "bpf verifier is misconfigured\n"); return -EINVAL; } else if (cnt) { new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); if (!new_prog) return -ENOMEM; env->prog = new_prog; delta += cnt - 1; } } if (!ops->convert_ctx_access) return 0; insn = env->prog->insnsi + delta; for (i = 0; i < insn_cnt; i++, insn++) { if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) || insn->code == (BPF_LDX | BPF_MEM | BPF_H) || insn->code == (BPF_LDX | BPF_MEM | BPF_W) || insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) type = BPF_READ; else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) || insn->code == (BPF_STX | BPF_MEM | BPF_H) || insn->code == (BPF_STX | BPF_MEM | BPF_W) || insn->code == (BPF_STX | BPF_MEM | BPF_DW)) type = BPF_WRITE; else continue; if (env->insn_aux_data[i + delta].ptr_type != PTR_TO_CTX) continue; ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size; size = BPF_LDST_BYTES(insn); /* If the read access is a narrower load of the field, * convert to a 4/8-byte load, to minimum program type specific * convert_ctx_access changes. If conversion is successful, * we will apply proper mask to the result. */ is_narrower_load = size < ctx_field_size; if (is_narrower_load) { u32 off = insn->off; u8 size_code; if (type == BPF_WRITE) { verbose(env, "bpf verifier narrow ctx access misconfigured\n"); return -EINVAL; } size_code = BPF_H; if (ctx_field_size == 4) size_code = BPF_W; else if (ctx_field_size == 8) size_code = BPF_DW; insn->off = off & ~(ctx_field_size - 1); insn->code = BPF_LDX | BPF_MEM | size_code; } target_size = 0; cnt = ops->convert_ctx_access(type, insn, insn_buf, env->prog, &target_size); if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) || (ctx_field_size && !target_size)) { verbose(env, "bpf verifier is misconfigured\n"); return -EINVAL; } if (is_narrower_load && size < target_size) { if (ctx_field_size <= 4) insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, (1 << size * 8) - 1); else insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg, (1 << size * 8) - 1); } new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); if (!new_prog) return -ENOMEM; delta += cnt - 1; /* keep walking new program and skip insns we just inserted */ env->prog = new_prog; insn = new_prog->insnsi + i + delta; } return 0; } /* fixup insn->imm field of bpf_call instructions * and inline eligible helpers as explicit sequence of BPF instructions * * this function is called after eBPF program passed verification */ static int fixup_bpf_calls(struct bpf_verifier_env *env) { struct bpf_prog *prog = env->prog; struct bpf_insn *insn = prog->insnsi; const struct bpf_func_proto *fn; const int insn_cnt = prog->len; struct bpf_insn insn_buf[16]; struct bpf_prog *new_prog; struct bpf_map *map_ptr; int i, cnt, delta = 0; for (i = 0; i < insn_cnt; i++, insn++) { if (insn->code != (BPF_JMP | BPF_CALL)) continue; if (insn->imm == BPF_FUNC_get_route_realm) prog->dst_needed = 1; if (insn->imm == BPF_FUNC_get_prandom_u32) bpf_user_rnd_init_once(); if (insn->imm == BPF_FUNC_tail_call) { /* If we tail call into other programs, we * cannot make any assumptions since they can * be replaced dynamically during runtime in * the program array. */ prog->cb_access = 1; env->prog->aux->stack_depth = MAX_BPF_STACK; /* mark bpf_tail_call as different opcode to avoid * conditional branch in the interpeter for every normal * call and to prevent accidental JITing by JIT compiler * that doesn't support bpf_tail_call yet */ insn->imm = 0; insn->code = BPF_JMP | BPF_TAIL_CALL; continue; } /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup * handlers are currently limited to 64 bit only. */ if (ebpf_jit_enabled() && BITS_PER_LONG == 64 && insn->imm == BPF_FUNC_map_lookup_elem) { map_ptr = env->insn_aux_data[i + delta].map_ptr; if (map_ptr == BPF_MAP_PTR_POISON || !map_ptr->ops->map_gen_lookup) goto patch_call_imm; cnt = map_ptr->ops->map_gen_lookup(map_ptr, insn_buf); if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { verbose(env, "bpf verifier is misconfigured\n"); return -EINVAL; } new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); if (!new_prog) return -ENOMEM; delta += cnt - 1; /* keep walking new program and skip insns we just inserted */ env->prog = prog = new_prog; insn = new_prog->insnsi + i + delta; continue; } if (insn->imm == BPF_FUNC_redirect_map) { /* Note, we cannot use prog directly as imm as subsequent * rewrites would still change the prog pointer. The only * stable address we can use is aux, which also works with * prog clones during blinding. */ u64 addr = (unsigned long)prog->aux; struct bpf_insn r4_ld[] = { BPF_LD_IMM64(BPF_REG_4, addr), *insn, }; cnt = ARRAY_SIZE(r4_ld); new_prog = bpf_patch_insn_data(env, i + delta, r4_ld, cnt); if (!new_prog) return -ENOMEM; delta += cnt - 1; env->prog = prog = new_prog; insn = new_prog->insnsi + i + delta; } patch_call_imm: fn = env->ops->get_func_proto(insn->imm); /* all functions that have prototype and verifier allowed * programs to call them, must be real in-kernel functions */ if (!fn->func) { verbose(env, "kernel subsystem misconfigured func %s#%d\n", func_id_name(insn->imm), insn->imm); return -EFAULT; } insn->imm = fn->func - __bpf_call_base; } return 0; } static void free_states(struct bpf_verifier_env *env) { struct bpf_verifier_state_list *sl, *sln; int i; if (!env->explored_states) return; for (i = 0; i < env->prog->len; i++) { sl = env->explored_states[i]; if (sl) while (sl != STATE_LIST_MARK) { sln = sl->next; free_verifier_state(&sl->state, false); kfree(sl); sl = sln; } } kfree(env->explored_states); } int bpf_check(struct bpf_prog **prog, union bpf_attr *attr) { struct bpf_verifier_env *env; struct bpf_verifer_log *log; int ret = -EINVAL; /* no program is valid */ if (ARRAY_SIZE(bpf_verifier_ops) == 0) return -EINVAL; /* 'struct bpf_verifier_env' can be global, but since it's not small, * allocate/free it every time bpf_check() is called */ env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL); if (!env) return -ENOMEM; log = &env->log; env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) * (*prog)->len); ret = -ENOMEM; if (!env->insn_aux_data) goto err_free_env; env->prog = *prog; env->ops = bpf_verifier_ops[env->prog->type]; /* grab the mutex to protect few globals used by verifier */ mutex_lock(&bpf_verifier_lock); if (attr->log_level || attr->log_buf || attr->log_size) { /* user requested verbose verifier output * and supplied buffer to store the verification trace */ log->level = attr->log_level; log->ubuf = (char __user *) (unsigned long) attr->log_buf; log->len_total = attr->log_size; ret = -EINVAL; /* log attributes have to be sane */ if (log->len_total < 128 || log->len_total > UINT_MAX >> 8 || !log->level || !log->ubuf) goto err_unlock; } env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) env->strict_alignment = true; if (env->prog->aux->offload) { ret = bpf_prog_offload_verifier_prep(env); if (ret) goto err_unlock; } ret = replace_map_fd_with_map_ptr(env); if (ret < 0) goto skip_full_check; env->explored_states = kcalloc(env->prog->len, sizeof(struct bpf_verifier_state_list *), GFP_USER); ret = -ENOMEM; if (!env->explored_states) goto skip_full_check; ret = check_cfg(env); if (ret < 0) goto skip_full_check; env->allow_ptr_leaks = capable(CAP_SYS_ADMIN); ret = do_check(env); if (env->cur_state) { free_verifier_state(env->cur_state, true); env->cur_state = NULL; } skip_full_check: while (!pop_stack(env, NULL, NULL)); free_states(env); if (ret == 0) sanitize_dead_code(env); if (ret == 0) /* program is valid, convert *(u32*)(ctx + off) accesses */ ret = convert_ctx_accesses(env); if (ret == 0) ret = fixup_bpf_calls(env); if (log->level && bpf_verifier_log_full(log)) ret = -ENOSPC; if (log->level && !log->ubuf) { ret = -EFAULT; goto err_release_maps; } if (ret == 0 && env->used_map_cnt) { /* if program passed verifier, update used_maps in bpf_prog_info */ env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, sizeof(env->used_maps[0]), GFP_KERNEL); if (!env->prog->aux->used_maps) { ret = -ENOMEM; goto err_release_maps; } memcpy(env->prog->aux->used_maps, env->used_maps, sizeof(env->used_maps[0]) * env->used_map_cnt); env->prog->aux->used_map_cnt = env->used_map_cnt; /* program is valid. Convert pseudo bpf_ld_imm64 into generic * bpf_ld_imm64 instructions */ convert_pseudo_ld_imm64(env); } err_release_maps: if (!env->prog->aux->used_maps) /* if we didn't copy map pointers into bpf_prog_info, release * them now. Otherwise free_bpf_prog_info() will release them. */ release_maps(env); *prog = env->prog; err_unlock: mutex_unlock(&bpf_verifier_lock); vfree(env->insn_aux_data); err_free_env: kfree(env); return ret; }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_2984_0
crossvul-cpp_data_bad_2947_1
/* * parser.c : an XML 1.0 parser, namespaces and validity support are mostly * implemented on top of the SAX interfaces * * References: * The XML specification: * http://www.w3.org/TR/REC-xml * Original 1.0 version: * http://www.w3.org/TR/1998/REC-xml-19980210 * XML second edition working draft * http://www.w3.org/TR/2000/WD-xml-2e-20000814 * * Okay this is a big file, the parser core is around 7000 lines, then it * is followed by the progressive parser top routines, then the various * high level APIs to call the parser and a few miscellaneous functions. * A number of helper functions and deprecated ones have been moved to * parserInternals.c to reduce this file size. * As much as possible the functions are associated with their relative * production in the XML specification. A few productions defining the * different ranges of character are actually implanted either in * parserInternals.h or parserInternals.c * The DOM tree build is realized from the default SAX callbacks in * the module SAX.c. * The routines doing the validation checks are in valid.c and called either * from the SAX callbacks or as standalone functions using a preparsed * document. * * See Copyright for the status of this software. * * daniel@veillard.com */ #define IN_LIBXML #include "libxml.h" #if defined(WIN32) && !defined (__CYGWIN__) #define XML_DIR_SEP '\\' #else #define XML_DIR_SEP '/' #endif #include <stdlib.h> #include <limits.h> #include <string.h> #include <stdarg.h> #include <stddef.h> #include <libxml/xmlmemory.h> #include <libxml/threads.h> #include <libxml/globals.h> #include <libxml/tree.h> #include <libxml/parser.h> #include <libxml/parserInternals.h> #include <libxml/valid.h> #include <libxml/entities.h> #include <libxml/xmlerror.h> #include <libxml/encoding.h> #include <libxml/xmlIO.h> #include <libxml/uri.h> #ifdef LIBXML_CATALOG_ENABLED #include <libxml/catalog.h> #endif #ifdef LIBXML_SCHEMAS_ENABLED #include <libxml/xmlschemastypes.h> #include <libxml/relaxng.h> #endif #ifdef HAVE_CTYPE_H #include <ctype.h> #endif #ifdef HAVE_STDLIB_H #include <stdlib.h> #endif #ifdef HAVE_SYS_STAT_H #include <sys/stat.h> #endif #ifdef HAVE_FCNTL_H #include <fcntl.h> #endif #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef HAVE_ZLIB_H #include <zlib.h> #endif #ifdef HAVE_LZMA_H #include <lzma.h> #endif #include "buf.h" #include "enc.h" static void xmlFatalErr(xmlParserCtxtPtr ctxt, xmlParserErrors error, const char *info); static xmlParserCtxtPtr xmlCreateEntityParserCtxtInternal(const xmlChar *URL, const xmlChar *ID, const xmlChar *base, xmlParserCtxtPtr pctx); static void xmlHaltParser(xmlParserCtxtPtr ctxt); /************************************************************************ * * * Arbitrary limits set in the parser. See XML_PARSE_HUGE * * * ************************************************************************/ #define XML_PARSER_BIG_ENTITY 1000 #define XML_PARSER_LOT_ENTITY 5000 /* * XML_PARSER_NON_LINEAR is the threshold where the ratio of parsed entity * replacement over the size in byte of the input indicates that you have * and eponential behaviour. A value of 10 correspond to at least 3 entity * replacement per byte of input. */ #define XML_PARSER_NON_LINEAR 10 /* * xmlParserEntityCheck * * Function to check non-linear entity expansion behaviour * This is here to detect and stop exponential linear entity expansion * This is not a limitation of the parser but a safety * boundary feature. It can be disabled with the XML_PARSE_HUGE * parser option. */ static int xmlParserEntityCheck(xmlParserCtxtPtr ctxt, size_t size, xmlEntityPtr ent, size_t replacement) { size_t consumed = 0; if ((ctxt == NULL) || (ctxt->options & XML_PARSE_HUGE)) return (0); if (ctxt->lastError.code == XML_ERR_ENTITY_LOOP) return (1); /* * This may look absurd but is needed to detect * entities problems */ if ((ent != NULL) && (ent->etype != XML_INTERNAL_PREDEFINED_ENTITY) && (ent->content != NULL) && (ent->checked == 0) && (ctxt->errNo != XML_ERR_ENTITY_LOOP)) { unsigned long oldnbent = ctxt->nbentities; xmlChar *rep; ent->checked = 1; ++ctxt->depth; rep = xmlStringDecodeEntities(ctxt, ent->content, XML_SUBSTITUTE_REF, 0, 0, 0); --ctxt->depth; if (ctxt->errNo == XML_ERR_ENTITY_LOOP) { ent->content[0] = 0; } ent->checked = (ctxt->nbentities - oldnbent + 1) * 2; if (rep != NULL) { if (xmlStrchr(rep, '<')) ent->checked |= 1; xmlFree(rep); rep = NULL; } } if (replacement != 0) { if (replacement < XML_MAX_TEXT_LENGTH) return(0); /* * If the volume of entity copy reaches 10 times the * amount of parsed data and over the large text threshold * then that's very likely to be an abuse. */ if (ctxt->input != NULL) { consumed = ctxt->input->consumed + (ctxt->input->cur - ctxt->input->base); } consumed += ctxt->sizeentities; if (replacement < XML_PARSER_NON_LINEAR * consumed) return(0); } else if (size != 0) { /* * Do the check based on the replacement size of the entity */ if (size < XML_PARSER_BIG_ENTITY) return(0); /* * A limit on the amount of text data reasonably used */ if (ctxt->input != NULL) { consumed = ctxt->input->consumed + (ctxt->input->cur - ctxt->input->base); } consumed += ctxt->sizeentities; if ((size < XML_PARSER_NON_LINEAR * consumed) && (ctxt->nbentities * 3 < XML_PARSER_NON_LINEAR * consumed)) return (0); } else if (ent != NULL) { /* * use the number of parsed entities in the replacement */ size = ent->checked / 2; /* * The amount of data parsed counting entities size only once */ if (ctxt->input != NULL) { consumed = ctxt->input->consumed + (ctxt->input->cur - ctxt->input->base); } consumed += ctxt->sizeentities; /* * Check the density of entities for the amount of data * knowing an entity reference will take at least 3 bytes */ if (size * 3 < consumed * XML_PARSER_NON_LINEAR) return (0); } else { /* * strange we got no data for checking */ if (((ctxt->lastError.code != XML_ERR_UNDECLARED_ENTITY) && (ctxt->lastError.code != XML_WAR_UNDECLARED_ENTITY)) || (ctxt->nbentities <= 10000)) return (0); } xmlFatalErr(ctxt, XML_ERR_ENTITY_LOOP, NULL); return (1); } /** * xmlParserMaxDepth: * * arbitrary depth limit for the XML documents that we allow to * process. This is not a limitation of the parser but a safety * boundary feature. It can be disabled with the XML_PARSE_HUGE * parser option. */ unsigned int xmlParserMaxDepth = 256; #define SAX2 1 #define XML_PARSER_BIG_BUFFER_SIZE 300 #define XML_PARSER_BUFFER_SIZE 100 #define SAX_COMPAT_MODE BAD_CAST "SAX compatibility mode document" /** * XML_PARSER_CHUNK_SIZE * * When calling GROW that's the minimal amount of data * the parser expected to have received. It is not a hard * limit but an optimization when reading strings like Names * It is not strictly needed as long as inputs available characters * are followed by 0, which should be provided by the I/O level */ #define XML_PARSER_CHUNK_SIZE 100 /* * List of XML prefixed PI allowed by W3C specs */ static const char *xmlW3CPIs[] = { "xml-stylesheet", "xml-model", NULL }; /* DEPR void xmlParserHandleReference(xmlParserCtxtPtr ctxt); */ static xmlEntityPtr xmlParseStringPEReference(xmlParserCtxtPtr ctxt, const xmlChar **str); static xmlParserErrors xmlParseExternalEntityPrivate(xmlDocPtr doc, xmlParserCtxtPtr oldctxt, xmlSAXHandlerPtr sax, void *user_data, int depth, const xmlChar *URL, const xmlChar *ID, xmlNodePtr *list); static int xmlCtxtUseOptionsInternal(xmlParserCtxtPtr ctxt, int options, const char *encoding); #ifdef LIBXML_LEGACY_ENABLED static void xmlAddEntityReference(xmlEntityPtr ent, xmlNodePtr firstNode, xmlNodePtr lastNode); #endif /* LIBXML_LEGACY_ENABLED */ static xmlParserErrors xmlParseBalancedChunkMemoryInternal(xmlParserCtxtPtr oldctxt, const xmlChar *string, void *user_data, xmlNodePtr *lst); static int xmlLoadEntityContent(xmlParserCtxtPtr ctxt, xmlEntityPtr entity); /************************************************************************ * * * Some factorized error routines * * * ************************************************************************/ /** * xmlErrAttributeDup: * @ctxt: an XML parser context * @prefix: the attribute prefix * @localname: the attribute localname * * Handle a redefinition of attribute error */ static void xmlErrAttributeDup(xmlParserCtxtPtr ctxt, const xmlChar * prefix, const xmlChar * localname) { if ((ctxt != NULL) && (ctxt->disableSAX != 0) && (ctxt->instate == XML_PARSER_EOF)) return; if (ctxt != NULL) ctxt->errNo = XML_ERR_ATTRIBUTE_REDEFINED; if (prefix == NULL) __xmlRaiseError(NULL, NULL, NULL, ctxt, NULL, XML_FROM_PARSER, XML_ERR_ATTRIBUTE_REDEFINED, XML_ERR_FATAL, NULL, 0, (const char *) localname, NULL, NULL, 0, 0, "Attribute %s redefined\n", localname); else __xmlRaiseError(NULL, NULL, NULL, ctxt, NULL, XML_FROM_PARSER, XML_ERR_ATTRIBUTE_REDEFINED, XML_ERR_FATAL, NULL, 0, (const char *) prefix, (const char *) localname, NULL, 0, 0, "Attribute %s:%s redefined\n", prefix, localname); if (ctxt != NULL) { ctxt->wellFormed = 0; if (ctxt->recovery == 0) ctxt->disableSAX = 1; } } /** * xmlFatalErr: * @ctxt: an XML parser context * @error: the error number * @extra: extra information string * * Handle a fatal parser error, i.e. violating Well-Formedness constraints */ static void xmlFatalErr(xmlParserCtxtPtr ctxt, xmlParserErrors error, const char *info) { const char *errmsg; if ((ctxt != NULL) && (ctxt->disableSAX != 0) && (ctxt->instate == XML_PARSER_EOF)) return; switch (error) { case XML_ERR_INVALID_HEX_CHARREF: errmsg = "CharRef: invalid hexadecimal value"; break; case XML_ERR_INVALID_DEC_CHARREF: errmsg = "CharRef: invalid decimal value"; break; case XML_ERR_INVALID_CHARREF: errmsg = "CharRef: invalid value"; break; case XML_ERR_INTERNAL_ERROR: errmsg = "internal error"; break; case XML_ERR_PEREF_AT_EOF: errmsg = "PEReference at end of document"; break; case XML_ERR_PEREF_IN_PROLOG: errmsg = "PEReference in prolog"; break; case XML_ERR_PEREF_IN_EPILOG: errmsg = "PEReference in epilog"; break; case XML_ERR_PEREF_NO_NAME: errmsg = "PEReference: no name"; break; case XML_ERR_PEREF_SEMICOL_MISSING: errmsg = "PEReference: expecting ';'"; break; case XML_ERR_ENTITY_LOOP: errmsg = "Detected an entity reference loop"; break; case XML_ERR_ENTITY_NOT_STARTED: errmsg = "EntityValue: \" or ' expected"; break; case XML_ERR_ENTITY_PE_INTERNAL: errmsg = "PEReferences forbidden in internal subset"; break; case XML_ERR_ENTITY_NOT_FINISHED: errmsg = "EntityValue: \" or ' expected"; break; case XML_ERR_ATTRIBUTE_NOT_STARTED: errmsg = "AttValue: \" or ' expected"; break; case XML_ERR_LT_IN_ATTRIBUTE: errmsg = "Unescaped '<' not allowed in attributes values"; break; case XML_ERR_LITERAL_NOT_STARTED: errmsg = "SystemLiteral \" or ' expected"; break; case XML_ERR_LITERAL_NOT_FINISHED: errmsg = "Unfinished System or Public ID \" or ' expected"; break; case XML_ERR_MISPLACED_CDATA_END: errmsg = "Sequence ']]>' not allowed in content"; break; case XML_ERR_URI_REQUIRED: errmsg = "SYSTEM or PUBLIC, the URI is missing"; break; case XML_ERR_PUBID_REQUIRED: errmsg = "PUBLIC, the Public Identifier is missing"; break; case XML_ERR_HYPHEN_IN_COMMENT: errmsg = "Comment must not contain '--' (double-hyphen)"; break; case XML_ERR_PI_NOT_STARTED: errmsg = "xmlParsePI : no target name"; break; case XML_ERR_RESERVED_XML_NAME: errmsg = "Invalid PI name"; break; case XML_ERR_NOTATION_NOT_STARTED: errmsg = "NOTATION: Name expected here"; break; case XML_ERR_NOTATION_NOT_FINISHED: errmsg = "'>' required to close NOTATION declaration"; break; case XML_ERR_VALUE_REQUIRED: errmsg = "Entity value required"; break; case XML_ERR_URI_FRAGMENT: errmsg = "Fragment not allowed"; break; case XML_ERR_ATTLIST_NOT_STARTED: errmsg = "'(' required to start ATTLIST enumeration"; break; case XML_ERR_NMTOKEN_REQUIRED: errmsg = "NmToken expected in ATTLIST enumeration"; break; case XML_ERR_ATTLIST_NOT_FINISHED: errmsg = "')' required to finish ATTLIST enumeration"; break; case XML_ERR_MIXED_NOT_STARTED: errmsg = "MixedContentDecl : '|' or ')*' expected"; break; case XML_ERR_PCDATA_REQUIRED: errmsg = "MixedContentDecl : '#PCDATA' expected"; break; case XML_ERR_ELEMCONTENT_NOT_STARTED: errmsg = "ContentDecl : Name or '(' expected"; break; case XML_ERR_ELEMCONTENT_NOT_FINISHED: errmsg = "ContentDecl : ',' '|' or ')' expected"; break; case XML_ERR_PEREF_IN_INT_SUBSET: errmsg = "PEReference: forbidden within markup decl in internal subset"; break; case XML_ERR_GT_REQUIRED: errmsg = "expected '>'"; break; case XML_ERR_CONDSEC_INVALID: errmsg = "XML conditional section '[' expected"; break; case XML_ERR_EXT_SUBSET_NOT_FINISHED: errmsg = "Content error in the external subset"; break; case XML_ERR_CONDSEC_INVALID_KEYWORD: errmsg = "conditional section INCLUDE or IGNORE keyword expected"; break; case XML_ERR_CONDSEC_NOT_FINISHED: errmsg = "XML conditional section not closed"; break; case XML_ERR_XMLDECL_NOT_STARTED: errmsg = "Text declaration '<?xml' required"; break; case XML_ERR_XMLDECL_NOT_FINISHED: errmsg = "parsing XML declaration: '?>' expected"; break; case XML_ERR_EXT_ENTITY_STANDALONE: errmsg = "external parsed entities cannot be standalone"; break; case XML_ERR_ENTITYREF_SEMICOL_MISSING: errmsg = "EntityRef: expecting ';'"; break; case XML_ERR_DOCTYPE_NOT_FINISHED: errmsg = "DOCTYPE improperly terminated"; break; case XML_ERR_LTSLASH_REQUIRED: errmsg = "EndTag: '</' not found"; break; case XML_ERR_EQUAL_REQUIRED: errmsg = "expected '='"; break; case XML_ERR_STRING_NOT_CLOSED: errmsg = "String not closed expecting \" or '"; break; case XML_ERR_STRING_NOT_STARTED: errmsg = "String not started expecting ' or \""; break; case XML_ERR_ENCODING_NAME: errmsg = "Invalid XML encoding name"; break; case XML_ERR_STANDALONE_VALUE: errmsg = "standalone accepts only 'yes' or 'no'"; break; case XML_ERR_DOCUMENT_EMPTY: errmsg = "Document is empty"; break; case XML_ERR_DOCUMENT_END: errmsg = "Extra content at the end of the document"; break; case XML_ERR_NOT_WELL_BALANCED: errmsg = "chunk is not well balanced"; break; case XML_ERR_EXTRA_CONTENT: errmsg = "extra content at the end of well balanced chunk"; break; case XML_ERR_VERSION_MISSING: errmsg = "Malformed declaration expecting version"; break; case XML_ERR_NAME_TOO_LONG: errmsg = "Name too long use XML_PARSE_HUGE option"; break; #if 0 case: errmsg = ""; break; #endif default: errmsg = "Unregistered error message"; } if (ctxt != NULL) ctxt->errNo = error; if (info == NULL) { __xmlRaiseError(NULL, NULL, NULL, ctxt, NULL, XML_FROM_PARSER, error, XML_ERR_FATAL, NULL, 0, info, NULL, NULL, 0, 0, "%s\n", errmsg); } else { __xmlRaiseError(NULL, NULL, NULL, ctxt, NULL, XML_FROM_PARSER, error, XML_ERR_FATAL, NULL, 0, info, NULL, NULL, 0, 0, "%s: %s\n", errmsg, info); } if (ctxt != NULL) { ctxt->wellFormed = 0; if (ctxt->recovery == 0) ctxt->disableSAX = 1; } } /** * xmlFatalErrMsg: * @ctxt: an XML parser context * @error: the error number * @msg: the error message * * Handle a fatal parser error, i.e. violating Well-Formedness constraints */ static void LIBXML_ATTR_FORMAT(3,0) xmlFatalErrMsg(xmlParserCtxtPtr ctxt, xmlParserErrors error, const char *msg) { if ((ctxt != NULL) && (ctxt->disableSAX != 0) && (ctxt->instate == XML_PARSER_EOF)) return; if (ctxt != NULL) ctxt->errNo = error; __xmlRaiseError(NULL, NULL, NULL, ctxt, NULL, XML_FROM_PARSER, error, XML_ERR_FATAL, NULL, 0, NULL, NULL, NULL, 0, 0, "%s", msg); if (ctxt != NULL) { ctxt->wellFormed = 0; if (ctxt->recovery == 0) ctxt->disableSAX = 1; } } /** * xmlWarningMsg: * @ctxt: an XML parser context * @error: the error number * @msg: the error message * @str1: extra data * @str2: extra data * * Handle a warning. */ static void LIBXML_ATTR_FORMAT(3,0) xmlWarningMsg(xmlParserCtxtPtr ctxt, xmlParserErrors error, const char *msg, const xmlChar *str1, const xmlChar *str2) { xmlStructuredErrorFunc schannel = NULL; if ((ctxt != NULL) && (ctxt->disableSAX != 0) && (ctxt->instate == XML_PARSER_EOF)) return; if ((ctxt != NULL) && (ctxt->sax != NULL) && (ctxt->sax->initialized == XML_SAX2_MAGIC)) schannel = ctxt->sax->serror; if (ctxt != NULL) { __xmlRaiseError(schannel, (ctxt->sax) ? ctxt->sax->warning : NULL, ctxt->userData, ctxt, NULL, XML_FROM_PARSER, error, XML_ERR_WARNING, NULL, 0, (const char *) str1, (const char *) str2, NULL, 0, 0, msg, (const char *) str1, (const char *) str2); } else { __xmlRaiseError(schannel, NULL, NULL, ctxt, NULL, XML_FROM_PARSER, error, XML_ERR_WARNING, NULL, 0, (const char *) str1, (const char *) str2, NULL, 0, 0, msg, (const char *) str1, (const char *) str2); } } /** * xmlValidityError: * @ctxt: an XML parser context * @error: the error number * @msg: the error message * @str1: extra data * * Handle a validity error. */ static void LIBXML_ATTR_FORMAT(3,0) xmlValidityError(xmlParserCtxtPtr ctxt, xmlParserErrors error, const char *msg, const xmlChar *str1, const xmlChar *str2) { xmlStructuredErrorFunc schannel = NULL; if ((ctxt != NULL) && (ctxt->disableSAX != 0) && (ctxt->instate == XML_PARSER_EOF)) return; if (ctxt != NULL) { ctxt->errNo = error; if ((ctxt->sax != NULL) && (ctxt->sax->initialized == XML_SAX2_MAGIC)) schannel = ctxt->sax->serror; } if (ctxt != NULL) { __xmlRaiseError(schannel, ctxt->vctxt.error, ctxt->vctxt.userData, ctxt, NULL, XML_FROM_DTD, error, XML_ERR_ERROR, NULL, 0, (const char *) str1, (const char *) str2, NULL, 0, 0, msg, (const char *) str1, (const char *) str2); ctxt->valid = 0; } else { __xmlRaiseError(schannel, NULL, NULL, ctxt, NULL, XML_FROM_DTD, error, XML_ERR_ERROR, NULL, 0, (const char *) str1, (const char *) str2, NULL, 0, 0, msg, (const char *) str1, (const char *) str2); } } /** * xmlFatalErrMsgInt: * @ctxt: an XML parser context * @error: the error number * @msg: the error message * @val: an integer value * * Handle a fatal parser error, i.e. violating Well-Formedness constraints */ static void LIBXML_ATTR_FORMAT(3,0) xmlFatalErrMsgInt(xmlParserCtxtPtr ctxt, xmlParserErrors error, const char *msg, int val) { if ((ctxt != NULL) && (ctxt->disableSAX != 0) && (ctxt->instate == XML_PARSER_EOF)) return; if (ctxt != NULL) ctxt->errNo = error; __xmlRaiseError(NULL, NULL, NULL, ctxt, NULL, XML_FROM_PARSER, error, XML_ERR_FATAL, NULL, 0, NULL, NULL, NULL, val, 0, msg, val); if (ctxt != NULL) { ctxt->wellFormed = 0; if (ctxt->recovery == 0) ctxt->disableSAX = 1; } } /** * xmlFatalErrMsgStrIntStr: * @ctxt: an XML parser context * @error: the error number * @msg: the error message * @str1: an string info * @val: an integer value * @str2: an string info * * Handle a fatal parser error, i.e. violating Well-Formedness constraints */ static void LIBXML_ATTR_FORMAT(3,0) xmlFatalErrMsgStrIntStr(xmlParserCtxtPtr ctxt, xmlParserErrors error, const char *msg, const xmlChar *str1, int val, const xmlChar *str2) { if ((ctxt != NULL) && (ctxt->disableSAX != 0) && (ctxt->instate == XML_PARSER_EOF)) return; if (ctxt != NULL) ctxt->errNo = error; __xmlRaiseError(NULL, NULL, NULL, ctxt, NULL, XML_FROM_PARSER, error, XML_ERR_FATAL, NULL, 0, (const char *) str1, (const char *) str2, NULL, val, 0, msg, str1, val, str2); if (ctxt != NULL) { ctxt->wellFormed = 0; if (ctxt->recovery == 0) ctxt->disableSAX = 1; } } /** * xmlFatalErrMsgStr: * @ctxt: an XML parser context * @error: the error number * @msg: the error message * @val: a string value * * Handle a fatal parser error, i.e. violating Well-Formedness constraints */ static void LIBXML_ATTR_FORMAT(3,0) xmlFatalErrMsgStr(xmlParserCtxtPtr ctxt, xmlParserErrors error, const char *msg, const xmlChar * val) { if ((ctxt != NULL) && (ctxt->disableSAX != 0) && (ctxt->instate == XML_PARSER_EOF)) return; if (ctxt != NULL) ctxt->errNo = error; __xmlRaiseError(NULL, NULL, NULL, ctxt, NULL, XML_FROM_PARSER, error, XML_ERR_FATAL, NULL, 0, (const char *) val, NULL, NULL, 0, 0, msg, val); if (ctxt != NULL) { ctxt->wellFormed = 0; if (ctxt->recovery == 0) ctxt->disableSAX = 1; } } /** * xmlErrMsgStr: * @ctxt: an XML parser context * @error: the error number * @msg: the error message * @val: a string value * * Handle a non fatal parser error */ static void LIBXML_ATTR_FORMAT(3,0) xmlErrMsgStr(xmlParserCtxtPtr ctxt, xmlParserErrors error, const char *msg, const xmlChar * val) { if ((ctxt != NULL) && (ctxt->disableSAX != 0) && (ctxt->instate == XML_PARSER_EOF)) return; if (ctxt != NULL) ctxt->errNo = error; __xmlRaiseError(NULL, NULL, NULL, ctxt, NULL, XML_FROM_PARSER, error, XML_ERR_ERROR, NULL, 0, (const char *) val, NULL, NULL, 0, 0, msg, val); } /** * xmlNsErr: * @ctxt: an XML parser context * @error: the error number * @msg: the message * @info1: extra information string * @info2: extra information string * * Handle a fatal parser error, i.e. violating Well-Formedness constraints */ static void LIBXML_ATTR_FORMAT(3,0) xmlNsErr(xmlParserCtxtPtr ctxt, xmlParserErrors error, const char *msg, const xmlChar * info1, const xmlChar * info2, const xmlChar * info3) { if ((ctxt != NULL) && (ctxt->disableSAX != 0) && (ctxt->instate == XML_PARSER_EOF)) return; if (ctxt != NULL) ctxt->errNo = error; __xmlRaiseError(NULL, NULL, NULL, ctxt, NULL, XML_FROM_NAMESPACE, error, XML_ERR_ERROR, NULL, 0, (const char *) info1, (const char *) info2, (const char *) info3, 0, 0, msg, info1, info2, info3); if (ctxt != NULL) ctxt->nsWellFormed = 0; } /** * xmlNsWarn * @ctxt: an XML parser context * @error: the error number * @msg: the message * @info1: extra information string * @info2: extra information string * * Handle a namespace warning error */ static void LIBXML_ATTR_FORMAT(3,0) xmlNsWarn(xmlParserCtxtPtr ctxt, xmlParserErrors error, const char *msg, const xmlChar * info1, const xmlChar * info2, const xmlChar * info3) { if ((ctxt != NULL) && (ctxt->disableSAX != 0) && (ctxt->instate == XML_PARSER_EOF)) return; __xmlRaiseError(NULL, NULL, NULL, ctxt, NULL, XML_FROM_NAMESPACE, error, XML_ERR_WARNING, NULL, 0, (const char *) info1, (const char *) info2, (const char *) info3, 0, 0, msg, info1, info2, info3); } /************************************************************************ * * * Library wide options * * * ************************************************************************/ /** * xmlHasFeature: * @feature: the feature to be examined * * Examines if the library has been compiled with a given feature. * * Returns a non-zero value if the feature exist, otherwise zero. * Returns zero (0) if the feature does not exist or an unknown * unknown feature is requested, non-zero otherwise. */ int xmlHasFeature(xmlFeature feature) { switch (feature) { case XML_WITH_THREAD: #ifdef LIBXML_THREAD_ENABLED return(1); #else return(0); #endif case XML_WITH_TREE: #ifdef LIBXML_TREE_ENABLED return(1); #else return(0); #endif case XML_WITH_OUTPUT: #ifdef LIBXML_OUTPUT_ENABLED return(1); #else return(0); #endif case XML_WITH_PUSH: #ifdef LIBXML_PUSH_ENABLED return(1); #else return(0); #endif case XML_WITH_READER: #ifdef LIBXML_READER_ENABLED return(1); #else return(0); #endif case XML_WITH_PATTERN: #ifdef LIBXML_PATTERN_ENABLED return(1); #else return(0); #endif case XML_WITH_WRITER: #ifdef LIBXML_WRITER_ENABLED return(1); #else return(0); #endif case XML_WITH_SAX1: #ifdef LIBXML_SAX1_ENABLED return(1); #else return(0); #endif case XML_WITH_FTP: #ifdef LIBXML_FTP_ENABLED return(1); #else return(0); #endif case XML_WITH_HTTP: #ifdef LIBXML_HTTP_ENABLED return(1); #else return(0); #endif case XML_WITH_VALID: #ifdef LIBXML_VALID_ENABLED return(1); #else return(0); #endif case XML_WITH_HTML: #ifdef LIBXML_HTML_ENABLED return(1); #else return(0); #endif case XML_WITH_LEGACY: #ifdef LIBXML_LEGACY_ENABLED return(1); #else return(0); #endif case XML_WITH_C14N: #ifdef LIBXML_C14N_ENABLED return(1); #else return(0); #endif case XML_WITH_CATALOG: #ifdef LIBXML_CATALOG_ENABLED return(1); #else return(0); #endif case XML_WITH_XPATH: #ifdef LIBXML_XPATH_ENABLED return(1); #else return(0); #endif case XML_WITH_XPTR: #ifdef LIBXML_XPTR_ENABLED return(1); #else return(0); #endif case XML_WITH_XINCLUDE: #ifdef LIBXML_XINCLUDE_ENABLED return(1); #else return(0); #endif case XML_WITH_ICONV: #ifdef LIBXML_ICONV_ENABLED return(1); #else return(0); #endif case XML_WITH_ISO8859X: #ifdef LIBXML_ISO8859X_ENABLED return(1); #else return(0); #endif case XML_WITH_UNICODE: #ifdef LIBXML_UNICODE_ENABLED return(1); #else return(0); #endif case XML_WITH_REGEXP: #ifdef LIBXML_REGEXP_ENABLED return(1); #else return(0); #endif case XML_WITH_AUTOMATA: #ifdef LIBXML_AUTOMATA_ENABLED return(1); #else return(0); #endif case XML_WITH_EXPR: #ifdef LIBXML_EXPR_ENABLED return(1); #else return(0); #endif case XML_WITH_SCHEMAS: #ifdef LIBXML_SCHEMAS_ENABLED return(1); #else return(0); #endif case XML_WITH_SCHEMATRON: #ifdef LIBXML_SCHEMATRON_ENABLED return(1); #else return(0); #endif case XML_WITH_MODULES: #ifdef LIBXML_MODULES_ENABLED return(1); #else return(0); #endif case XML_WITH_DEBUG: #ifdef LIBXML_DEBUG_ENABLED return(1); #else return(0); #endif case XML_WITH_DEBUG_MEM: #ifdef DEBUG_MEMORY_LOCATION return(1); #else return(0); #endif case XML_WITH_DEBUG_RUN: #ifdef LIBXML_DEBUG_RUNTIME return(1); #else return(0); #endif case XML_WITH_ZLIB: #ifdef LIBXML_ZLIB_ENABLED return(1); #else return(0); #endif case XML_WITH_LZMA: #ifdef LIBXML_LZMA_ENABLED return(1); #else return(0); #endif case XML_WITH_ICU: #ifdef LIBXML_ICU_ENABLED return(1); #else return(0); #endif default: break; } return(0); } /************************************************************************ * * * SAX2 defaulted attributes handling * * * ************************************************************************/ /** * xmlDetectSAX2: * @ctxt: an XML parser context * * Do the SAX2 detection and specific intialization */ static void xmlDetectSAX2(xmlParserCtxtPtr ctxt) { if (ctxt == NULL) return; #ifdef LIBXML_SAX1_ENABLED if ((ctxt->sax) && (ctxt->sax->initialized == XML_SAX2_MAGIC) && ((ctxt->sax->startElementNs != NULL) || (ctxt->sax->endElementNs != NULL))) ctxt->sax2 = 1; #else ctxt->sax2 = 1; #endif /* LIBXML_SAX1_ENABLED */ ctxt->str_xml = xmlDictLookup(ctxt->dict, BAD_CAST "xml", 3); ctxt->str_xmlns = xmlDictLookup(ctxt->dict, BAD_CAST "xmlns", 5); ctxt->str_xml_ns = xmlDictLookup(ctxt->dict, XML_XML_NAMESPACE, 36); if ((ctxt->str_xml==NULL) || (ctxt->str_xmlns==NULL) || (ctxt->str_xml_ns == NULL)) { xmlErrMemory(ctxt, NULL); } } typedef struct _xmlDefAttrs xmlDefAttrs; typedef xmlDefAttrs *xmlDefAttrsPtr; struct _xmlDefAttrs { int nbAttrs; /* number of defaulted attributes on that element */ int maxAttrs; /* the size of the array */ #if __STDC_VERSION__ >= 199901L /* Using a C99 flexible array member avoids UBSan errors. */ const xmlChar *values[]; /* array of localname/prefix/values/external */ #else const xmlChar *values[5]; #endif }; /** * xmlAttrNormalizeSpace: * @src: the source string * @dst: the target string * * Normalize the space in non CDATA attribute values: * If the attribute type is not CDATA, then the XML processor MUST further * process the normalized attribute value by discarding any leading and * trailing space (#x20) characters, and by replacing sequences of space * (#x20) characters by a single space (#x20) character. * Note that the size of dst need to be at least src, and if one doesn't need * to preserve dst (and it doesn't come from a dictionary or read-only) then * passing src as dst is just fine. * * Returns a pointer to the normalized value (dst) or NULL if no conversion * is needed. */ static xmlChar * xmlAttrNormalizeSpace(const xmlChar *src, xmlChar *dst) { if ((src == NULL) || (dst == NULL)) return(NULL); while (*src == 0x20) src++; while (*src != 0) { if (*src == 0x20) { while (*src == 0x20) src++; if (*src != 0) *dst++ = 0x20; } else { *dst++ = *src++; } } *dst = 0; if (dst == src) return(NULL); return(dst); } /** * xmlAttrNormalizeSpace2: * @src: the source string * * Normalize the space in non CDATA attribute values, a slightly more complex * front end to avoid allocation problems when running on attribute values * coming from the input. * * Returns a pointer to the normalized value (dst) or NULL if no conversion * is needed. */ static const xmlChar * xmlAttrNormalizeSpace2(xmlParserCtxtPtr ctxt, xmlChar *src, int *len) { int i; int remove_head = 0; int need_realloc = 0; const xmlChar *cur; if ((ctxt == NULL) || (src == NULL) || (len == NULL)) return(NULL); i = *len; if (i <= 0) return(NULL); cur = src; while (*cur == 0x20) { cur++; remove_head++; } while (*cur != 0) { if (*cur == 0x20) { cur++; if ((*cur == 0x20) || (*cur == 0)) { need_realloc = 1; break; } } else cur++; } if (need_realloc) { xmlChar *ret; ret = xmlStrndup(src + remove_head, i - remove_head + 1); if (ret == NULL) { xmlErrMemory(ctxt, NULL); return(NULL); } xmlAttrNormalizeSpace(ret, ret); *len = (int) strlen((const char *)ret); return(ret); } else if (remove_head) { *len -= remove_head; memmove(src, src + remove_head, 1 + *len); return(src); } return(NULL); } /** * xmlAddDefAttrs: * @ctxt: an XML parser context * @fullname: the element fullname * @fullattr: the attribute fullname * @value: the attribute value * * Add a defaulted attribute for an element */ static void xmlAddDefAttrs(xmlParserCtxtPtr ctxt, const xmlChar *fullname, const xmlChar *fullattr, const xmlChar *value) { xmlDefAttrsPtr defaults; int len; const xmlChar *name; const xmlChar *prefix; /* * Allows to detect attribute redefinitions */ if (ctxt->attsSpecial != NULL) { if (xmlHashLookup2(ctxt->attsSpecial, fullname, fullattr) != NULL) return; } if (ctxt->attsDefault == NULL) { ctxt->attsDefault = xmlHashCreateDict(10, ctxt->dict); if (ctxt->attsDefault == NULL) goto mem_error; } /* * split the element name into prefix:localname , the string found * are within the DTD and then not associated to namespace names. */ name = xmlSplitQName3(fullname, &len); if (name == NULL) { name = xmlDictLookup(ctxt->dict, fullname, -1); prefix = NULL; } else { name = xmlDictLookup(ctxt->dict, name, -1); prefix = xmlDictLookup(ctxt->dict, fullname, len); } /* * make sure there is some storage */ defaults = xmlHashLookup2(ctxt->attsDefault, name, prefix); if (defaults == NULL) { defaults = (xmlDefAttrsPtr) xmlMalloc(sizeof(xmlDefAttrs) + (4 * 5) * sizeof(const xmlChar *)); if (defaults == NULL) goto mem_error; defaults->nbAttrs = 0; defaults->maxAttrs = 4; if (xmlHashUpdateEntry2(ctxt->attsDefault, name, prefix, defaults, NULL) < 0) { xmlFree(defaults); goto mem_error; } } else if (defaults->nbAttrs >= defaults->maxAttrs) { xmlDefAttrsPtr temp; temp = (xmlDefAttrsPtr) xmlRealloc(defaults, sizeof(xmlDefAttrs) + (2 * defaults->maxAttrs * 5) * sizeof(const xmlChar *)); if (temp == NULL) goto mem_error; defaults = temp; defaults->maxAttrs *= 2; if (xmlHashUpdateEntry2(ctxt->attsDefault, name, prefix, defaults, NULL) < 0) { xmlFree(defaults); goto mem_error; } } /* * Split the element name into prefix:localname , the string found * are within the DTD and hen not associated to namespace names. */ name = xmlSplitQName3(fullattr, &len); if (name == NULL) { name = xmlDictLookup(ctxt->dict, fullattr, -1); prefix = NULL; } else { name = xmlDictLookup(ctxt->dict, name, -1); prefix = xmlDictLookup(ctxt->dict, fullattr, len); } defaults->values[5 * defaults->nbAttrs] = name; defaults->values[5 * defaults->nbAttrs + 1] = prefix; /* intern the string and precompute the end */ len = xmlStrlen(value); value = xmlDictLookup(ctxt->dict, value, len); defaults->values[5 * defaults->nbAttrs + 2] = value; defaults->values[5 * defaults->nbAttrs + 3] = value + len; if (ctxt->external) defaults->values[5 * defaults->nbAttrs + 4] = BAD_CAST "external"; else defaults->values[5 * defaults->nbAttrs + 4] = NULL; defaults->nbAttrs++; return; mem_error: xmlErrMemory(ctxt, NULL); return; } /** * xmlAddSpecialAttr: * @ctxt: an XML parser context * @fullname: the element fullname * @fullattr: the attribute fullname * @type: the attribute type * * Register this attribute type */ static void xmlAddSpecialAttr(xmlParserCtxtPtr ctxt, const xmlChar *fullname, const xmlChar *fullattr, int type) { if (ctxt->attsSpecial == NULL) { ctxt->attsSpecial = xmlHashCreateDict(10, ctxt->dict); if (ctxt->attsSpecial == NULL) goto mem_error; } if (xmlHashLookup2(ctxt->attsSpecial, fullname, fullattr) != NULL) return; xmlHashAddEntry2(ctxt->attsSpecial, fullname, fullattr, (void *) (long) type); return; mem_error: xmlErrMemory(ctxt, NULL); return; } /** * xmlCleanSpecialAttrCallback: * * Removes CDATA attributes from the special attribute table */ static void xmlCleanSpecialAttrCallback(void *payload, void *data, const xmlChar *fullname, const xmlChar *fullattr, const xmlChar *unused ATTRIBUTE_UNUSED) { xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) data; if (((long) payload) == XML_ATTRIBUTE_CDATA) { xmlHashRemoveEntry2(ctxt->attsSpecial, fullname, fullattr, NULL); } } /** * xmlCleanSpecialAttr: * @ctxt: an XML parser context * * Trim the list of attributes defined to remove all those of type * CDATA as they are not special. This call should be done when finishing * to parse the DTD and before starting to parse the document root. */ static void xmlCleanSpecialAttr(xmlParserCtxtPtr ctxt) { if (ctxt->attsSpecial == NULL) return; xmlHashScanFull(ctxt->attsSpecial, xmlCleanSpecialAttrCallback, ctxt); if (xmlHashSize(ctxt->attsSpecial) == 0) { xmlHashFree(ctxt->attsSpecial, NULL); ctxt->attsSpecial = NULL; } return; } /** * xmlCheckLanguageID: * @lang: pointer to the string value * * Checks that the value conforms to the LanguageID production: * * NOTE: this is somewhat deprecated, those productions were removed from * the XML Second edition. * * [33] LanguageID ::= Langcode ('-' Subcode)* * [34] Langcode ::= ISO639Code | IanaCode | UserCode * [35] ISO639Code ::= ([a-z] | [A-Z]) ([a-z] | [A-Z]) * [36] IanaCode ::= ('i' | 'I') '-' ([a-z] | [A-Z])+ * [37] UserCode ::= ('x' | 'X') '-' ([a-z] | [A-Z])+ * [38] Subcode ::= ([a-z] | [A-Z])+ * * The current REC reference the sucessors of RFC 1766, currently 5646 * * http://www.rfc-editor.org/rfc/rfc5646.txt * langtag = language * ["-" script] * ["-" region] * *("-" variant) * *("-" extension) * ["-" privateuse] * language = 2*3ALPHA ; shortest ISO 639 code * ["-" extlang] ; sometimes followed by * ; extended language subtags * / 4ALPHA ; or reserved for future use * / 5*8ALPHA ; or registered language subtag * * extlang = 3ALPHA ; selected ISO 639 codes * *2("-" 3ALPHA) ; permanently reserved * * script = 4ALPHA ; ISO 15924 code * * region = 2ALPHA ; ISO 3166-1 code * / 3DIGIT ; UN M.49 code * * variant = 5*8alphanum ; registered variants * / (DIGIT 3alphanum) * * extension = singleton 1*("-" (2*8alphanum)) * * ; Single alphanumerics * ; "x" reserved for private use * singleton = DIGIT ; 0 - 9 * / %x41-57 ; A - W * / %x59-5A ; Y - Z * / %x61-77 ; a - w * / %x79-7A ; y - z * * it sounds right to still allow Irregular i-xxx IANA and user codes too * The parser below doesn't try to cope with extension or privateuse * that could be added but that's not interoperable anyway * * Returns 1 if correct 0 otherwise **/ int xmlCheckLanguageID(const xmlChar * lang) { const xmlChar *cur = lang, *nxt; if (cur == NULL) return (0); if (((cur[0] == 'i') && (cur[1] == '-')) || ((cur[0] == 'I') && (cur[1] == '-')) || ((cur[0] == 'x') && (cur[1] == '-')) || ((cur[0] == 'X') && (cur[1] == '-'))) { /* * Still allow IANA code and user code which were coming * from the previous version of the XML-1.0 specification * it's deprecated but we should not fail */ cur += 2; while (((cur[0] >= 'A') && (cur[0] <= 'Z')) || ((cur[0] >= 'a') && (cur[0] <= 'z'))) cur++; return(cur[0] == 0); } nxt = cur; while (((nxt[0] >= 'A') && (nxt[0] <= 'Z')) || ((nxt[0] >= 'a') && (nxt[0] <= 'z'))) nxt++; if (nxt - cur >= 4) { /* * Reserved */ if ((nxt - cur > 8) || (nxt[0] != 0)) return(0); return(1); } if (nxt - cur < 2) return(0); /* we got an ISO 639 code */ if (nxt[0] == 0) return(1); if (nxt[0] != '-') return(0); nxt++; cur = nxt; /* now we can have extlang or script or region or variant */ if ((nxt[0] >= '0') && (nxt[0] <= '9')) goto region_m49; while (((nxt[0] >= 'A') && (nxt[0] <= 'Z')) || ((nxt[0] >= 'a') && (nxt[0] <= 'z'))) nxt++; if (nxt - cur == 4) goto script; if (nxt - cur == 2) goto region; if ((nxt - cur >= 5) && (nxt - cur <= 8)) goto variant; if (nxt - cur != 3) return(0); /* we parsed an extlang */ if (nxt[0] == 0) return(1); if (nxt[0] != '-') return(0); nxt++; cur = nxt; /* now we can have script or region or variant */ if ((nxt[0] >= '0') && (nxt[0] <= '9')) goto region_m49; while (((nxt[0] >= 'A') && (nxt[0] <= 'Z')) || ((nxt[0] >= 'a') && (nxt[0] <= 'z'))) nxt++; if (nxt - cur == 2) goto region; if ((nxt - cur >= 5) && (nxt - cur <= 8)) goto variant; if (nxt - cur != 4) return(0); /* we parsed a script */ script: if (nxt[0] == 0) return(1); if (nxt[0] != '-') return(0); nxt++; cur = nxt; /* now we can have region or variant */ if ((nxt[0] >= '0') && (nxt[0] <= '9')) goto region_m49; while (((nxt[0] >= 'A') && (nxt[0] <= 'Z')) || ((nxt[0] >= 'a') && (nxt[0] <= 'z'))) nxt++; if ((nxt - cur >= 5) && (nxt - cur <= 8)) goto variant; if (nxt - cur != 2) return(0); /* we parsed a region */ region: if (nxt[0] == 0) return(1); if (nxt[0] != '-') return(0); nxt++; cur = nxt; /* now we can just have a variant */ while (((nxt[0] >= 'A') && (nxt[0] <= 'Z')) || ((nxt[0] >= 'a') && (nxt[0] <= 'z'))) nxt++; if ((nxt - cur < 5) || (nxt - cur > 8)) return(0); /* we parsed a variant */ variant: if (nxt[0] == 0) return(1); if (nxt[0] != '-') return(0); /* extensions and private use subtags not checked */ return (1); region_m49: if (((nxt[1] >= '0') && (nxt[1] <= '9')) && ((nxt[2] >= '0') && (nxt[2] <= '9'))) { nxt += 3; goto region; } return(0); } /************************************************************************ * * * Parser stacks related functions and macros * * * ************************************************************************/ static xmlEntityPtr xmlParseStringEntityRef(xmlParserCtxtPtr ctxt, const xmlChar ** str); #ifdef SAX2 /** * nsPush: * @ctxt: an XML parser context * @prefix: the namespace prefix or NULL * @URL: the namespace name * * Pushes a new parser namespace on top of the ns stack * * Returns -1 in case of error, -2 if the namespace should be discarded * and the index in the stack otherwise. */ static int nsPush(xmlParserCtxtPtr ctxt, const xmlChar *prefix, const xmlChar *URL) { if (ctxt->options & XML_PARSE_NSCLEAN) { int i; for (i = ctxt->nsNr - 2;i >= 0;i -= 2) { if (ctxt->nsTab[i] == prefix) { /* in scope */ if (ctxt->nsTab[i + 1] == URL) return(-2); /* out of scope keep it */ break; } } } if ((ctxt->nsMax == 0) || (ctxt->nsTab == NULL)) { ctxt->nsMax = 10; ctxt->nsNr = 0; ctxt->nsTab = (const xmlChar **) xmlMalloc(ctxt->nsMax * sizeof(xmlChar *)); if (ctxt->nsTab == NULL) { xmlErrMemory(ctxt, NULL); ctxt->nsMax = 0; return (-1); } } else if (ctxt->nsNr >= ctxt->nsMax) { const xmlChar ** tmp; ctxt->nsMax *= 2; tmp = (const xmlChar **) xmlRealloc((char *) ctxt->nsTab, ctxt->nsMax * sizeof(ctxt->nsTab[0])); if (tmp == NULL) { xmlErrMemory(ctxt, NULL); ctxt->nsMax /= 2; return (-1); } ctxt->nsTab = tmp; } ctxt->nsTab[ctxt->nsNr++] = prefix; ctxt->nsTab[ctxt->nsNr++] = URL; return (ctxt->nsNr); } /** * nsPop: * @ctxt: an XML parser context * @nr: the number to pop * * Pops the top @nr parser prefix/namespace from the ns stack * * Returns the number of namespaces removed */ static int nsPop(xmlParserCtxtPtr ctxt, int nr) { int i; if (ctxt->nsTab == NULL) return(0); if (ctxt->nsNr < nr) { xmlGenericError(xmlGenericErrorContext, "Pbm popping %d NS\n", nr); nr = ctxt->nsNr; } if (ctxt->nsNr <= 0) return (0); for (i = 0;i < nr;i++) { ctxt->nsNr--; ctxt->nsTab[ctxt->nsNr] = NULL; } return(nr); } #endif static int xmlCtxtGrowAttrs(xmlParserCtxtPtr ctxt, int nr) { const xmlChar **atts; int *attallocs; int maxatts; if (ctxt->atts == NULL) { maxatts = 55; /* allow for 10 attrs by default */ atts = (const xmlChar **) xmlMalloc(maxatts * sizeof(xmlChar *)); if (atts == NULL) goto mem_error; ctxt->atts = atts; attallocs = (int *) xmlMalloc((maxatts / 5) * sizeof(int)); if (attallocs == NULL) goto mem_error; ctxt->attallocs = attallocs; ctxt->maxatts = maxatts; } else if (nr + 5 > ctxt->maxatts) { maxatts = (nr + 5) * 2; atts = (const xmlChar **) xmlRealloc((void *) ctxt->atts, maxatts * sizeof(const xmlChar *)); if (atts == NULL) goto mem_error; ctxt->atts = atts; attallocs = (int *) xmlRealloc((void *) ctxt->attallocs, (maxatts / 5) * sizeof(int)); if (attallocs == NULL) goto mem_error; ctxt->attallocs = attallocs; ctxt->maxatts = maxatts; } return(ctxt->maxatts); mem_error: xmlErrMemory(ctxt, NULL); return(-1); } /** * inputPush: * @ctxt: an XML parser context * @value: the parser input * * Pushes a new parser input on top of the input stack * * Returns -1 in case of error, the index in the stack otherwise */ int inputPush(xmlParserCtxtPtr ctxt, xmlParserInputPtr value) { if ((ctxt == NULL) || (value == NULL)) return(-1); if (ctxt->inputNr >= ctxt->inputMax) { ctxt->inputMax *= 2; ctxt->inputTab = (xmlParserInputPtr *) xmlRealloc(ctxt->inputTab, ctxt->inputMax * sizeof(ctxt->inputTab[0])); if (ctxt->inputTab == NULL) { xmlErrMemory(ctxt, NULL); xmlFreeInputStream(value); ctxt->inputMax /= 2; value = NULL; return (-1); } } ctxt->inputTab[ctxt->inputNr] = value; ctxt->input = value; return (ctxt->inputNr++); } /** * inputPop: * @ctxt: an XML parser context * * Pops the top parser input from the input stack * * Returns the input just removed */ xmlParserInputPtr inputPop(xmlParserCtxtPtr ctxt) { xmlParserInputPtr ret; if (ctxt == NULL) return(NULL); if (ctxt->inputNr <= 0) return (NULL); ctxt->inputNr--; if (ctxt->inputNr > 0) ctxt->input = ctxt->inputTab[ctxt->inputNr - 1]; else ctxt->input = NULL; ret = ctxt->inputTab[ctxt->inputNr]; ctxt->inputTab[ctxt->inputNr] = NULL; return (ret); } /** * nodePush: * @ctxt: an XML parser context * @value: the element node * * Pushes a new element node on top of the node stack * * Returns -1 in case of error, the index in the stack otherwise */ int nodePush(xmlParserCtxtPtr ctxt, xmlNodePtr value) { if (ctxt == NULL) return(0); if (ctxt->nodeNr >= ctxt->nodeMax) { xmlNodePtr *tmp; tmp = (xmlNodePtr *) xmlRealloc(ctxt->nodeTab, ctxt->nodeMax * 2 * sizeof(ctxt->nodeTab[0])); if (tmp == NULL) { xmlErrMemory(ctxt, NULL); return (-1); } ctxt->nodeTab = tmp; ctxt->nodeMax *= 2; } if ((((unsigned int) ctxt->nodeNr) > xmlParserMaxDepth) && ((ctxt->options & XML_PARSE_HUGE) == 0)) { xmlFatalErrMsgInt(ctxt, XML_ERR_INTERNAL_ERROR, "Excessive depth in document: %d use XML_PARSE_HUGE option\n", xmlParserMaxDepth); xmlHaltParser(ctxt); return(-1); } ctxt->nodeTab[ctxt->nodeNr] = value; ctxt->node = value; return (ctxt->nodeNr++); } /** * nodePop: * @ctxt: an XML parser context * * Pops the top element node from the node stack * * Returns the node just removed */ xmlNodePtr nodePop(xmlParserCtxtPtr ctxt) { xmlNodePtr ret; if (ctxt == NULL) return(NULL); if (ctxt->nodeNr <= 0) return (NULL); ctxt->nodeNr--; if (ctxt->nodeNr > 0) ctxt->node = ctxt->nodeTab[ctxt->nodeNr - 1]; else ctxt->node = NULL; ret = ctxt->nodeTab[ctxt->nodeNr]; ctxt->nodeTab[ctxt->nodeNr] = NULL; return (ret); } #ifdef LIBXML_PUSH_ENABLED /** * nameNsPush: * @ctxt: an XML parser context * @value: the element name * @prefix: the element prefix * @URI: the element namespace name * * Pushes a new element name/prefix/URL on top of the name stack * * Returns -1 in case of error, the index in the stack otherwise */ static int nameNsPush(xmlParserCtxtPtr ctxt, const xmlChar * value, const xmlChar *prefix, const xmlChar *URI, int nsNr) { if (ctxt->nameNr >= ctxt->nameMax) { const xmlChar * *tmp; void **tmp2; ctxt->nameMax *= 2; tmp = (const xmlChar * *) xmlRealloc((xmlChar * *)ctxt->nameTab, ctxt->nameMax * sizeof(ctxt->nameTab[0])); if (tmp == NULL) { ctxt->nameMax /= 2; goto mem_error; } ctxt->nameTab = tmp; tmp2 = (void **) xmlRealloc((void * *)ctxt->pushTab, ctxt->nameMax * 3 * sizeof(ctxt->pushTab[0])); if (tmp2 == NULL) { ctxt->nameMax /= 2; goto mem_error; } ctxt->pushTab = tmp2; } ctxt->nameTab[ctxt->nameNr] = value; ctxt->name = value; ctxt->pushTab[ctxt->nameNr * 3] = (void *) prefix; ctxt->pushTab[ctxt->nameNr * 3 + 1] = (void *) URI; ctxt->pushTab[ctxt->nameNr * 3 + 2] = (void *) (long) nsNr; return (ctxt->nameNr++); mem_error: xmlErrMemory(ctxt, NULL); return (-1); } /** * nameNsPop: * @ctxt: an XML parser context * * Pops the top element/prefix/URI name from the name stack * * Returns the name just removed */ static const xmlChar * nameNsPop(xmlParserCtxtPtr ctxt) { const xmlChar *ret; if (ctxt->nameNr <= 0) return (NULL); ctxt->nameNr--; if (ctxt->nameNr > 0) ctxt->name = ctxt->nameTab[ctxt->nameNr - 1]; else ctxt->name = NULL; ret = ctxt->nameTab[ctxt->nameNr]; ctxt->nameTab[ctxt->nameNr] = NULL; return (ret); } #endif /* LIBXML_PUSH_ENABLED */ /** * namePush: * @ctxt: an XML parser context * @value: the element name * * Pushes a new element name on top of the name stack * * Returns -1 in case of error, the index in the stack otherwise */ int namePush(xmlParserCtxtPtr ctxt, const xmlChar * value) { if (ctxt == NULL) return (-1); if (ctxt->nameNr >= ctxt->nameMax) { const xmlChar * *tmp; tmp = (const xmlChar * *) xmlRealloc((xmlChar * *)ctxt->nameTab, ctxt->nameMax * 2 * sizeof(ctxt->nameTab[0])); if (tmp == NULL) { goto mem_error; } ctxt->nameTab = tmp; ctxt->nameMax *= 2; } ctxt->nameTab[ctxt->nameNr] = value; ctxt->name = value; return (ctxt->nameNr++); mem_error: xmlErrMemory(ctxt, NULL); return (-1); } /** * namePop: * @ctxt: an XML parser context * * Pops the top element name from the name stack * * Returns the name just removed */ const xmlChar * namePop(xmlParserCtxtPtr ctxt) { const xmlChar *ret; if ((ctxt == NULL) || (ctxt->nameNr <= 0)) return (NULL); ctxt->nameNr--; if (ctxt->nameNr > 0) ctxt->name = ctxt->nameTab[ctxt->nameNr - 1]; else ctxt->name = NULL; ret = ctxt->nameTab[ctxt->nameNr]; ctxt->nameTab[ctxt->nameNr] = NULL; return (ret); } static int spacePush(xmlParserCtxtPtr ctxt, int val) { if (ctxt->spaceNr >= ctxt->spaceMax) { int *tmp; ctxt->spaceMax *= 2; tmp = (int *) xmlRealloc(ctxt->spaceTab, ctxt->spaceMax * sizeof(ctxt->spaceTab[0])); if (tmp == NULL) { xmlErrMemory(ctxt, NULL); ctxt->spaceMax /=2; return(-1); } ctxt->spaceTab = tmp; } ctxt->spaceTab[ctxt->spaceNr] = val; ctxt->space = &ctxt->spaceTab[ctxt->spaceNr]; return(ctxt->spaceNr++); } static int spacePop(xmlParserCtxtPtr ctxt) { int ret; if (ctxt->spaceNr <= 0) return(0); ctxt->spaceNr--; if (ctxt->spaceNr > 0) ctxt->space = &ctxt->spaceTab[ctxt->spaceNr - 1]; else ctxt->space = &ctxt->spaceTab[0]; ret = ctxt->spaceTab[ctxt->spaceNr]; ctxt->spaceTab[ctxt->spaceNr] = -1; return(ret); } /* * Macros for accessing the content. Those should be used only by the parser, * and not exported. * * Dirty macros, i.e. one often need to make assumption on the context to * use them * * CUR_PTR return the current pointer to the xmlChar to be parsed. * To be used with extreme caution since operations consuming * characters may move the input buffer to a different location ! * CUR returns the current xmlChar value, i.e. a 8 bit value if compiled * This should be used internally by the parser * only to compare to ASCII values otherwise it would break when * running with UTF-8 encoding. * RAW same as CUR but in the input buffer, bypass any token * extraction that may have been done * NXT(n) returns the n'th next xmlChar. Same as CUR is should be used only * to compare on ASCII based substring. * SKIP(n) Skip n xmlChar, and must also be used only to skip ASCII defined * strings without newlines within the parser. * NEXT1(l) Skip 1 xmlChar, and must also be used only to skip 1 non-newline ASCII * defined char within the parser. * Clean macros, not dependent of an ASCII context, expect UTF-8 encoding * * NEXT Skip to the next character, this does the proper decoding * in UTF-8 mode. It also pop-up unfinished entities on the fly. * NEXTL(l) Skip the current unicode character of l xmlChars long. * CUR_CHAR(l) returns the current unicode character (int), set l * to the number of xmlChars used for the encoding [0-5]. * CUR_SCHAR same but operate on a string instead of the context * COPY_BUF copy the current unicode char to the target buffer, increment * the index * GROW, SHRINK handling of input buffers */ #define RAW (*ctxt->input->cur) #define CUR (*ctxt->input->cur) #define NXT(val) ctxt->input->cur[(val)] #define CUR_PTR ctxt->input->cur #define BASE_PTR ctxt->input->base #define CMP4( s, c1, c2, c3, c4 ) \ ( ((unsigned char *) s)[ 0 ] == c1 && ((unsigned char *) s)[ 1 ] == c2 && \ ((unsigned char *) s)[ 2 ] == c3 && ((unsigned char *) s)[ 3 ] == c4 ) #define CMP5( s, c1, c2, c3, c4, c5 ) \ ( CMP4( s, c1, c2, c3, c4 ) && ((unsigned char *) s)[ 4 ] == c5 ) #define CMP6( s, c1, c2, c3, c4, c5, c6 ) \ ( CMP5( s, c1, c2, c3, c4, c5 ) && ((unsigned char *) s)[ 5 ] == c6 ) #define CMP7( s, c1, c2, c3, c4, c5, c6, c7 ) \ ( CMP6( s, c1, c2, c3, c4, c5, c6 ) && ((unsigned char *) s)[ 6 ] == c7 ) #define CMP8( s, c1, c2, c3, c4, c5, c6, c7, c8 ) \ ( CMP7( s, c1, c2, c3, c4, c5, c6, c7 ) && ((unsigned char *) s)[ 7 ] == c8 ) #define CMP9( s, c1, c2, c3, c4, c5, c6, c7, c8, c9 ) \ ( CMP8( s, c1, c2, c3, c4, c5, c6, c7, c8 ) && \ ((unsigned char *) s)[ 8 ] == c9 ) #define CMP10( s, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10 ) \ ( CMP9( s, c1, c2, c3, c4, c5, c6, c7, c8, c9 ) && \ ((unsigned char *) s)[ 9 ] == c10 ) #define SKIP(val) do { \ ctxt->nbChars += (val),ctxt->input->cur += (val),ctxt->input->col+=(val); \ if (*ctxt->input->cur == '%') xmlParserHandlePEReference(ctxt); \ if ((*ctxt->input->cur == 0) && \ (xmlParserInputGrow(ctxt->input, INPUT_CHUNK) <= 0)) \ xmlPopInput(ctxt); \ } while (0) #define SKIPL(val) do { \ int skipl; \ for(skipl=0; skipl<val; skipl++) { \ if (*(ctxt->input->cur) == '\n') { \ ctxt->input->line++; ctxt->input->col = 1; \ } else ctxt->input->col++; \ ctxt->nbChars++; \ ctxt->input->cur++; \ } \ if (*ctxt->input->cur == '%') xmlParserHandlePEReference(ctxt); \ if ((*ctxt->input->cur == 0) && \ (xmlParserInputGrow(ctxt->input, INPUT_CHUNK) <= 0)) \ xmlPopInput(ctxt); \ } while (0) #define SHRINK if ((ctxt->progressive == 0) && \ (ctxt->input->cur - ctxt->input->base > 2 * INPUT_CHUNK) && \ (ctxt->input->end - ctxt->input->cur < 2 * INPUT_CHUNK)) \ xmlSHRINK (ctxt); static void xmlSHRINK (xmlParserCtxtPtr ctxt) { xmlParserInputShrink(ctxt->input); if ((*ctxt->input->cur == 0) && (xmlParserInputGrow(ctxt->input, INPUT_CHUNK) <= 0)) xmlPopInput(ctxt); } #define GROW if ((ctxt->progressive == 0) && \ (ctxt->input->end - ctxt->input->cur < INPUT_CHUNK)) \ xmlGROW (ctxt); static void xmlGROW (xmlParserCtxtPtr ctxt) { unsigned long curEnd = ctxt->input->end - ctxt->input->cur; unsigned long curBase = ctxt->input->cur - ctxt->input->base; if (((curEnd > (unsigned long) XML_MAX_LOOKUP_LIMIT) || (curBase > (unsigned long) XML_MAX_LOOKUP_LIMIT)) && ((ctxt->input->buf) && (ctxt->input->buf->readcallback != (xmlInputReadCallback) xmlNop)) && ((ctxt->options & XML_PARSE_HUGE) == 0)) { xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "Huge input lookup"); xmlHaltParser(ctxt); return; } xmlParserInputGrow(ctxt->input, INPUT_CHUNK); if ((ctxt->input->cur > ctxt->input->end) || (ctxt->input->cur < ctxt->input->base)) { xmlHaltParser(ctxt); xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "cur index out of bound"); return; } if ((ctxt->input->cur != NULL) && (*ctxt->input->cur == 0) && (xmlParserInputGrow(ctxt->input, INPUT_CHUNK) <= 0)) xmlPopInput(ctxt); } #define SKIP_BLANKS xmlSkipBlankChars(ctxt) #define NEXT xmlNextChar(ctxt) #define NEXT1 { \ ctxt->input->col++; \ ctxt->input->cur++; \ ctxt->nbChars++; \ if (*ctxt->input->cur == 0) \ xmlParserInputGrow(ctxt->input, INPUT_CHUNK); \ } #define NEXTL(l) do { \ if (*(ctxt->input->cur) == '\n') { \ ctxt->input->line++; ctxt->input->col = 1; \ } else ctxt->input->col++; \ ctxt->input->cur += l; \ if (*ctxt->input->cur == '%') xmlParserHandlePEReference(ctxt); \ } while (0) #define CUR_CHAR(l) xmlCurrentChar(ctxt, &l) #define CUR_SCHAR(s, l) xmlStringCurrentChar(ctxt, s, &l) #define COPY_BUF(l,b,i,v) \ if (l == 1) b[i++] = (xmlChar) v; \ else i += xmlCopyCharMultiByte(&b[i],v) /** * xmlSkipBlankChars: * @ctxt: the XML parser context * * skip all blanks character found at that point in the input streams. * It pops up finished entities in the process if allowable at that point. * * Returns the number of space chars skipped */ int xmlSkipBlankChars(xmlParserCtxtPtr ctxt) { int res = 0; /* * It's Okay to use CUR/NEXT here since all the blanks are on * the ASCII range. */ if ((ctxt->inputNr == 1) && (ctxt->instate != XML_PARSER_DTD)) { const xmlChar *cur; /* * if we are in the document content, go really fast */ cur = ctxt->input->cur; while (IS_BLANK_CH(*cur)) { if (*cur == '\n') { ctxt->input->line++; ctxt->input->col = 1; } else { ctxt->input->col++; } cur++; res++; if (*cur == 0) { ctxt->input->cur = cur; xmlParserInputGrow(ctxt->input, INPUT_CHUNK); cur = ctxt->input->cur; } } ctxt->input->cur = cur; } else { int cur; do { cur = CUR; while ((IS_BLANK_CH(cur) && /* CHECKED tstblanks.xml */ (ctxt->instate != XML_PARSER_EOF))) { NEXT; cur = CUR; res++; } while ((cur == 0) && (ctxt->inputNr > 1) && (ctxt->instate != XML_PARSER_COMMENT)) { xmlPopInput(ctxt); cur = CUR; } /* * Need to handle support of entities branching here */ if (*ctxt->input->cur == '%') xmlParserHandlePEReference(ctxt); } while ((IS_BLANK(cur)) && /* CHECKED tstblanks.xml */ (ctxt->instate != XML_PARSER_EOF)); } return(res); } /************************************************************************ * * * Commodity functions to handle entities * * * ************************************************************************/ /** * xmlPopInput: * @ctxt: an XML parser context * * xmlPopInput: the current input pointed by ctxt->input came to an end * pop it and return the next char. * * Returns the current xmlChar in the parser context */ xmlChar xmlPopInput(xmlParserCtxtPtr ctxt) { if ((ctxt == NULL) || (ctxt->inputNr <= 1)) return(0); if (xmlParserDebugEntities) xmlGenericError(xmlGenericErrorContext, "Popping input %d\n", ctxt->inputNr); xmlFreeInputStream(inputPop(ctxt)); if ((*ctxt->input->cur == 0) && (xmlParserInputGrow(ctxt->input, INPUT_CHUNK) <= 0)) return(xmlPopInput(ctxt)); return(CUR); } /** * xmlPushInput: * @ctxt: an XML parser context * @input: an XML parser input fragment (entity, XML fragment ...). * * xmlPushInput: switch to a new input stream which is stacked on top * of the previous one(s). * Returns -1 in case of error or the index in the input stack */ int xmlPushInput(xmlParserCtxtPtr ctxt, xmlParserInputPtr input) { int ret; if (input == NULL) return(-1); if (xmlParserDebugEntities) { if ((ctxt->input != NULL) && (ctxt->input->filename)) xmlGenericError(xmlGenericErrorContext, "%s(%d): ", ctxt->input->filename, ctxt->input->line); xmlGenericError(xmlGenericErrorContext, "Pushing input %d : %.30s\n", ctxt->inputNr+1, input->cur); } ret = inputPush(ctxt, input); if (ctxt->instate == XML_PARSER_EOF) return(-1); GROW; return(ret); } /** * xmlParseCharRef: * @ctxt: an XML parser context * * parse Reference declarations * * [66] CharRef ::= '&#' [0-9]+ ';' | * '&#x' [0-9a-fA-F]+ ';' * * [ WFC: Legal Character ] * Characters referred to using character references must match the * production for Char. * * Returns the value parsed (as an int), 0 in case of error */ int xmlParseCharRef(xmlParserCtxtPtr ctxt) { unsigned int val = 0; int count = 0; unsigned int outofrange = 0; /* * Using RAW/CUR/NEXT is okay since we are working on ASCII range here */ if ((RAW == '&') && (NXT(1) == '#') && (NXT(2) == 'x')) { SKIP(3); GROW; while (RAW != ';') { /* loop blocked by count */ if (count++ > 20) { count = 0; GROW; if (ctxt->instate == XML_PARSER_EOF) return(0); } if ((RAW >= '0') && (RAW <= '9')) val = val * 16 + (CUR - '0'); else if ((RAW >= 'a') && (RAW <= 'f') && (count < 20)) val = val * 16 + (CUR - 'a') + 10; else if ((RAW >= 'A') && (RAW <= 'F') && (count < 20)) val = val * 16 + (CUR - 'A') + 10; else { xmlFatalErr(ctxt, XML_ERR_INVALID_HEX_CHARREF, NULL); val = 0; break; } if (val > 0x10FFFF) outofrange = val; NEXT; count++; } if (RAW == ';') { /* on purpose to avoid reentrancy problems with NEXT and SKIP */ ctxt->input->col++; ctxt->nbChars ++; ctxt->input->cur++; } } else if ((RAW == '&') && (NXT(1) == '#')) { SKIP(2); GROW; while (RAW != ';') { /* loop blocked by count */ if (count++ > 20) { count = 0; GROW; if (ctxt->instate == XML_PARSER_EOF) return(0); } if ((RAW >= '0') && (RAW <= '9')) val = val * 10 + (CUR - '0'); else { xmlFatalErr(ctxt, XML_ERR_INVALID_DEC_CHARREF, NULL); val = 0; break; } if (val > 0x10FFFF) outofrange = val; NEXT; count++; } if (RAW == ';') { /* on purpose to avoid reentrancy problems with NEXT and SKIP */ ctxt->input->col++; ctxt->nbChars ++; ctxt->input->cur++; } } else { xmlFatalErr(ctxt, XML_ERR_INVALID_CHARREF, NULL); } /* * [ WFC: Legal Character ] * Characters referred to using character references must match the * production for Char. */ if ((IS_CHAR(val) && (outofrange == 0))) { return(val); } else { xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR, "xmlParseCharRef: invalid xmlChar value %d\n", val); } return(0); } /** * xmlParseStringCharRef: * @ctxt: an XML parser context * @str: a pointer to an index in the string * * parse Reference declarations, variant parsing from a string rather * than an an input flow. * * [66] CharRef ::= '&#' [0-9]+ ';' | * '&#x' [0-9a-fA-F]+ ';' * * [ WFC: Legal Character ] * Characters referred to using character references must match the * production for Char. * * Returns the value parsed (as an int), 0 in case of error, str will be * updated to the current value of the index */ static int xmlParseStringCharRef(xmlParserCtxtPtr ctxt, const xmlChar **str) { const xmlChar *ptr; xmlChar cur; unsigned int val = 0; unsigned int outofrange = 0; if ((str == NULL) || (*str == NULL)) return(0); ptr = *str; cur = *ptr; if ((cur == '&') && (ptr[1] == '#') && (ptr[2] == 'x')) { ptr += 3; cur = *ptr; while (cur != ';') { /* Non input consuming loop */ if ((cur >= '0') && (cur <= '9')) val = val * 16 + (cur - '0'); else if ((cur >= 'a') && (cur <= 'f')) val = val * 16 + (cur - 'a') + 10; else if ((cur >= 'A') && (cur <= 'F')) val = val * 16 + (cur - 'A') + 10; else { xmlFatalErr(ctxt, XML_ERR_INVALID_HEX_CHARREF, NULL); val = 0; break; } if (val > 0x10FFFF) outofrange = val; ptr++; cur = *ptr; } if (cur == ';') ptr++; } else if ((cur == '&') && (ptr[1] == '#')){ ptr += 2; cur = *ptr; while (cur != ';') { /* Non input consuming loops */ if ((cur >= '0') && (cur <= '9')) val = val * 10 + (cur - '0'); else { xmlFatalErr(ctxt, XML_ERR_INVALID_DEC_CHARREF, NULL); val = 0; break; } if (val > 0x10FFFF) outofrange = val; ptr++; cur = *ptr; } if (cur == ';') ptr++; } else { xmlFatalErr(ctxt, XML_ERR_INVALID_CHARREF, NULL); return(0); } *str = ptr; /* * [ WFC: Legal Character ] * Characters referred to using character references must match the * production for Char. */ if ((IS_CHAR(val) && (outofrange == 0))) { return(val); } else { xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR, "xmlParseStringCharRef: invalid xmlChar value %d\n", val); } return(0); } /** * xmlNewBlanksWrapperInputStream: * @ctxt: an XML parser context * @entity: an Entity pointer * * Create a new input stream for wrapping * blanks around a PEReference * * Returns the new input stream or NULL */ static void deallocblankswrapper (xmlChar *str) {xmlFree(str);} static xmlParserInputPtr xmlNewBlanksWrapperInputStream(xmlParserCtxtPtr ctxt, xmlEntityPtr entity) { xmlParserInputPtr input; xmlChar *buffer; size_t length; if (entity == NULL) { xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "xmlNewBlanksWrapperInputStream entity\n"); return(NULL); } if (xmlParserDebugEntities) xmlGenericError(xmlGenericErrorContext, "new blanks wrapper for entity: %s\n", entity->name); input = xmlNewInputStream(ctxt); if (input == NULL) { return(NULL); } length = xmlStrlen(entity->name) + 5; buffer = xmlMallocAtomic(length); if (buffer == NULL) { xmlErrMemory(ctxt, NULL); xmlFree(input); return(NULL); } buffer [0] = ' '; buffer [1] = '%'; buffer [length-3] = ';'; buffer [length-2] = ' '; buffer [length-1] = 0; memcpy(buffer + 2, entity->name, length - 5); input->free = deallocblankswrapper; input->base = buffer; input->cur = buffer; input->length = length; input->end = &buffer[length]; return(input); } /** * xmlParserHandlePEReference: * @ctxt: the parser context * * [69] PEReference ::= '%' Name ';' * * [ WFC: No Recursion ] * A parsed entity must not contain a recursive * reference to itself, either directly or indirectly. * * [ WFC: Entity Declared ] * In a document without any DTD, a document with only an internal DTD * subset which contains no parameter entity references, or a document * with "standalone='yes'", ... ... The declaration of a parameter * entity must precede any reference to it... * * [ VC: Entity Declared ] * In a document with an external subset or external parameter entities * with "standalone='no'", ... ... The declaration of a parameter entity * must precede any reference to it... * * [ WFC: In DTD ] * Parameter-entity references may only appear in the DTD. * NOTE: misleading but this is handled. * * A PEReference may have been detected in the current input stream * the handling is done accordingly to * http://www.w3.org/TR/REC-xml#entproc * i.e. * - Included in literal in entity values * - Included as Parameter Entity reference within DTDs */ void xmlParserHandlePEReference(xmlParserCtxtPtr ctxt) { const xmlChar *name; xmlEntityPtr entity = NULL; xmlParserInputPtr input; if (RAW != '%') return; switch(ctxt->instate) { case XML_PARSER_CDATA_SECTION: return; case XML_PARSER_COMMENT: return; case XML_PARSER_START_TAG: return; case XML_PARSER_END_TAG: return; case XML_PARSER_EOF: xmlFatalErr(ctxt, XML_ERR_PEREF_AT_EOF, NULL); return; case XML_PARSER_PROLOG: case XML_PARSER_START: case XML_PARSER_MISC: xmlFatalErr(ctxt, XML_ERR_PEREF_IN_PROLOG, NULL); return; case XML_PARSER_ENTITY_DECL: case XML_PARSER_CONTENT: case XML_PARSER_ATTRIBUTE_VALUE: case XML_PARSER_PI: case XML_PARSER_SYSTEM_LITERAL: case XML_PARSER_PUBLIC_LITERAL: /* we just ignore it there */ return; case XML_PARSER_EPILOG: xmlFatalErr(ctxt, XML_ERR_PEREF_IN_EPILOG, NULL); return; case XML_PARSER_ENTITY_VALUE: /* * NOTE: in the case of entity values, we don't do the * substitution here since we need the literal * entity value to be able to save the internal * subset of the document. * This will be handled by xmlStringDecodeEntities */ return; case XML_PARSER_DTD: /* * [WFC: Well-Formedness Constraint: PEs in Internal Subset] * In the internal DTD subset, parameter-entity references * can occur only where markup declarations can occur, not * within markup declarations. * In that case this is handled in xmlParseMarkupDecl */ if ((ctxt->external == 0) && (ctxt->inputNr == 1)) return; if (IS_BLANK_CH(NXT(1)) || NXT(1) == 0) return; break; case XML_PARSER_IGNORE: return; } NEXT; name = xmlParseName(ctxt); if (xmlParserDebugEntities) xmlGenericError(xmlGenericErrorContext, "PEReference: %s\n", name); if (name == NULL) { xmlFatalErr(ctxt, XML_ERR_PEREF_NO_NAME, NULL); } else { if (RAW == ';') { NEXT; if ((ctxt->sax != NULL) && (ctxt->sax->getParameterEntity != NULL)) entity = ctxt->sax->getParameterEntity(ctxt->userData, name); if (ctxt->instate == XML_PARSER_EOF) return; if (entity == NULL) { /* * [ WFC: Entity Declared ] * In a document without any DTD, a document with only an * internal DTD subset which contains no parameter entity * references, or a document with "standalone='yes'", ... * ... The declaration of a parameter entity must precede * any reference to it... */ if ((ctxt->standalone == 1) || ((ctxt->hasExternalSubset == 0) && (ctxt->hasPErefs == 0))) { xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY, "PEReference: %%%s; not found\n", name); } else { /* * [ VC: Entity Declared ] * In a document with an external subset or external * parameter entities with "standalone='no'", ... * ... The declaration of a parameter entity must precede * any reference to it... */ if ((ctxt->validate) && (ctxt->vctxt.error != NULL)) { xmlValidityError(ctxt, XML_WAR_UNDECLARED_ENTITY, "PEReference: %%%s; not found\n", name, NULL); } else xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY, "PEReference: %%%s; not found\n", name, NULL); ctxt->valid = 0; } xmlParserEntityCheck(ctxt, 0, NULL, 0); } else if (ctxt->input->free != deallocblankswrapper) { input = xmlNewBlanksWrapperInputStream(ctxt, entity); if (xmlPushInput(ctxt, input) < 0) return; } else { if ((entity->etype == XML_INTERNAL_PARAMETER_ENTITY) || (entity->etype == XML_EXTERNAL_PARAMETER_ENTITY)) { xmlChar start[4]; xmlCharEncoding enc; /* * Note: external parameter entities will not be loaded, it * is not required for a non-validating parser, unless the * option of validating, or substituting entities were * given. Doing so is far more secure as the parser will * only process data coming from the document entity by * default. */ if ((entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) && ((ctxt->options & XML_PARSE_NOENT) == 0) && ((ctxt->options & XML_PARSE_DTDVALID) == 0) && ((ctxt->options & XML_PARSE_DTDLOAD) == 0) && ((ctxt->options & XML_PARSE_DTDATTR) == 0) && (ctxt->replaceEntities == 0) && (ctxt->validate == 0)) return; /* * handle the extra spaces added before and after * c.f. http://www.w3.org/TR/REC-xml#as-PE * this is done independently. */ input = xmlNewEntityInputStream(ctxt, entity); if (xmlPushInput(ctxt, input) < 0) return; /* * Get the 4 first bytes and decode the charset * if enc != XML_CHAR_ENCODING_NONE * plug some encoding conversion routines. * Note that, since we may have some non-UTF8 * encoding (like UTF16, bug 135229), the 'length' * is not known, but we can calculate based upon * the amount of data in the buffer. */ GROW if (ctxt->instate == XML_PARSER_EOF) return; if ((ctxt->input->end - ctxt->input->cur)>=4) { start[0] = RAW; start[1] = NXT(1); start[2] = NXT(2); start[3] = NXT(3); enc = xmlDetectCharEncoding(start, 4); if (enc != XML_CHAR_ENCODING_NONE) { xmlSwitchEncoding(ctxt, enc); } } if ((entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) && (CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l' )) && (IS_BLANK_CH(NXT(5)))) { xmlParseTextDecl(ctxt); } } else { xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_PARAMETER, "PEReference: %s is not a parameter entity\n", name); } } } else { xmlFatalErr(ctxt, XML_ERR_PEREF_SEMICOL_MISSING, NULL); } } } /* * Macro used to grow the current buffer. * buffer##_size is expected to be a size_t * mem_error: is expected to handle memory allocation failures */ #define growBuffer(buffer, n) { \ xmlChar *tmp; \ size_t new_size = buffer##_size * 2 + n; \ if (new_size < buffer##_size) goto mem_error; \ tmp = (xmlChar *) xmlRealloc(buffer, new_size); \ if (tmp == NULL) goto mem_error; \ buffer = tmp; \ buffer##_size = new_size; \ } /** * xmlStringLenDecodeEntities: * @ctxt: the parser context * @str: the input string * @len: the string length * @what: combination of XML_SUBSTITUTE_REF and XML_SUBSTITUTE_PEREF * @end: an end marker xmlChar, 0 if none * @end2: an end marker xmlChar, 0 if none * @end3: an end marker xmlChar, 0 if none * * Takes a entity string content and process to do the adequate substitutions. * * [67] Reference ::= EntityRef | CharRef * * [69] PEReference ::= '%' Name ';' * * Returns A newly allocated string with the substitution done. The caller * must deallocate it ! */ xmlChar * xmlStringLenDecodeEntities(xmlParserCtxtPtr ctxt, const xmlChar *str, int len, int what, xmlChar end, xmlChar end2, xmlChar end3) { xmlChar *buffer = NULL; size_t buffer_size = 0; size_t nbchars = 0; xmlChar *current = NULL; xmlChar *rep = NULL; const xmlChar *last; xmlEntityPtr ent; int c,l; if ((ctxt == NULL) || (str == NULL) || (len < 0)) return(NULL); last = str + len; if (((ctxt->depth > 40) && ((ctxt->options & XML_PARSE_HUGE) == 0)) || (ctxt->depth > 1024)) { xmlFatalErr(ctxt, XML_ERR_ENTITY_LOOP, NULL); return(NULL); } /* * allocate a translation buffer. */ buffer_size = XML_PARSER_BIG_BUFFER_SIZE; buffer = (xmlChar *) xmlMallocAtomic(buffer_size); if (buffer == NULL) goto mem_error; /* * OK loop until we reach one of the ending char or a size limit. * we are operating on already parsed values. */ if (str < last) c = CUR_SCHAR(str, l); else c = 0; while ((c != 0) && (c != end) && /* non input consuming loop */ (c != end2) && (c != end3)) { if (c == 0) break; if ((c == '&') && (str[1] == '#')) { int val = xmlParseStringCharRef(ctxt, &str); if (val != 0) { COPY_BUF(0,buffer,nbchars,val); } if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) { growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } else if ((c == '&') && (what & XML_SUBSTITUTE_REF)) { if (xmlParserDebugEntities) xmlGenericError(xmlGenericErrorContext, "String decoding Entity Reference: %.30s\n", str); ent = xmlParseStringEntityRef(ctxt, &str); if ((ctxt->lastError.code == XML_ERR_ENTITY_LOOP) || (ctxt->lastError.code == XML_ERR_INTERNAL_ERROR)) goto int_error; xmlParserEntityCheck(ctxt, 0, ent, 0); if (ent != NULL) ctxt->nbentities += ent->checked / 2; if ((ent != NULL) && (ent->etype == XML_INTERNAL_PREDEFINED_ENTITY)) { if (ent->content != NULL) { COPY_BUF(0,buffer,nbchars,ent->content[0]); if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) { growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } else { xmlFatalErrMsg(ctxt, XML_ERR_INTERNAL_ERROR, "predefined entity has no content\n"); } } else if ((ent != NULL) && (ent->content != NULL)) { ctxt->depth++; rep = xmlStringDecodeEntities(ctxt, ent->content, what, 0, 0, 0); ctxt->depth--; if ((ctxt->lastError.code == XML_ERR_ENTITY_LOOP) || (ctxt->lastError.code == XML_ERR_INTERNAL_ERROR)) goto int_error; if (rep != NULL) { current = rep; while (*current != 0) { /* non input consuming loop */ buffer[nbchars++] = *current++; if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) { if (xmlParserEntityCheck(ctxt, nbchars, ent, 0)) goto int_error; growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } xmlFree(rep); rep = NULL; } } else if (ent != NULL) { int i = xmlStrlen(ent->name); const xmlChar *cur = ent->name; buffer[nbchars++] = '&'; if (nbchars + i + XML_PARSER_BUFFER_SIZE > buffer_size) { growBuffer(buffer, i + XML_PARSER_BUFFER_SIZE); } for (;i > 0;i--) buffer[nbchars++] = *cur++; buffer[nbchars++] = ';'; } } else if (c == '%' && (what & XML_SUBSTITUTE_PEREF)) { if (xmlParserDebugEntities) xmlGenericError(xmlGenericErrorContext, "String decoding PE Reference: %.30s\n", str); ent = xmlParseStringPEReference(ctxt, &str); if (ctxt->lastError.code == XML_ERR_ENTITY_LOOP) goto int_error; xmlParserEntityCheck(ctxt, 0, ent, 0); if (ent != NULL) ctxt->nbentities += ent->checked / 2; if (ent != NULL) { if (ent->content == NULL) { /* * Note: external parsed entities will not be loaded, * it is not required for a non-validating parser to * complete external PEreferences coming from the * internal subset */ if (((ctxt->options & XML_PARSE_NOENT) != 0) || ((ctxt->options & XML_PARSE_DTDVALID) != 0) || (ctxt->validate != 0)) { xmlLoadEntityContent(ctxt, ent); } else { xmlWarningMsg(ctxt, XML_ERR_ENTITY_PROCESSING, "not validating will not read content for PE entity %s\n", ent->name, NULL); } } ctxt->depth++; rep = xmlStringDecodeEntities(ctxt, ent->content, what, 0, 0, 0); ctxt->depth--; if (rep != NULL) { current = rep; while (*current != 0) { /* non input consuming loop */ buffer[nbchars++] = *current++; if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) { if (xmlParserEntityCheck(ctxt, nbchars, ent, 0)) goto int_error; growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } xmlFree(rep); rep = NULL; } } } else { COPY_BUF(l,buffer,nbchars,c); str += l; if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) { growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } if (str < last) c = CUR_SCHAR(str, l); else c = 0; } buffer[nbchars] = 0; return(buffer); mem_error: xmlErrMemory(ctxt, NULL); int_error: if (rep != NULL) xmlFree(rep); if (buffer != NULL) xmlFree(buffer); return(NULL); } /** * xmlStringDecodeEntities: * @ctxt: the parser context * @str: the input string * @what: combination of XML_SUBSTITUTE_REF and XML_SUBSTITUTE_PEREF * @end: an end marker xmlChar, 0 if none * @end2: an end marker xmlChar, 0 if none * @end3: an end marker xmlChar, 0 if none * * Takes a entity string content and process to do the adequate substitutions. * * [67] Reference ::= EntityRef | CharRef * * [69] PEReference ::= '%' Name ';' * * Returns A newly allocated string with the substitution done. The caller * must deallocate it ! */ xmlChar * xmlStringDecodeEntities(xmlParserCtxtPtr ctxt, const xmlChar *str, int what, xmlChar end, xmlChar end2, xmlChar end3) { if ((ctxt == NULL) || (str == NULL)) return(NULL); return(xmlStringLenDecodeEntities(ctxt, str, xmlStrlen(str), what, end, end2, end3)); } /************************************************************************ * * * Commodity functions, cleanup needed ? * * * ************************************************************************/ /** * areBlanks: * @ctxt: an XML parser context * @str: a xmlChar * * @len: the size of @str * @blank_chars: we know the chars are blanks * * Is this a sequence of blank chars that one can ignore ? * * Returns 1 if ignorable 0 otherwise. */ static int areBlanks(xmlParserCtxtPtr ctxt, const xmlChar *str, int len, int blank_chars) { int i, ret; xmlNodePtr lastChild; /* * Don't spend time trying to differentiate them, the same callback is * used ! */ if (ctxt->sax->ignorableWhitespace == ctxt->sax->characters) return(0); /* * Check for xml:space value. */ if ((ctxt->space == NULL) || (*(ctxt->space) == 1) || (*(ctxt->space) == -2)) return(0); /* * Check that the string is made of blanks */ if (blank_chars == 0) { for (i = 0;i < len;i++) if (!(IS_BLANK_CH(str[i]))) return(0); } /* * Look if the element is mixed content in the DTD if available */ if (ctxt->node == NULL) return(0); if (ctxt->myDoc != NULL) { ret = xmlIsMixedElement(ctxt->myDoc, ctxt->node->name); if (ret == 0) return(1); if (ret == 1) return(0); } /* * Otherwise, heuristic :-\ */ if ((RAW != '<') && (RAW != 0xD)) return(0); if ((ctxt->node->children == NULL) && (RAW == '<') && (NXT(1) == '/')) return(0); lastChild = xmlGetLastChild(ctxt->node); if (lastChild == NULL) { if ((ctxt->node->type != XML_ELEMENT_NODE) && (ctxt->node->content != NULL)) return(0); } else if (xmlNodeIsText(lastChild)) return(0); else if ((ctxt->node->children != NULL) && (xmlNodeIsText(ctxt->node->children))) return(0); return(1); } /************************************************************************ * * * Extra stuff for namespace support * * Relates to http://www.w3.org/TR/WD-xml-names * * * ************************************************************************/ /** * xmlSplitQName: * @ctxt: an XML parser context * @name: an XML parser context * @prefix: a xmlChar ** * * parse an UTF8 encoded XML qualified name string * * [NS 5] QName ::= (Prefix ':')? LocalPart * * [NS 6] Prefix ::= NCName * * [NS 7] LocalPart ::= NCName * * Returns the local part, and prefix is updated * to get the Prefix if any. */ xmlChar * xmlSplitQName(xmlParserCtxtPtr ctxt, const xmlChar *name, xmlChar **prefix) { xmlChar buf[XML_MAX_NAMELEN + 5]; xmlChar *buffer = NULL; int len = 0; int max = XML_MAX_NAMELEN; xmlChar *ret = NULL; const xmlChar *cur = name; int c; if (prefix == NULL) return(NULL); *prefix = NULL; if (cur == NULL) return(NULL); #ifndef XML_XML_NAMESPACE /* xml: prefix is not really a namespace */ if ((cur[0] == 'x') && (cur[1] == 'm') && (cur[2] == 'l') && (cur[3] == ':')) return(xmlStrdup(name)); #endif /* nasty but well=formed */ if (cur[0] == ':') return(xmlStrdup(name)); c = *cur++; while ((c != 0) && (c != ':') && (len < max)) { /* tested bigname.xml */ buf[len++] = c; c = *cur++; } if (len >= max) { /* * Okay someone managed to make a huge name, so he's ready to pay * for the processing speed. */ max = len * 2; buffer = (xmlChar *) xmlMallocAtomic(max * sizeof(xmlChar)); if (buffer == NULL) { xmlErrMemory(ctxt, NULL); return(NULL); } memcpy(buffer, buf, len); while ((c != 0) && (c != ':')) { /* tested bigname.xml */ if (len + 10 > max) { xmlChar *tmp; max *= 2; tmp = (xmlChar *) xmlRealloc(buffer, max * sizeof(xmlChar)); if (tmp == NULL) { xmlFree(buffer); xmlErrMemory(ctxt, NULL); return(NULL); } buffer = tmp; } buffer[len++] = c; c = *cur++; } buffer[len] = 0; } if ((c == ':') && (*cur == 0)) { if (buffer != NULL) xmlFree(buffer); *prefix = NULL; return(xmlStrdup(name)); } if (buffer == NULL) ret = xmlStrndup(buf, len); else { ret = buffer; buffer = NULL; max = XML_MAX_NAMELEN; } if (c == ':') { c = *cur; *prefix = ret; if (c == 0) { return(xmlStrndup(BAD_CAST "", 0)); } len = 0; /* * Check that the first character is proper to start * a new name */ if (!(((c >= 0x61) && (c <= 0x7A)) || ((c >= 0x41) && (c <= 0x5A)) || (c == '_') || (c == ':'))) { int l; int first = CUR_SCHAR(cur, l); if (!IS_LETTER(first) && (first != '_')) { xmlFatalErrMsgStr(ctxt, XML_NS_ERR_QNAME, "Name %s is not XML Namespace compliant\n", name); } } cur++; while ((c != 0) && (len < max)) { /* tested bigname2.xml */ buf[len++] = c; c = *cur++; } if (len >= max) { /* * Okay someone managed to make a huge name, so he's ready to pay * for the processing speed. */ max = len * 2; buffer = (xmlChar *) xmlMallocAtomic(max * sizeof(xmlChar)); if (buffer == NULL) { xmlErrMemory(ctxt, NULL); return(NULL); } memcpy(buffer, buf, len); while (c != 0) { /* tested bigname2.xml */ if (len + 10 > max) { xmlChar *tmp; max *= 2; tmp = (xmlChar *) xmlRealloc(buffer, max * sizeof(xmlChar)); if (tmp == NULL) { xmlErrMemory(ctxt, NULL); xmlFree(buffer); return(NULL); } buffer = tmp; } buffer[len++] = c; c = *cur++; } buffer[len] = 0; } if (buffer == NULL) ret = xmlStrndup(buf, len); else { ret = buffer; } } return(ret); } /************************************************************************ * * * The parser itself * * Relates to http://www.w3.org/TR/REC-xml * * * ************************************************************************/ /************************************************************************ * * * Routines to parse Name, NCName and NmToken * * * ************************************************************************/ #ifdef DEBUG static unsigned long nbParseName = 0; static unsigned long nbParseNmToken = 0; static unsigned long nbParseNCName = 0; static unsigned long nbParseNCNameComplex = 0; static unsigned long nbParseNameComplex = 0; static unsigned long nbParseStringName = 0; #endif /* * The two following functions are related to the change of accepted * characters for Name and NmToken in the Revision 5 of XML-1.0 * They correspond to the modified production [4] and the new production [4a] * changes in that revision. Also note that the macros used for the * productions Letter, Digit, CombiningChar and Extender are not needed * anymore. * We still keep compatibility to pre-revision5 parsing semantic if the * new XML_PARSE_OLD10 option is given to the parser. */ static int xmlIsNameStartChar(xmlParserCtxtPtr ctxt, int c) { if ((ctxt->options & XML_PARSE_OLD10) == 0) { /* * Use the new checks of production [4] [4a] amd [5] of the * Update 5 of XML-1.0 */ if ((c != ' ') && (c != '>') && (c != '/') && /* accelerators */ (((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')) || (c == '_') || (c == ':') || ((c >= 0xC0) && (c <= 0xD6)) || ((c >= 0xD8) && (c <= 0xF6)) || ((c >= 0xF8) && (c <= 0x2FF)) || ((c >= 0x370) && (c <= 0x37D)) || ((c >= 0x37F) && (c <= 0x1FFF)) || ((c >= 0x200C) && (c <= 0x200D)) || ((c >= 0x2070) && (c <= 0x218F)) || ((c >= 0x2C00) && (c <= 0x2FEF)) || ((c >= 0x3001) && (c <= 0xD7FF)) || ((c >= 0xF900) && (c <= 0xFDCF)) || ((c >= 0xFDF0) && (c <= 0xFFFD)) || ((c >= 0x10000) && (c <= 0xEFFFF)))) return(1); } else { if (IS_LETTER(c) || (c == '_') || (c == ':')) return(1); } return(0); } static int xmlIsNameChar(xmlParserCtxtPtr ctxt, int c) { if ((ctxt->options & XML_PARSE_OLD10) == 0) { /* * Use the new checks of production [4] [4a] amd [5] of the * Update 5 of XML-1.0 */ if ((c != ' ') && (c != '>') && (c != '/') && /* accelerators */ (((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')) || ((c >= '0') && (c <= '9')) || /* !start */ (c == '_') || (c == ':') || (c == '-') || (c == '.') || (c == 0xB7) || /* !start */ ((c >= 0xC0) && (c <= 0xD6)) || ((c >= 0xD8) && (c <= 0xF6)) || ((c >= 0xF8) && (c <= 0x2FF)) || ((c >= 0x300) && (c <= 0x36F)) || /* !start */ ((c >= 0x370) && (c <= 0x37D)) || ((c >= 0x37F) && (c <= 0x1FFF)) || ((c >= 0x200C) && (c <= 0x200D)) || ((c >= 0x203F) && (c <= 0x2040)) || /* !start */ ((c >= 0x2070) && (c <= 0x218F)) || ((c >= 0x2C00) && (c <= 0x2FEF)) || ((c >= 0x3001) && (c <= 0xD7FF)) || ((c >= 0xF900) && (c <= 0xFDCF)) || ((c >= 0xFDF0) && (c <= 0xFFFD)) || ((c >= 0x10000) && (c <= 0xEFFFF)))) return(1); } else { if ((IS_LETTER(c)) || (IS_DIGIT(c)) || (c == '.') || (c == '-') || (c == '_') || (c == ':') || (IS_COMBINING(c)) || (IS_EXTENDER(c))) return(1); } return(0); } static xmlChar * xmlParseAttValueInternal(xmlParserCtxtPtr ctxt, int *len, int *alloc, int normalize); static const xmlChar * xmlParseNameComplex(xmlParserCtxtPtr ctxt) { int len = 0, l; int c; int count = 0; #ifdef DEBUG nbParseNameComplex++; #endif /* * Handler for more complex cases */ GROW; if (ctxt->instate == XML_PARSER_EOF) return(NULL); c = CUR_CHAR(l); if ((ctxt->options & XML_PARSE_OLD10) == 0) { /* * Use the new checks of production [4] [4a] amd [5] of the * Update 5 of XML-1.0 */ if ((c == ' ') || (c == '>') || (c == '/') || /* accelerators */ (!(((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')) || (c == '_') || (c == ':') || ((c >= 0xC0) && (c <= 0xD6)) || ((c >= 0xD8) && (c <= 0xF6)) || ((c >= 0xF8) && (c <= 0x2FF)) || ((c >= 0x370) && (c <= 0x37D)) || ((c >= 0x37F) && (c <= 0x1FFF)) || ((c >= 0x200C) && (c <= 0x200D)) || ((c >= 0x2070) && (c <= 0x218F)) || ((c >= 0x2C00) && (c <= 0x2FEF)) || ((c >= 0x3001) && (c <= 0xD7FF)) || ((c >= 0xF900) && (c <= 0xFDCF)) || ((c >= 0xFDF0) && (c <= 0xFFFD)) || ((c >= 0x10000) && (c <= 0xEFFFF))))) { return(NULL); } len += l; NEXTL(l); c = CUR_CHAR(l); while ((c != ' ') && (c != '>') && (c != '/') && /* accelerators */ (((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')) || ((c >= '0') && (c <= '9')) || /* !start */ (c == '_') || (c == ':') || (c == '-') || (c == '.') || (c == 0xB7) || /* !start */ ((c >= 0xC0) && (c <= 0xD6)) || ((c >= 0xD8) && (c <= 0xF6)) || ((c >= 0xF8) && (c <= 0x2FF)) || ((c >= 0x300) && (c <= 0x36F)) || /* !start */ ((c >= 0x370) && (c <= 0x37D)) || ((c >= 0x37F) && (c <= 0x1FFF)) || ((c >= 0x200C) && (c <= 0x200D)) || ((c >= 0x203F) && (c <= 0x2040)) || /* !start */ ((c >= 0x2070) && (c <= 0x218F)) || ((c >= 0x2C00) && (c <= 0x2FEF)) || ((c >= 0x3001) && (c <= 0xD7FF)) || ((c >= 0xF900) && (c <= 0xFDCF)) || ((c >= 0xFDF0) && (c <= 0xFFFD)) || ((c >= 0x10000) && (c <= 0xEFFFF)) )) { if (count++ > XML_PARSER_CHUNK_SIZE) { count = 0; GROW; if (ctxt->instate == XML_PARSER_EOF) return(NULL); } len += l; NEXTL(l); c = CUR_CHAR(l); } } else { if ((c == ' ') || (c == '>') || (c == '/') || /* accelerators */ (!IS_LETTER(c) && (c != '_') && (c != ':'))) { return(NULL); } len += l; NEXTL(l); c = CUR_CHAR(l); while ((c != ' ') && (c != '>') && (c != '/') && /* test bigname.xml */ ((IS_LETTER(c)) || (IS_DIGIT(c)) || (c == '.') || (c == '-') || (c == '_') || (c == ':') || (IS_COMBINING(c)) || (IS_EXTENDER(c)))) { if (count++ > XML_PARSER_CHUNK_SIZE) { count = 0; GROW; if (ctxt->instate == XML_PARSER_EOF) return(NULL); } len += l; NEXTL(l); c = CUR_CHAR(l); if (c == 0) { count = 0; GROW; if (ctxt->instate == XML_PARSER_EOF) return(NULL); c = CUR_CHAR(l); } } } if ((len > XML_MAX_NAME_LENGTH) && ((ctxt->options & XML_PARSE_HUGE) == 0)) { xmlFatalErr(ctxt, XML_ERR_NAME_TOO_LONG, "Name"); return(NULL); } if ((*ctxt->input->cur == '\n') && (ctxt->input->cur[-1] == '\r')) return(xmlDictLookup(ctxt->dict, ctxt->input->cur - (len + 1), len)); return(xmlDictLookup(ctxt->dict, ctxt->input->cur - len, len)); } /** * xmlParseName: * @ctxt: an XML parser context * * parse an XML name. * * [4] NameChar ::= Letter | Digit | '.' | '-' | '_' | ':' | * CombiningChar | Extender * * [5] Name ::= (Letter | '_' | ':') (NameChar)* * * [6] Names ::= Name (#x20 Name)* * * Returns the Name parsed or NULL */ const xmlChar * xmlParseName(xmlParserCtxtPtr ctxt) { const xmlChar *in; const xmlChar *ret; int count = 0; GROW; #ifdef DEBUG nbParseName++; #endif /* * Accelerator for simple ASCII names */ in = ctxt->input->cur; if (((*in >= 0x61) && (*in <= 0x7A)) || ((*in >= 0x41) && (*in <= 0x5A)) || (*in == '_') || (*in == ':')) { in++; while (((*in >= 0x61) && (*in <= 0x7A)) || ((*in >= 0x41) && (*in <= 0x5A)) || ((*in >= 0x30) && (*in <= 0x39)) || (*in == '_') || (*in == '-') || (*in == ':') || (*in == '.')) in++; if ((*in > 0) && (*in < 0x80)) { count = in - ctxt->input->cur; if ((count > XML_MAX_NAME_LENGTH) && ((ctxt->options & XML_PARSE_HUGE) == 0)) { xmlFatalErr(ctxt, XML_ERR_NAME_TOO_LONG, "Name"); return(NULL); } ret = xmlDictLookup(ctxt->dict, ctxt->input->cur, count); ctxt->input->cur = in; ctxt->nbChars += count; ctxt->input->col += count; if (ret == NULL) xmlErrMemory(ctxt, NULL); return(ret); } } /* accelerator for special cases */ return(xmlParseNameComplex(ctxt)); } static const xmlChar * xmlParseNCNameComplex(xmlParserCtxtPtr ctxt) { int len = 0, l; int c; int count = 0; size_t startPosition = 0; #ifdef DEBUG nbParseNCNameComplex++; #endif /* * Handler for more complex cases */ GROW; startPosition = CUR_PTR - BASE_PTR; c = CUR_CHAR(l); if ((c == ' ') || (c == '>') || (c == '/') || /* accelerators */ (!xmlIsNameStartChar(ctxt, c) || (c == ':'))) { return(NULL); } while ((c != ' ') && (c != '>') && (c != '/') && /* test bigname.xml */ (xmlIsNameChar(ctxt, c) && (c != ':'))) { if (count++ > XML_PARSER_CHUNK_SIZE) { if ((len > XML_MAX_NAME_LENGTH) && ((ctxt->options & XML_PARSE_HUGE) == 0)) { xmlFatalErr(ctxt, XML_ERR_NAME_TOO_LONG, "NCName"); return(NULL); } count = 0; GROW; if (ctxt->instate == XML_PARSER_EOF) return(NULL); } len += l; NEXTL(l); c = CUR_CHAR(l); if (c == 0) { count = 0; /* * when shrinking to extend the buffer we really need to preserve * the part of the name we already parsed. Hence rolling back * by current lenght. */ ctxt->input->cur -= l; GROW; ctxt->input->cur += l; if (ctxt->instate == XML_PARSER_EOF) return(NULL); c = CUR_CHAR(l); } } if ((len > XML_MAX_NAME_LENGTH) && ((ctxt->options & XML_PARSE_HUGE) == 0)) { xmlFatalErr(ctxt, XML_ERR_NAME_TOO_LONG, "NCName"); return(NULL); } return(xmlDictLookup(ctxt->dict, (BASE_PTR + startPosition), len)); } /** * xmlParseNCName: * @ctxt: an XML parser context * @len: length of the string parsed * * parse an XML name. * * [4NS] NCNameChar ::= Letter | Digit | '.' | '-' | '_' | * CombiningChar | Extender * * [5NS] NCName ::= (Letter | '_') (NCNameChar)* * * Returns the Name parsed or NULL */ static const xmlChar * xmlParseNCName(xmlParserCtxtPtr ctxt) { const xmlChar *in, *e; const xmlChar *ret; int count = 0; #ifdef DEBUG nbParseNCName++; #endif /* * Accelerator for simple ASCII names */ in = ctxt->input->cur; e = ctxt->input->end; if ((((*in >= 0x61) && (*in <= 0x7A)) || ((*in >= 0x41) && (*in <= 0x5A)) || (*in == '_')) && (in < e)) { in++; while ((((*in >= 0x61) && (*in <= 0x7A)) || ((*in >= 0x41) && (*in <= 0x5A)) || ((*in >= 0x30) && (*in <= 0x39)) || (*in == '_') || (*in == '-') || (*in == '.')) && (in < e)) in++; if (in >= e) goto complex; if ((*in > 0) && (*in < 0x80)) { count = in - ctxt->input->cur; if ((count > XML_MAX_NAME_LENGTH) && ((ctxt->options & XML_PARSE_HUGE) == 0)) { xmlFatalErr(ctxt, XML_ERR_NAME_TOO_LONG, "NCName"); return(NULL); } ret = xmlDictLookup(ctxt->dict, ctxt->input->cur, count); ctxt->input->cur = in; ctxt->nbChars += count; ctxt->input->col += count; if (ret == NULL) { xmlErrMemory(ctxt, NULL); } return(ret); } } complex: return(xmlParseNCNameComplex(ctxt)); } /** * xmlParseNameAndCompare: * @ctxt: an XML parser context * * parse an XML name and compares for match * (specialized for endtag parsing) * * Returns NULL for an illegal name, (xmlChar*) 1 for success * and the name for mismatch */ static const xmlChar * xmlParseNameAndCompare(xmlParserCtxtPtr ctxt, xmlChar const *other) { register const xmlChar *cmp = other; register const xmlChar *in; const xmlChar *ret; GROW; if (ctxt->instate == XML_PARSER_EOF) return(NULL); in = ctxt->input->cur; while (*in != 0 && *in == *cmp) { ++in; ++cmp; ctxt->input->col++; } if (*cmp == 0 && (*in == '>' || IS_BLANK_CH (*in))) { /* success */ ctxt->input->cur = in; return (const xmlChar*) 1; } /* failure (or end of input buffer), check with full function */ ret = xmlParseName (ctxt); /* strings coming from the dictionary direct compare possible */ if (ret == other) { return (const xmlChar*) 1; } return ret; } /** * xmlParseStringName: * @ctxt: an XML parser context * @str: a pointer to the string pointer (IN/OUT) * * parse an XML name. * * [4] NameChar ::= Letter | Digit | '.' | '-' | '_' | ':' | * CombiningChar | Extender * * [5] Name ::= (Letter | '_' | ':') (NameChar)* * * [6] Names ::= Name (#x20 Name)* * * Returns the Name parsed or NULL. The @str pointer * is updated to the current location in the string. */ static xmlChar * xmlParseStringName(xmlParserCtxtPtr ctxt, const xmlChar** str) { xmlChar buf[XML_MAX_NAMELEN + 5]; const xmlChar *cur = *str; int len = 0, l; int c; #ifdef DEBUG nbParseStringName++; #endif c = CUR_SCHAR(cur, l); if (!xmlIsNameStartChar(ctxt, c)) { return(NULL); } COPY_BUF(l,buf,len,c); cur += l; c = CUR_SCHAR(cur, l); while (xmlIsNameChar(ctxt, c)) { COPY_BUF(l,buf,len,c); cur += l; c = CUR_SCHAR(cur, l); if (len >= XML_MAX_NAMELEN) { /* test bigentname.xml */ /* * Okay someone managed to make a huge name, so he's ready to pay * for the processing speed. */ xmlChar *buffer; int max = len * 2; buffer = (xmlChar *) xmlMallocAtomic(max * sizeof(xmlChar)); if (buffer == NULL) { xmlErrMemory(ctxt, NULL); return(NULL); } memcpy(buffer, buf, len); while (xmlIsNameChar(ctxt, c)) { if (len + 10 > max) { xmlChar *tmp; if ((len > XML_MAX_NAME_LENGTH) && ((ctxt->options & XML_PARSE_HUGE) == 0)) { xmlFatalErr(ctxt, XML_ERR_NAME_TOO_LONG, "NCName"); xmlFree(buffer); return(NULL); } max *= 2; tmp = (xmlChar *) xmlRealloc(buffer, max * sizeof(xmlChar)); if (tmp == NULL) { xmlErrMemory(ctxt, NULL); xmlFree(buffer); return(NULL); } buffer = tmp; } COPY_BUF(l,buffer,len,c); cur += l; c = CUR_SCHAR(cur, l); } buffer[len] = 0; *str = cur; return(buffer); } } if ((len > XML_MAX_NAME_LENGTH) && ((ctxt->options & XML_PARSE_HUGE) == 0)) { xmlFatalErr(ctxt, XML_ERR_NAME_TOO_LONG, "NCName"); return(NULL); } *str = cur; return(xmlStrndup(buf, len)); } /** * xmlParseNmtoken: * @ctxt: an XML parser context * * parse an XML Nmtoken. * * [7] Nmtoken ::= (NameChar)+ * * [8] Nmtokens ::= Nmtoken (#x20 Nmtoken)* * * Returns the Nmtoken parsed or NULL */ xmlChar * xmlParseNmtoken(xmlParserCtxtPtr ctxt) { xmlChar buf[XML_MAX_NAMELEN + 5]; int len = 0, l; int c; int count = 0; #ifdef DEBUG nbParseNmToken++; #endif GROW; if (ctxt->instate == XML_PARSER_EOF) return(NULL); c = CUR_CHAR(l); while (xmlIsNameChar(ctxt, c)) { if (count++ > XML_PARSER_CHUNK_SIZE) { count = 0; GROW; } COPY_BUF(l,buf,len,c); NEXTL(l); c = CUR_CHAR(l); if (c == 0) { count = 0; GROW; if (ctxt->instate == XML_PARSER_EOF) return(NULL); c = CUR_CHAR(l); } if (len >= XML_MAX_NAMELEN) { /* * Okay someone managed to make a huge token, so he's ready to pay * for the processing speed. */ xmlChar *buffer; int max = len * 2; buffer = (xmlChar *) xmlMallocAtomic(max * sizeof(xmlChar)); if (buffer == NULL) { xmlErrMemory(ctxt, NULL); return(NULL); } memcpy(buffer, buf, len); while (xmlIsNameChar(ctxt, c)) { if (count++ > XML_PARSER_CHUNK_SIZE) { count = 0; GROW; if (ctxt->instate == XML_PARSER_EOF) { xmlFree(buffer); return(NULL); } } if (len + 10 > max) { xmlChar *tmp; if ((max > XML_MAX_NAME_LENGTH) && ((ctxt->options & XML_PARSE_HUGE) == 0)) { xmlFatalErr(ctxt, XML_ERR_NAME_TOO_LONG, "NmToken"); xmlFree(buffer); return(NULL); } max *= 2; tmp = (xmlChar *) xmlRealloc(buffer, max * sizeof(xmlChar)); if (tmp == NULL) { xmlErrMemory(ctxt, NULL); xmlFree(buffer); return(NULL); } buffer = tmp; } COPY_BUF(l,buffer,len,c); NEXTL(l); c = CUR_CHAR(l); } buffer[len] = 0; return(buffer); } } if (len == 0) return(NULL); if ((len > XML_MAX_NAME_LENGTH) && ((ctxt->options & XML_PARSE_HUGE) == 0)) { xmlFatalErr(ctxt, XML_ERR_NAME_TOO_LONG, "NmToken"); return(NULL); } return(xmlStrndup(buf, len)); } /** * xmlParseEntityValue: * @ctxt: an XML parser context * @orig: if non-NULL store a copy of the original entity value * * parse a value for ENTITY declarations * * [9] EntityValue ::= '"' ([^%&"] | PEReference | Reference)* '"' | * "'" ([^%&'] | PEReference | Reference)* "'" * * Returns the EntityValue parsed with reference substituted or NULL */ xmlChar * xmlParseEntityValue(xmlParserCtxtPtr ctxt, xmlChar **orig) { xmlChar *buf = NULL; int len = 0; int size = XML_PARSER_BUFFER_SIZE; int c, l; xmlChar stop; xmlChar *ret = NULL; const xmlChar *cur = NULL; xmlParserInputPtr input; if (RAW == '"') stop = '"'; else if (RAW == '\'') stop = '\''; else { xmlFatalErr(ctxt, XML_ERR_ENTITY_NOT_STARTED, NULL); return(NULL); } buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar)); if (buf == NULL) { xmlErrMemory(ctxt, NULL); return(NULL); } /* * The content of the entity definition is copied in a buffer. */ ctxt->instate = XML_PARSER_ENTITY_VALUE; input = ctxt->input; GROW; if (ctxt->instate == XML_PARSER_EOF) { xmlFree(buf); return(NULL); } NEXT; c = CUR_CHAR(l); /* * NOTE: 4.4.5 Included in Literal * When a parameter entity reference appears in a literal entity * value, ... a single or double quote character in the replacement * text is always treated as a normal data character and will not * terminate the literal. * In practice it means we stop the loop only when back at parsing * the initial entity and the quote is found */ while (((IS_CHAR(c)) && ((c != stop) || /* checked */ (ctxt->input != input))) && (ctxt->instate != XML_PARSER_EOF)) { if (len + 5 >= size) { xmlChar *tmp; size *= 2; tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar)); if (tmp == NULL) { xmlErrMemory(ctxt, NULL); xmlFree(buf); return(NULL); } buf = tmp; } COPY_BUF(l,buf,len,c); NEXTL(l); /* * Pop-up of finished entities. */ while ((RAW == 0) && (ctxt->inputNr > 1)) /* non input consuming */ xmlPopInput(ctxt); GROW; c = CUR_CHAR(l); if (c == 0) { GROW; c = CUR_CHAR(l); } } buf[len] = 0; if (ctxt->instate == XML_PARSER_EOF) { xmlFree(buf); return(NULL); } /* * Raise problem w.r.t. '&' and '%' being used in non-entities * reference constructs. Note Charref will be handled in * xmlStringDecodeEntities() */ cur = buf; while (*cur != 0) { /* non input consuming */ if ((*cur == '%') || ((*cur == '&') && (cur[1] != '#'))) { xmlChar *name; xmlChar tmp = *cur; cur++; name = xmlParseStringName(ctxt, &cur); if ((name == NULL) || (*cur != ';')) { xmlFatalErrMsgInt(ctxt, XML_ERR_ENTITY_CHAR_ERROR, "EntityValue: '%c' forbidden except for entities references\n", tmp); } if ((tmp == '%') && (ctxt->inSubset == 1) && (ctxt->inputNr == 1)) { xmlFatalErr(ctxt, XML_ERR_ENTITY_PE_INTERNAL, NULL); } if (name != NULL) xmlFree(name); if (*cur == 0) break; } cur++; } /* * Then PEReference entities are substituted. */ if (c != stop) { xmlFatalErr(ctxt, XML_ERR_ENTITY_NOT_FINISHED, NULL); xmlFree(buf); } else { NEXT; /* * NOTE: 4.4.7 Bypassed * When a general entity reference appears in the EntityValue in * an entity declaration, it is bypassed and left as is. * so XML_SUBSTITUTE_REF is not set here. */ ++ctxt->depth; ret = xmlStringDecodeEntities(ctxt, buf, XML_SUBSTITUTE_PEREF, 0, 0, 0); --ctxt->depth; if (orig != NULL) *orig = buf; else xmlFree(buf); } return(ret); } /** * xmlParseAttValueComplex: * @ctxt: an XML parser context * @len: the resulting attribute len * @normalize: wether to apply the inner normalization * * parse a value for an attribute, this is the fallback function * of xmlParseAttValue() when the attribute parsing requires handling * of non-ASCII characters, or normalization compaction. * * Returns the AttValue parsed or NULL. The value has to be freed by the caller. */ static xmlChar * xmlParseAttValueComplex(xmlParserCtxtPtr ctxt, int *attlen, int normalize) { xmlChar limit = 0; xmlChar *buf = NULL; xmlChar *rep = NULL; size_t len = 0; size_t buf_size = 0; int c, l, in_space = 0; xmlChar *current = NULL; xmlEntityPtr ent; if (NXT(0) == '"') { ctxt->instate = XML_PARSER_ATTRIBUTE_VALUE; limit = '"'; NEXT; } else if (NXT(0) == '\'') { limit = '\''; ctxt->instate = XML_PARSER_ATTRIBUTE_VALUE; NEXT; } else { xmlFatalErr(ctxt, XML_ERR_ATTRIBUTE_NOT_STARTED, NULL); return(NULL); } /* * allocate a translation buffer. */ buf_size = XML_PARSER_BUFFER_SIZE; buf = (xmlChar *) xmlMallocAtomic(buf_size); if (buf == NULL) goto mem_error; /* * OK loop until we reach one of the ending char or a size limit. */ c = CUR_CHAR(l); while (((NXT(0) != limit) && /* checked */ (IS_CHAR(c)) && (c != '<')) && (ctxt->instate != XML_PARSER_EOF)) { /* * Impose a reasonable limit on attribute size, unless XML_PARSE_HUGE * special option is given */ if ((len > XML_MAX_TEXT_LENGTH) && ((ctxt->options & XML_PARSE_HUGE) == 0)) { xmlFatalErrMsg(ctxt, XML_ERR_ATTRIBUTE_NOT_FINISHED, "AttValue length too long\n"); goto mem_error; } if (c == 0) break; if (c == '&') { in_space = 0; if (NXT(1) == '#') { int val = xmlParseCharRef(ctxt); if (val == '&') { if (ctxt->replaceEntities) { if (len + 10 > buf_size) { growBuffer(buf, 10); } buf[len++] = '&'; } else { /* * The reparsing will be done in xmlStringGetNodeList() * called by the attribute() function in SAX.c */ if (len + 10 > buf_size) { growBuffer(buf, 10); } buf[len++] = '&'; buf[len++] = '#'; buf[len++] = '3'; buf[len++] = '8'; buf[len++] = ';'; } } else if (val != 0) { if (len + 10 > buf_size) { growBuffer(buf, 10); } len += xmlCopyChar(0, &buf[len], val); } } else { ent = xmlParseEntityRef(ctxt); ctxt->nbentities++; if (ent != NULL) ctxt->nbentities += ent->owner; if ((ent != NULL) && (ent->etype == XML_INTERNAL_PREDEFINED_ENTITY)) { if (len + 10 > buf_size) { growBuffer(buf, 10); } if ((ctxt->replaceEntities == 0) && (ent->content[0] == '&')) { buf[len++] = '&'; buf[len++] = '#'; buf[len++] = '3'; buf[len++] = '8'; buf[len++] = ';'; } else { buf[len++] = ent->content[0]; } } else if ((ent != NULL) && (ctxt->replaceEntities != 0)) { if (ent->etype != XML_INTERNAL_PREDEFINED_ENTITY) { ++ctxt->depth; rep = xmlStringDecodeEntities(ctxt, ent->content, XML_SUBSTITUTE_REF, 0, 0, 0); --ctxt->depth; if (rep != NULL) { current = rep; while (*current != 0) { /* non input consuming */ if ((*current == 0xD) || (*current == 0xA) || (*current == 0x9)) { buf[len++] = 0x20; current++; } else buf[len++] = *current++; if (len + 10 > buf_size) { growBuffer(buf, 10); } } xmlFree(rep); rep = NULL; } } else { if (len + 10 > buf_size) { growBuffer(buf, 10); } if (ent->content != NULL) buf[len++] = ent->content[0]; } } else if (ent != NULL) { int i = xmlStrlen(ent->name); const xmlChar *cur = ent->name; /* * This may look absurd but is needed to detect * entities problems */ if ((ent->etype != XML_INTERNAL_PREDEFINED_ENTITY) && (ent->content != NULL) && (ent->checked == 0)) { unsigned long oldnbent = ctxt->nbentities; ++ctxt->depth; rep = xmlStringDecodeEntities(ctxt, ent->content, XML_SUBSTITUTE_REF, 0, 0, 0); --ctxt->depth; ent->checked = (ctxt->nbentities - oldnbent + 1) * 2; if (rep != NULL) { if (xmlStrchr(rep, '<')) ent->checked |= 1; xmlFree(rep); rep = NULL; } } /* * Just output the reference */ buf[len++] = '&'; while (len + i + 10 > buf_size) { growBuffer(buf, i + 10); } for (;i > 0;i--) buf[len++] = *cur++; buf[len++] = ';'; } } } else { if ((c == 0x20) || (c == 0xD) || (c == 0xA) || (c == 0x9)) { if ((len != 0) || (!normalize)) { if ((!normalize) || (!in_space)) { COPY_BUF(l,buf,len,0x20); while (len + 10 > buf_size) { growBuffer(buf, 10); } } in_space = 1; } } else { in_space = 0; COPY_BUF(l,buf,len,c); if (len + 10 > buf_size) { growBuffer(buf, 10); } } NEXTL(l); } GROW; c = CUR_CHAR(l); } if (ctxt->instate == XML_PARSER_EOF) goto error; if ((in_space) && (normalize)) { while ((len > 0) && (buf[len - 1] == 0x20)) len--; } buf[len] = 0; if (RAW == '<') { xmlFatalErr(ctxt, XML_ERR_LT_IN_ATTRIBUTE, NULL); } else if (RAW != limit) { if ((c != 0) && (!IS_CHAR(c))) { xmlFatalErrMsg(ctxt, XML_ERR_INVALID_CHAR, "invalid character in attribute value\n"); } else { xmlFatalErrMsg(ctxt, XML_ERR_ATTRIBUTE_NOT_FINISHED, "AttValue: ' expected\n"); } } else NEXT; /* * There we potentially risk an overflow, don't allow attribute value of * length more than INT_MAX it is a very reasonnable assumption ! */ if (len >= INT_MAX) { xmlFatalErrMsg(ctxt, XML_ERR_ATTRIBUTE_NOT_FINISHED, "AttValue length too long\n"); goto mem_error; } if (attlen != NULL) *attlen = (int) len; return(buf); mem_error: xmlErrMemory(ctxt, NULL); error: if (buf != NULL) xmlFree(buf); if (rep != NULL) xmlFree(rep); return(NULL); } /** * xmlParseAttValue: * @ctxt: an XML parser context * * parse a value for an attribute * Note: the parser won't do substitution of entities here, this * will be handled later in xmlStringGetNodeList * * [10] AttValue ::= '"' ([^<&"] | Reference)* '"' | * "'" ([^<&'] | Reference)* "'" * * 3.3.3 Attribute-Value Normalization: * Before the value of an attribute is passed to the application or * checked for validity, the XML processor must normalize it as follows: * - a character reference is processed by appending the referenced * character to the attribute value * - an entity reference is processed by recursively processing the * replacement text of the entity * - a whitespace character (#x20, #xD, #xA, #x9) is processed by * appending #x20 to the normalized value, except that only a single * #x20 is appended for a "#xD#xA" sequence that is part of an external * parsed entity or the literal entity value of an internal parsed entity * - other characters are processed by appending them to the normalized value * If the declared value is not CDATA, then the XML processor must further * process the normalized attribute value by discarding any leading and * trailing space (#x20) characters, and by replacing sequences of space * (#x20) characters by a single space (#x20) character. * All attributes for which no declaration has been read should be treated * by a non-validating parser as if declared CDATA. * * Returns the AttValue parsed or NULL. The value has to be freed by the caller. */ xmlChar * xmlParseAttValue(xmlParserCtxtPtr ctxt) { if ((ctxt == NULL) || (ctxt->input == NULL)) return(NULL); return(xmlParseAttValueInternal(ctxt, NULL, NULL, 0)); } /** * xmlParseSystemLiteral: * @ctxt: an XML parser context * * parse an XML Literal * * [11] SystemLiteral ::= ('"' [^"]* '"') | ("'" [^']* "'") * * Returns the SystemLiteral parsed or NULL */ xmlChar * xmlParseSystemLiteral(xmlParserCtxtPtr ctxt) { xmlChar *buf = NULL; int len = 0; int size = XML_PARSER_BUFFER_SIZE; int cur, l; xmlChar stop; int state = ctxt->instate; int count = 0; SHRINK; if (RAW == '"') { NEXT; stop = '"'; } else if (RAW == '\'') { NEXT; stop = '\''; } else { xmlFatalErr(ctxt, XML_ERR_LITERAL_NOT_STARTED, NULL); return(NULL); } buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar)); if (buf == NULL) { xmlErrMemory(ctxt, NULL); return(NULL); } ctxt->instate = XML_PARSER_SYSTEM_LITERAL; cur = CUR_CHAR(l); while ((IS_CHAR(cur)) && (cur != stop)) { /* checked */ if (len + 5 >= size) { xmlChar *tmp; if ((size > XML_MAX_NAME_LENGTH) && ((ctxt->options & XML_PARSE_HUGE) == 0)) { xmlFatalErr(ctxt, XML_ERR_NAME_TOO_LONG, "SystemLiteral"); xmlFree(buf); ctxt->instate = (xmlParserInputState) state; return(NULL); } size *= 2; tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar)); if (tmp == NULL) { xmlFree(buf); xmlErrMemory(ctxt, NULL); ctxt->instate = (xmlParserInputState) state; return(NULL); } buf = tmp; } count++; if (count > 50) { GROW; count = 0; if (ctxt->instate == XML_PARSER_EOF) { xmlFree(buf); return(NULL); } } COPY_BUF(l,buf,len,cur); NEXTL(l); cur = CUR_CHAR(l); if (cur == 0) { GROW; SHRINK; cur = CUR_CHAR(l); } } buf[len] = 0; ctxt->instate = (xmlParserInputState) state; if (!IS_CHAR(cur)) { xmlFatalErr(ctxt, XML_ERR_LITERAL_NOT_FINISHED, NULL); } else { NEXT; } return(buf); } /** * xmlParsePubidLiteral: * @ctxt: an XML parser context * * parse an XML public literal * * [12] PubidLiteral ::= '"' PubidChar* '"' | "'" (PubidChar - "'")* "'" * * Returns the PubidLiteral parsed or NULL. */ xmlChar * xmlParsePubidLiteral(xmlParserCtxtPtr ctxt) { xmlChar *buf = NULL; int len = 0; int size = XML_PARSER_BUFFER_SIZE; xmlChar cur; xmlChar stop; int count = 0; xmlParserInputState oldstate = ctxt->instate; SHRINK; if (RAW == '"') { NEXT; stop = '"'; } else if (RAW == '\'') { NEXT; stop = '\''; } else { xmlFatalErr(ctxt, XML_ERR_LITERAL_NOT_STARTED, NULL); return(NULL); } buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar)); if (buf == NULL) { xmlErrMemory(ctxt, NULL); return(NULL); } ctxt->instate = XML_PARSER_PUBLIC_LITERAL; cur = CUR; while ((IS_PUBIDCHAR_CH(cur)) && (cur != stop)) { /* checked */ if (len + 1 >= size) { xmlChar *tmp; if ((size > XML_MAX_NAME_LENGTH) && ((ctxt->options & XML_PARSE_HUGE) == 0)) { xmlFatalErr(ctxt, XML_ERR_NAME_TOO_LONG, "Public ID"); xmlFree(buf); return(NULL); } size *= 2; tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar)); if (tmp == NULL) { xmlErrMemory(ctxt, NULL); xmlFree(buf); return(NULL); } buf = tmp; } buf[len++] = cur; count++; if (count > 50) { GROW; count = 0; if (ctxt->instate == XML_PARSER_EOF) { xmlFree(buf); return(NULL); } } NEXT; cur = CUR; if (cur == 0) { GROW; SHRINK; cur = CUR; } } buf[len] = 0; if (cur != stop) { xmlFatalErr(ctxt, XML_ERR_LITERAL_NOT_FINISHED, NULL); } else { NEXT; } ctxt->instate = oldstate; return(buf); } static void xmlParseCharDataComplex(xmlParserCtxtPtr ctxt, int cdata); /* * used for the test in the inner loop of the char data testing */ static const unsigned char test_char_data[256] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x9, CR/LF separated */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x00, 0x27, /* & */ 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x00, 0x3D, 0x3E, 0x3F, /* < */ 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x00, 0x5E, 0x5F, /* ] */ 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* non-ascii */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; /** * xmlParseCharData: * @ctxt: an XML parser context * @cdata: int indicating whether we are within a CDATA section * * parse a CharData section. * if we are within a CDATA section ']]>' marks an end of section. * * The right angle bracket (>) may be represented using the string "&gt;", * and must, for compatibility, be escaped using "&gt;" or a character * reference when it appears in the string "]]>" in content, when that * string is not marking the end of a CDATA section. * * [14] CharData ::= [^<&]* - ([^<&]* ']]>' [^<&]*) */ void xmlParseCharData(xmlParserCtxtPtr ctxt, int cdata) { const xmlChar *in; int nbchar = 0; int line = ctxt->input->line; int col = ctxt->input->col; int ccol; SHRINK; GROW; /* * Accelerated common case where input don't need to be * modified before passing it to the handler. */ if (!cdata) { in = ctxt->input->cur; do { get_more_space: while (*in == 0x20) { in++; ctxt->input->col++; } if (*in == 0xA) { do { ctxt->input->line++; ctxt->input->col = 1; in++; } while (*in == 0xA); goto get_more_space; } if (*in == '<') { nbchar = in - ctxt->input->cur; if (nbchar > 0) { const xmlChar *tmp = ctxt->input->cur; ctxt->input->cur = in; if ((ctxt->sax != NULL) && (ctxt->sax->ignorableWhitespace != ctxt->sax->characters)) { if (areBlanks(ctxt, tmp, nbchar, 1)) { if (ctxt->sax->ignorableWhitespace != NULL) ctxt->sax->ignorableWhitespace(ctxt->userData, tmp, nbchar); } else { if (ctxt->sax->characters != NULL) ctxt->sax->characters(ctxt->userData, tmp, nbchar); if (*ctxt->space == -1) *ctxt->space = -2; } } else if ((ctxt->sax != NULL) && (ctxt->sax->characters != NULL)) { ctxt->sax->characters(ctxt->userData, tmp, nbchar); } } return; } get_more: ccol = ctxt->input->col; while (test_char_data[*in]) { in++; ccol++; } ctxt->input->col = ccol; if (*in == 0xA) { do { ctxt->input->line++; ctxt->input->col = 1; in++; } while (*in == 0xA); goto get_more; } if (*in == ']') { if ((in[1] == ']') && (in[2] == '>')) { xmlFatalErr(ctxt, XML_ERR_MISPLACED_CDATA_END, NULL); ctxt->input->cur = in; return; } in++; ctxt->input->col++; goto get_more; } nbchar = in - ctxt->input->cur; if (nbchar > 0) { if ((ctxt->sax != NULL) && (ctxt->sax->ignorableWhitespace != ctxt->sax->characters) && (IS_BLANK_CH(*ctxt->input->cur))) { const xmlChar *tmp = ctxt->input->cur; ctxt->input->cur = in; if (areBlanks(ctxt, tmp, nbchar, 0)) { if (ctxt->sax->ignorableWhitespace != NULL) ctxt->sax->ignorableWhitespace(ctxt->userData, tmp, nbchar); } else { if (ctxt->sax->characters != NULL) ctxt->sax->characters(ctxt->userData, tmp, nbchar); if (*ctxt->space == -1) *ctxt->space = -2; } line = ctxt->input->line; col = ctxt->input->col; } else if (ctxt->sax != NULL) { if (ctxt->sax->characters != NULL) ctxt->sax->characters(ctxt->userData, ctxt->input->cur, nbchar); line = ctxt->input->line; col = ctxt->input->col; } /* something really bad happened in the SAX callback */ if (ctxt->instate != XML_PARSER_CONTENT) return; } ctxt->input->cur = in; if (*in == 0xD) { in++; if (*in == 0xA) { ctxt->input->cur = in; in++; ctxt->input->line++; ctxt->input->col = 1; continue; /* while */ } in--; } if (*in == '<') { return; } if (*in == '&') { return; } SHRINK; GROW; if (ctxt->instate == XML_PARSER_EOF) return; in = ctxt->input->cur; } while (((*in >= 0x20) && (*in <= 0x7F)) || (*in == 0x09)); nbchar = 0; } ctxt->input->line = line; ctxt->input->col = col; xmlParseCharDataComplex(ctxt, cdata); } /** * xmlParseCharDataComplex: * @ctxt: an XML parser context * @cdata: int indicating whether we are within a CDATA section * * parse a CharData section.this is the fallback function * of xmlParseCharData() when the parsing requires handling * of non-ASCII characters. */ static void xmlParseCharDataComplex(xmlParserCtxtPtr ctxt, int cdata) { xmlChar buf[XML_PARSER_BIG_BUFFER_SIZE + 5]; int nbchar = 0; int cur, l; int count = 0; SHRINK; GROW; cur = CUR_CHAR(l); while ((cur != '<') && /* checked */ (cur != '&') && (IS_CHAR(cur))) /* test also done in xmlCurrentChar() */ { if ((cur == ']') && (NXT(1) == ']') && (NXT(2) == '>')) { if (cdata) break; else { xmlFatalErr(ctxt, XML_ERR_MISPLACED_CDATA_END, NULL); } } COPY_BUF(l,buf,nbchar,cur); if (nbchar >= XML_PARSER_BIG_BUFFER_SIZE) { buf[nbchar] = 0; /* * OK the segment is to be consumed as chars. */ if ((ctxt->sax != NULL) && (!ctxt->disableSAX)) { if (areBlanks(ctxt, buf, nbchar, 0)) { if (ctxt->sax->ignorableWhitespace != NULL) ctxt->sax->ignorableWhitespace(ctxt->userData, buf, nbchar); } else { if (ctxt->sax->characters != NULL) ctxt->sax->characters(ctxt->userData, buf, nbchar); if ((ctxt->sax->characters != ctxt->sax->ignorableWhitespace) && (*ctxt->space == -1)) *ctxt->space = -2; } } nbchar = 0; /* something really bad happened in the SAX callback */ if (ctxt->instate != XML_PARSER_CONTENT) return; } count++; if (count > 50) { GROW; count = 0; if (ctxt->instate == XML_PARSER_EOF) return; } NEXTL(l); cur = CUR_CHAR(l); } if (nbchar != 0) { buf[nbchar] = 0; /* * OK the segment is to be consumed as chars. */ if ((ctxt->sax != NULL) && (!ctxt->disableSAX)) { if (areBlanks(ctxt, buf, nbchar, 0)) { if (ctxt->sax->ignorableWhitespace != NULL) ctxt->sax->ignorableWhitespace(ctxt->userData, buf, nbchar); } else { if (ctxt->sax->characters != NULL) ctxt->sax->characters(ctxt->userData, buf, nbchar); if ((ctxt->sax->characters != ctxt->sax->ignorableWhitespace) && (*ctxt->space == -1)) *ctxt->space = -2; } } } if ((cur != 0) && (!IS_CHAR(cur))) { /* Generate the error and skip the offending character */ xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR, "PCDATA invalid Char value %d\n", cur); NEXTL(l); } } /** * xmlParseExternalID: * @ctxt: an XML parser context * @publicID: a xmlChar** receiving PubidLiteral * @strict: indicate whether we should restrict parsing to only * production [75], see NOTE below * * Parse an External ID or a Public ID * * NOTE: Productions [75] and [83] interact badly since [75] can generate * 'PUBLIC' S PubidLiteral S SystemLiteral * * [75] ExternalID ::= 'SYSTEM' S SystemLiteral * | 'PUBLIC' S PubidLiteral S SystemLiteral * * [83] PublicID ::= 'PUBLIC' S PubidLiteral * * Returns the function returns SystemLiteral and in the second * case publicID receives PubidLiteral, is strict is off * it is possible to return NULL and have publicID set. */ xmlChar * xmlParseExternalID(xmlParserCtxtPtr ctxt, xmlChar **publicID, int strict) { xmlChar *URI = NULL; SHRINK; *publicID = NULL; if (CMP6(CUR_PTR, 'S', 'Y', 'S', 'T', 'E', 'M')) { SKIP(6); if (!IS_BLANK_CH(CUR)) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "Space required after 'SYSTEM'\n"); } SKIP_BLANKS; URI = xmlParseSystemLiteral(ctxt); if (URI == NULL) { xmlFatalErr(ctxt, XML_ERR_URI_REQUIRED, NULL); } } else if (CMP6(CUR_PTR, 'P', 'U', 'B', 'L', 'I', 'C')) { SKIP(6); if (!IS_BLANK_CH(CUR)) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "Space required after 'PUBLIC'\n"); } SKIP_BLANKS; *publicID = xmlParsePubidLiteral(ctxt); if (*publicID == NULL) { xmlFatalErr(ctxt, XML_ERR_PUBID_REQUIRED, NULL); } if (strict) { /* * We don't handle [83] so "S SystemLiteral" is required. */ if (!IS_BLANK_CH(CUR)) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "Space required after the Public Identifier\n"); } } else { /* * We handle [83] so we return immediately, if * "S SystemLiteral" is not detected. From a purely parsing * point of view that's a nice mess. */ const xmlChar *ptr; GROW; ptr = CUR_PTR; if (!IS_BLANK_CH(*ptr)) return(NULL); while (IS_BLANK_CH(*ptr)) ptr++; /* TODO: dangerous, fix ! */ if ((*ptr != '\'') && (*ptr != '"')) return(NULL); } SKIP_BLANKS; URI = xmlParseSystemLiteral(ctxt); if (URI == NULL) { xmlFatalErr(ctxt, XML_ERR_URI_REQUIRED, NULL); } } return(URI); } /** * xmlParseCommentComplex: * @ctxt: an XML parser context * @buf: the already parsed part of the buffer * @len: number of bytes filles in the buffer * @size: allocated size of the buffer * * Skip an XML (SGML) comment <!-- .... --> * The spec says that "For compatibility, the string "--" (double-hyphen) * must not occur within comments. " * This is the slow routine in case the accelerator for ascii didn't work * * [15] Comment ::= '<!--' ((Char - '-') | ('-' (Char - '-')))* '-->' */ static void xmlParseCommentComplex(xmlParserCtxtPtr ctxt, xmlChar *buf, size_t len, size_t size) { int q, ql; int r, rl; int cur, l; size_t count = 0; int inputid; inputid = ctxt->input->id; if (buf == NULL) { len = 0; size = XML_PARSER_BUFFER_SIZE; buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar)); if (buf == NULL) { xmlErrMemory(ctxt, NULL); return; } } GROW; /* Assure there's enough input data */ q = CUR_CHAR(ql); if (q == 0) goto not_terminated; if (!IS_CHAR(q)) { xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR, "xmlParseComment: invalid xmlChar value %d\n", q); xmlFree (buf); return; } NEXTL(ql); r = CUR_CHAR(rl); if (r == 0) goto not_terminated; if (!IS_CHAR(r)) { xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR, "xmlParseComment: invalid xmlChar value %d\n", q); xmlFree (buf); return; } NEXTL(rl); cur = CUR_CHAR(l); if (cur == 0) goto not_terminated; while (IS_CHAR(cur) && /* checked */ ((cur != '>') || (r != '-') || (q != '-'))) { if ((r == '-') && (q == '-')) { xmlFatalErr(ctxt, XML_ERR_HYPHEN_IN_COMMENT, NULL); } if ((len > XML_MAX_TEXT_LENGTH) && ((ctxt->options & XML_PARSE_HUGE) == 0)) { xmlFatalErrMsgStr(ctxt, XML_ERR_COMMENT_NOT_FINISHED, "Comment too big found", NULL); xmlFree (buf); return; } if (len + 5 >= size) { xmlChar *new_buf; size_t new_size; new_size = size * 2; new_buf = (xmlChar *) xmlRealloc(buf, new_size); if (new_buf == NULL) { xmlFree (buf); xmlErrMemory(ctxt, NULL); return; } buf = new_buf; size = new_size; } COPY_BUF(ql,buf,len,q); q = r; ql = rl; r = cur; rl = l; count++; if (count > 50) { GROW; count = 0; if (ctxt->instate == XML_PARSER_EOF) { xmlFree(buf); return; } } NEXTL(l); cur = CUR_CHAR(l); if (cur == 0) { SHRINK; GROW; cur = CUR_CHAR(l); } } buf[len] = 0; if (cur == 0) { xmlFatalErrMsgStr(ctxt, XML_ERR_COMMENT_NOT_FINISHED, "Comment not terminated \n<!--%.50s\n", buf); } else if (!IS_CHAR(cur)) { xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR, "xmlParseComment: invalid xmlChar value %d\n", cur); } else { if (inputid != ctxt->input->id) { xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY, "Comment doesn't start and stop in the same entity\n"); } NEXT; if ((ctxt->sax != NULL) && (ctxt->sax->comment != NULL) && (!ctxt->disableSAX)) ctxt->sax->comment(ctxt->userData, buf); } xmlFree(buf); return; not_terminated: xmlFatalErrMsgStr(ctxt, XML_ERR_COMMENT_NOT_FINISHED, "Comment not terminated\n", NULL); xmlFree(buf); return; } /** * xmlParseComment: * @ctxt: an XML parser context * * Skip an XML (SGML) comment <!-- .... --> * The spec says that "For compatibility, the string "--" (double-hyphen) * must not occur within comments. " * * [15] Comment ::= '<!--' ((Char - '-') | ('-' (Char - '-')))* '-->' */ void xmlParseComment(xmlParserCtxtPtr ctxt) { xmlChar *buf = NULL; size_t size = XML_PARSER_BUFFER_SIZE; size_t len = 0; xmlParserInputState state; const xmlChar *in; size_t nbchar = 0; int ccol; int inputid; /* * Check that there is a comment right here. */ if ((RAW != '<') || (NXT(1) != '!') || (NXT(2) != '-') || (NXT(3) != '-')) return; state = ctxt->instate; ctxt->instate = XML_PARSER_COMMENT; inputid = ctxt->input->id; SKIP(4); SHRINK; GROW; /* * Accelerated common case where input don't need to be * modified before passing it to the handler. */ in = ctxt->input->cur; do { if (*in == 0xA) { do { ctxt->input->line++; ctxt->input->col = 1; in++; } while (*in == 0xA); } get_more: ccol = ctxt->input->col; while (((*in > '-') && (*in <= 0x7F)) || ((*in >= 0x20) && (*in < '-')) || (*in == 0x09)) { in++; ccol++; } ctxt->input->col = ccol; if (*in == 0xA) { do { ctxt->input->line++; ctxt->input->col = 1; in++; } while (*in == 0xA); goto get_more; } nbchar = in - ctxt->input->cur; /* * save current set of data */ if (nbchar > 0) { if ((ctxt->sax != NULL) && (ctxt->sax->comment != NULL)) { if (buf == NULL) { if ((*in == '-') && (in[1] == '-')) size = nbchar + 1; else size = XML_PARSER_BUFFER_SIZE + nbchar; buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar)); if (buf == NULL) { xmlErrMemory(ctxt, NULL); ctxt->instate = state; return; } len = 0; } else if (len + nbchar + 1 >= size) { xmlChar *new_buf; size += len + nbchar + XML_PARSER_BUFFER_SIZE; new_buf = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar)); if (new_buf == NULL) { xmlFree (buf); xmlErrMemory(ctxt, NULL); ctxt->instate = state; return; } buf = new_buf; } memcpy(&buf[len], ctxt->input->cur, nbchar); len += nbchar; buf[len] = 0; } } if ((len > XML_MAX_TEXT_LENGTH) && ((ctxt->options & XML_PARSE_HUGE) == 0)) { xmlFatalErrMsgStr(ctxt, XML_ERR_COMMENT_NOT_FINISHED, "Comment too big found", NULL); xmlFree (buf); return; } ctxt->input->cur = in; if (*in == 0xA) { in++; ctxt->input->line++; ctxt->input->col = 1; } if (*in == 0xD) { in++; if (*in == 0xA) { ctxt->input->cur = in; in++; ctxt->input->line++; ctxt->input->col = 1; continue; /* while */ } in--; } SHRINK; GROW; if (ctxt->instate == XML_PARSER_EOF) { xmlFree(buf); return; } in = ctxt->input->cur; if (*in == '-') { if (in[1] == '-') { if (in[2] == '>') { if (ctxt->input->id != inputid) { xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY, "comment doesn't start and stop in the same entity\n"); } SKIP(3); if ((ctxt->sax != NULL) && (ctxt->sax->comment != NULL) && (!ctxt->disableSAX)) { if (buf != NULL) ctxt->sax->comment(ctxt->userData, buf); else ctxt->sax->comment(ctxt->userData, BAD_CAST ""); } if (buf != NULL) xmlFree(buf); if (ctxt->instate != XML_PARSER_EOF) ctxt->instate = state; return; } if (buf != NULL) { xmlFatalErrMsgStr(ctxt, XML_ERR_HYPHEN_IN_COMMENT, "Double hyphen within comment: " "<!--%.50s\n", buf); } else xmlFatalErrMsgStr(ctxt, XML_ERR_HYPHEN_IN_COMMENT, "Double hyphen within comment\n", NULL); in++; ctxt->input->col++; } in++; ctxt->input->col++; goto get_more; } } while (((*in >= 0x20) && (*in <= 0x7F)) || (*in == 0x09)); xmlParseCommentComplex(ctxt, buf, len, size); ctxt->instate = state; return; } /** * xmlParsePITarget: * @ctxt: an XML parser context * * parse the name of a PI * * [17] PITarget ::= Name - (('X' | 'x') ('M' | 'm') ('L' | 'l')) * * Returns the PITarget name or NULL */ const xmlChar * xmlParsePITarget(xmlParserCtxtPtr ctxt) { const xmlChar *name; name = xmlParseName(ctxt); if ((name != NULL) && ((name[0] == 'x') || (name[0] == 'X')) && ((name[1] == 'm') || (name[1] == 'M')) && ((name[2] == 'l') || (name[2] == 'L'))) { int i; if ((name[0] == 'x') && (name[1] == 'm') && (name[2] == 'l') && (name[3] == 0)) { xmlFatalErrMsg(ctxt, XML_ERR_RESERVED_XML_NAME, "XML declaration allowed only at the start of the document\n"); return(name); } else if (name[3] == 0) { xmlFatalErr(ctxt, XML_ERR_RESERVED_XML_NAME, NULL); return(name); } for (i = 0;;i++) { if (xmlW3CPIs[i] == NULL) break; if (xmlStrEqual(name, (const xmlChar *)xmlW3CPIs[i])) return(name); } xmlWarningMsg(ctxt, XML_ERR_RESERVED_XML_NAME, "xmlParsePITarget: invalid name prefix 'xml'\n", NULL, NULL); } if ((name != NULL) && (xmlStrchr(name, ':') != NULL)) { xmlNsErr(ctxt, XML_NS_ERR_COLON, "colons are forbidden from PI names '%s'\n", name, NULL, NULL); } return(name); } #ifdef LIBXML_CATALOG_ENABLED /** * xmlParseCatalogPI: * @ctxt: an XML parser context * @catalog: the PI value string * * parse an XML Catalog Processing Instruction. * * <?oasis-xml-catalog catalog="http://example.com/catalog.xml"?> * * Occurs only if allowed by the user and if happening in the Misc * part of the document before any doctype informations * This will add the given catalog to the parsing context in order * to be used if there is a resolution need further down in the document */ static void xmlParseCatalogPI(xmlParserCtxtPtr ctxt, const xmlChar *catalog) { xmlChar *URL = NULL; const xmlChar *tmp, *base; xmlChar marker; tmp = catalog; while (IS_BLANK_CH(*tmp)) tmp++; if (xmlStrncmp(tmp, BAD_CAST"catalog", 7)) goto error; tmp += 7; while (IS_BLANK_CH(*tmp)) tmp++; if (*tmp != '=') { return; } tmp++; while (IS_BLANK_CH(*tmp)) tmp++; marker = *tmp; if ((marker != '\'') && (marker != '"')) goto error; tmp++; base = tmp; while ((*tmp != 0) && (*tmp != marker)) tmp++; if (*tmp == 0) goto error; URL = xmlStrndup(base, tmp - base); tmp++; while (IS_BLANK_CH(*tmp)) tmp++; if (*tmp != 0) goto error; if (URL != NULL) { ctxt->catalogs = xmlCatalogAddLocal(ctxt->catalogs, URL); xmlFree(URL); } return; error: xmlWarningMsg(ctxt, XML_WAR_CATALOG_PI, "Catalog PI syntax error: %s\n", catalog, NULL); if (URL != NULL) xmlFree(URL); } #endif /** * xmlParsePI: * @ctxt: an XML parser context * * parse an XML Processing Instruction. * * [16] PI ::= '<?' PITarget (S (Char* - (Char* '?>' Char*)))? '?>' * * The processing is transfered to SAX once parsed. */ void xmlParsePI(xmlParserCtxtPtr ctxt) { xmlChar *buf = NULL; size_t len = 0; size_t size = XML_PARSER_BUFFER_SIZE; int cur, l; const xmlChar *target; xmlParserInputState state; int count = 0; if ((RAW == '<') && (NXT(1) == '?')) { xmlParserInputPtr input = ctxt->input; state = ctxt->instate; ctxt->instate = XML_PARSER_PI; /* * this is a Processing Instruction. */ SKIP(2); SHRINK; /* * Parse the target name and check for special support like * namespace. */ target = xmlParsePITarget(ctxt); if (target != NULL) { if ((RAW == '?') && (NXT(1) == '>')) { if (input != ctxt->input) { xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY, "PI declaration doesn't start and stop in the same entity\n"); } SKIP(2); /* * SAX: PI detected. */ if ((ctxt->sax) && (!ctxt->disableSAX) && (ctxt->sax->processingInstruction != NULL)) ctxt->sax->processingInstruction(ctxt->userData, target, NULL); if (ctxt->instate != XML_PARSER_EOF) ctxt->instate = state; return; } buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar)); if (buf == NULL) { xmlErrMemory(ctxt, NULL); ctxt->instate = state; return; } cur = CUR; if (!IS_BLANK(cur)) { xmlFatalErrMsgStr(ctxt, XML_ERR_SPACE_REQUIRED, "ParsePI: PI %s space expected\n", target); } SKIP_BLANKS; cur = CUR_CHAR(l); while (IS_CHAR(cur) && /* checked */ ((cur != '?') || (NXT(1) != '>'))) { if (len + 5 >= size) { xmlChar *tmp; size_t new_size = size * 2; tmp = (xmlChar *) xmlRealloc(buf, new_size); if (tmp == NULL) { xmlErrMemory(ctxt, NULL); xmlFree(buf); ctxt->instate = state; return; } buf = tmp; size = new_size; } count++; if (count > 50) { GROW; if (ctxt->instate == XML_PARSER_EOF) { xmlFree(buf); return; } count = 0; if ((len > XML_MAX_TEXT_LENGTH) && ((ctxt->options & XML_PARSE_HUGE) == 0)) { xmlFatalErrMsgStr(ctxt, XML_ERR_PI_NOT_FINISHED, "PI %s too big found", target); xmlFree(buf); ctxt->instate = state; return; } } COPY_BUF(l,buf,len,cur); NEXTL(l); cur = CUR_CHAR(l); if (cur == 0) { SHRINK; GROW; cur = CUR_CHAR(l); } } if ((len > XML_MAX_TEXT_LENGTH) && ((ctxt->options & XML_PARSE_HUGE) == 0)) { xmlFatalErrMsgStr(ctxt, XML_ERR_PI_NOT_FINISHED, "PI %s too big found", target); xmlFree(buf); ctxt->instate = state; return; } buf[len] = 0; if (cur != '?') { xmlFatalErrMsgStr(ctxt, XML_ERR_PI_NOT_FINISHED, "ParsePI: PI %s never end ...\n", target); } else { if (input != ctxt->input) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "PI declaration doesn't start and stop in the same entity\n"); } SKIP(2); #ifdef LIBXML_CATALOG_ENABLED if (((state == XML_PARSER_MISC) || (state == XML_PARSER_START)) && (xmlStrEqual(target, XML_CATALOG_PI))) { xmlCatalogAllow allow = xmlCatalogGetDefaults(); if ((allow == XML_CATA_ALLOW_DOCUMENT) || (allow == XML_CATA_ALLOW_ALL)) xmlParseCatalogPI(ctxt, buf); } #endif /* * SAX: PI detected. */ if ((ctxt->sax) && (!ctxt->disableSAX) && (ctxt->sax->processingInstruction != NULL)) ctxt->sax->processingInstruction(ctxt->userData, target, buf); } xmlFree(buf); } else { xmlFatalErr(ctxt, XML_ERR_PI_NOT_STARTED, NULL); } if (ctxt->instate != XML_PARSER_EOF) ctxt->instate = state; } } /** * xmlParseNotationDecl: * @ctxt: an XML parser context * * parse a notation declaration * * [82] NotationDecl ::= '<!NOTATION' S Name S (ExternalID | PublicID) S? '>' * * Hence there is actually 3 choices: * 'PUBLIC' S PubidLiteral * 'PUBLIC' S PubidLiteral S SystemLiteral * and 'SYSTEM' S SystemLiteral * * See the NOTE on xmlParseExternalID(). */ void xmlParseNotationDecl(xmlParserCtxtPtr ctxt) { const xmlChar *name; xmlChar *Pubid; xmlChar *Systemid; if (CMP10(CUR_PTR, '<', '!', 'N', 'O', 'T', 'A', 'T', 'I', 'O', 'N')) { xmlParserInputPtr input = ctxt->input; SHRINK; SKIP(10); if (!IS_BLANK_CH(CUR)) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "Space required after '<!NOTATION'\n"); return; } SKIP_BLANKS; name = xmlParseName(ctxt); if (name == NULL) { xmlFatalErr(ctxt, XML_ERR_NOTATION_NOT_STARTED, NULL); return; } if (!IS_BLANK_CH(CUR)) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "Space required after the NOTATION name'\n"); return; } if (xmlStrchr(name, ':') != NULL) { xmlNsErr(ctxt, XML_NS_ERR_COLON, "colons are forbidden from notation names '%s'\n", name, NULL, NULL); } SKIP_BLANKS; /* * Parse the IDs. */ Systemid = xmlParseExternalID(ctxt, &Pubid, 0); SKIP_BLANKS; if (RAW == '>') { if (input != ctxt->input) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "Notation declaration doesn't start and stop in the same entity\n"); } NEXT; if ((ctxt->sax != NULL) && (!ctxt->disableSAX) && (ctxt->sax->notationDecl != NULL)) ctxt->sax->notationDecl(ctxt->userData, name, Pubid, Systemid); } else { xmlFatalErr(ctxt, XML_ERR_NOTATION_NOT_FINISHED, NULL); } if (Systemid != NULL) xmlFree(Systemid); if (Pubid != NULL) xmlFree(Pubid); } } /** * xmlParseEntityDecl: * @ctxt: an XML parser context * * parse <!ENTITY declarations * * [70] EntityDecl ::= GEDecl | PEDecl * * [71] GEDecl ::= '<!ENTITY' S Name S EntityDef S? '>' * * [72] PEDecl ::= '<!ENTITY' S '%' S Name S PEDef S? '>' * * [73] EntityDef ::= EntityValue | (ExternalID NDataDecl?) * * [74] PEDef ::= EntityValue | ExternalID * * [76] NDataDecl ::= S 'NDATA' S Name * * [ VC: Notation Declared ] * The Name must match the declared name of a notation. */ void xmlParseEntityDecl(xmlParserCtxtPtr ctxt) { const xmlChar *name = NULL; xmlChar *value = NULL; xmlChar *URI = NULL, *literal = NULL; const xmlChar *ndata = NULL; int isParameter = 0; xmlChar *orig = NULL; int skipped; /* GROW; done in the caller */ if (CMP8(CUR_PTR, '<', '!', 'E', 'N', 'T', 'I', 'T', 'Y')) { xmlParserInputPtr input = ctxt->input; SHRINK; SKIP(8); skipped = SKIP_BLANKS; if (skipped == 0) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "Space required after '<!ENTITY'\n"); } if (RAW == '%') { NEXT; skipped = SKIP_BLANKS; if (skipped == 0) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "Space required after '%%'\n"); } isParameter = 1; } name = xmlParseName(ctxt); if (name == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED, "xmlParseEntityDecl: no name\n"); return; } if (xmlStrchr(name, ':') != NULL) { xmlNsErr(ctxt, XML_NS_ERR_COLON, "colons are forbidden from entities names '%s'\n", name, NULL, NULL); } skipped = SKIP_BLANKS; if (skipped == 0) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "Space required after the entity name\n"); } ctxt->instate = XML_PARSER_ENTITY_DECL; /* * handle the various case of definitions... */ if (isParameter) { if ((RAW == '"') || (RAW == '\'')) { value = xmlParseEntityValue(ctxt, &orig); if (value) { if ((ctxt->sax != NULL) && (!ctxt->disableSAX) && (ctxt->sax->entityDecl != NULL)) ctxt->sax->entityDecl(ctxt->userData, name, XML_INTERNAL_PARAMETER_ENTITY, NULL, NULL, value); } } else { URI = xmlParseExternalID(ctxt, &literal, 1); if ((URI == NULL) && (literal == NULL)) { xmlFatalErr(ctxt, XML_ERR_VALUE_REQUIRED, NULL); } if (URI) { xmlURIPtr uri; uri = xmlParseURI((const char *) URI); if (uri == NULL) { xmlErrMsgStr(ctxt, XML_ERR_INVALID_URI, "Invalid URI: %s\n", URI); /* * This really ought to be a well formedness error * but the XML Core WG decided otherwise c.f. issue * E26 of the XML erratas. */ } else { if (uri->fragment != NULL) { /* * Okay this is foolish to block those but not * invalid URIs. */ xmlFatalErr(ctxt, XML_ERR_URI_FRAGMENT, NULL); } else { if ((ctxt->sax != NULL) && (!ctxt->disableSAX) && (ctxt->sax->entityDecl != NULL)) ctxt->sax->entityDecl(ctxt->userData, name, XML_EXTERNAL_PARAMETER_ENTITY, literal, URI, NULL); } xmlFreeURI(uri); } } } } else { if ((RAW == '"') || (RAW == '\'')) { value = xmlParseEntityValue(ctxt, &orig); if ((ctxt->sax != NULL) && (!ctxt->disableSAX) && (ctxt->sax->entityDecl != NULL)) ctxt->sax->entityDecl(ctxt->userData, name, XML_INTERNAL_GENERAL_ENTITY, NULL, NULL, value); /* * For expat compatibility in SAX mode. */ if ((ctxt->myDoc == NULL) || (xmlStrEqual(ctxt->myDoc->version, SAX_COMPAT_MODE))) { if (ctxt->myDoc == NULL) { ctxt->myDoc = xmlNewDoc(SAX_COMPAT_MODE); if (ctxt->myDoc == NULL) { xmlErrMemory(ctxt, "New Doc failed"); return; } ctxt->myDoc->properties = XML_DOC_INTERNAL; } if (ctxt->myDoc->intSubset == NULL) ctxt->myDoc->intSubset = xmlNewDtd(ctxt->myDoc, BAD_CAST "fake", NULL, NULL); xmlSAX2EntityDecl(ctxt, name, XML_INTERNAL_GENERAL_ENTITY, NULL, NULL, value); } } else { URI = xmlParseExternalID(ctxt, &literal, 1); if ((URI == NULL) && (literal == NULL)) { xmlFatalErr(ctxt, XML_ERR_VALUE_REQUIRED, NULL); } if (URI) { xmlURIPtr uri; uri = xmlParseURI((const char *)URI); if (uri == NULL) { xmlErrMsgStr(ctxt, XML_ERR_INVALID_URI, "Invalid URI: %s\n", URI); /* * This really ought to be a well formedness error * but the XML Core WG decided otherwise c.f. issue * E26 of the XML erratas. */ } else { if (uri->fragment != NULL) { /* * Okay this is foolish to block those but not * invalid URIs. */ xmlFatalErr(ctxt, XML_ERR_URI_FRAGMENT, NULL); } xmlFreeURI(uri); } } if ((RAW != '>') && (!IS_BLANK_CH(CUR))) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "Space required before 'NDATA'\n"); } SKIP_BLANKS; if (CMP5(CUR_PTR, 'N', 'D', 'A', 'T', 'A')) { SKIP(5); if (!IS_BLANK_CH(CUR)) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "Space required after 'NDATA'\n"); } SKIP_BLANKS; ndata = xmlParseName(ctxt); if ((ctxt->sax != NULL) && (!ctxt->disableSAX) && (ctxt->sax->unparsedEntityDecl != NULL)) ctxt->sax->unparsedEntityDecl(ctxt->userData, name, literal, URI, ndata); } else { if ((ctxt->sax != NULL) && (!ctxt->disableSAX) && (ctxt->sax->entityDecl != NULL)) ctxt->sax->entityDecl(ctxt->userData, name, XML_EXTERNAL_GENERAL_PARSED_ENTITY, literal, URI, NULL); /* * For expat compatibility in SAX mode. * assuming the entity repalcement was asked for */ if ((ctxt->replaceEntities != 0) && ((ctxt->myDoc == NULL) || (xmlStrEqual(ctxt->myDoc->version, SAX_COMPAT_MODE)))) { if (ctxt->myDoc == NULL) { ctxt->myDoc = xmlNewDoc(SAX_COMPAT_MODE); if (ctxt->myDoc == NULL) { xmlErrMemory(ctxt, "New Doc failed"); return; } ctxt->myDoc->properties = XML_DOC_INTERNAL; } if (ctxt->myDoc->intSubset == NULL) ctxt->myDoc->intSubset = xmlNewDtd(ctxt->myDoc, BAD_CAST "fake", NULL, NULL); xmlSAX2EntityDecl(ctxt, name, XML_EXTERNAL_GENERAL_PARSED_ENTITY, literal, URI, NULL); } } } } if (ctxt->instate == XML_PARSER_EOF) return; SKIP_BLANKS; if (RAW != '>') { xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_NOT_FINISHED, "xmlParseEntityDecl: entity %s not terminated\n", name); xmlHaltParser(ctxt); } else { if (input != ctxt->input) { xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY, "Entity declaration doesn't start and stop in the same entity\n"); } NEXT; } if (orig != NULL) { /* * Ugly mechanism to save the raw entity value. */ xmlEntityPtr cur = NULL; if (isParameter) { if ((ctxt->sax != NULL) && (ctxt->sax->getParameterEntity != NULL)) cur = ctxt->sax->getParameterEntity(ctxt->userData, name); } else { if ((ctxt->sax != NULL) && (ctxt->sax->getEntity != NULL)) cur = ctxt->sax->getEntity(ctxt->userData, name); if ((cur == NULL) && (ctxt->userData==ctxt)) { cur = xmlSAX2GetEntity(ctxt, name); } } if (cur != NULL) { if (cur->orig != NULL) xmlFree(orig); else cur->orig = orig; } else xmlFree(orig); } if (value != NULL) xmlFree(value); if (URI != NULL) xmlFree(URI); if (literal != NULL) xmlFree(literal); } } /** * xmlParseDefaultDecl: * @ctxt: an XML parser context * @value: Receive a possible fixed default value for the attribute * * Parse an attribute default declaration * * [60] DefaultDecl ::= '#REQUIRED' | '#IMPLIED' | (('#FIXED' S)? AttValue) * * [ VC: Required Attribute ] * if the default declaration is the keyword #REQUIRED, then the * attribute must be specified for all elements of the type in the * attribute-list declaration. * * [ VC: Attribute Default Legal ] * The declared default value must meet the lexical constraints of * the declared attribute type c.f. xmlValidateAttributeDecl() * * [ VC: Fixed Attribute Default ] * if an attribute has a default value declared with the #FIXED * keyword, instances of that attribute must match the default value. * * [ WFC: No < in Attribute Values ] * handled in xmlParseAttValue() * * returns: XML_ATTRIBUTE_NONE, XML_ATTRIBUTE_REQUIRED, XML_ATTRIBUTE_IMPLIED * or XML_ATTRIBUTE_FIXED. */ int xmlParseDefaultDecl(xmlParserCtxtPtr ctxt, xmlChar **value) { int val; xmlChar *ret; *value = NULL; if (CMP9(CUR_PTR, '#', 'R', 'E', 'Q', 'U', 'I', 'R', 'E', 'D')) { SKIP(9); return(XML_ATTRIBUTE_REQUIRED); } if (CMP8(CUR_PTR, '#', 'I', 'M', 'P', 'L', 'I', 'E', 'D')) { SKIP(8); return(XML_ATTRIBUTE_IMPLIED); } val = XML_ATTRIBUTE_NONE; if (CMP6(CUR_PTR, '#', 'F', 'I', 'X', 'E', 'D')) { SKIP(6); val = XML_ATTRIBUTE_FIXED; if (!IS_BLANK_CH(CUR)) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "Space required after '#FIXED'\n"); } SKIP_BLANKS; } ret = xmlParseAttValue(ctxt); ctxt->instate = XML_PARSER_DTD; if (ret == NULL) { xmlFatalErrMsg(ctxt, (xmlParserErrors)ctxt->errNo, "Attribute default value declaration error\n"); } else *value = ret; return(val); } /** * xmlParseNotationType: * @ctxt: an XML parser context * * parse an Notation attribute type. * * Note: the leading 'NOTATION' S part has already being parsed... * * [58] NotationType ::= 'NOTATION' S '(' S? Name (S? '|' S? Name)* S? ')' * * [ VC: Notation Attributes ] * Values of this type must match one of the notation names included * in the declaration; all notation names in the declaration must be declared. * * Returns: the notation attribute tree built while parsing */ xmlEnumerationPtr xmlParseNotationType(xmlParserCtxtPtr ctxt) { const xmlChar *name; xmlEnumerationPtr ret = NULL, last = NULL, cur, tmp; if (RAW != '(') { xmlFatalErr(ctxt, XML_ERR_NOTATION_NOT_STARTED, NULL); return(NULL); } SHRINK; do { NEXT; SKIP_BLANKS; name = xmlParseName(ctxt); if (name == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED, "Name expected in NOTATION declaration\n"); xmlFreeEnumeration(ret); return(NULL); } tmp = ret; while (tmp != NULL) { if (xmlStrEqual(name, tmp->name)) { xmlValidityError(ctxt, XML_DTD_DUP_TOKEN, "standalone: attribute notation value token %s duplicated\n", name, NULL); if (!xmlDictOwns(ctxt->dict, name)) xmlFree((xmlChar *) name); break; } tmp = tmp->next; } if (tmp == NULL) { cur = xmlCreateEnumeration(name); if (cur == NULL) { xmlFreeEnumeration(ret); return(NULL); } if (last == NULL) ret = last = cur; else { last->next = cur; last = cur; } } SKIP_BLANKS; } while (RAW == '|'); if (RAW != ')') { xmlFatalErr(ctxt, XML_ERR_NOTATION_NOT_FINISHED, NULL); xmlFreeEnumeration(ret); return(NULL); } NEXT; return(ret); } /** * xmlParseEnumerationType: * @ctxt: an XML parser context * * parse an Enumeration attribute type. * * [59] Enumeration ::= '(' S? Nmtoken (S? '|' S? Nmtoken)* S? ')' * * [ VC: Enumeration ] * Values of this type must match one of the Nmtoken tokens in * the declaration * * Returns: the enumeration attribute tree built while parsing */ xmlEnumerationPtr xmlParseEnumerationType(xmlParserCtxtPtr ctxt) { xmlChar *name; xmlEnumerationPtr ret = NULL, last = NULL, cur, tmp; if (RAW != '(') { xmlFatalErr(ctxt, XML_ERR_ATTLIST_NOT_STARTED, NULL); return(NULL); } SHRINK; do { NEXT; SKIP_BLANKS; name = xmlParseNmtoken(ctxt); if (name == NULL) { xmlFatalErr(ctxt, XML_ERR_NMTOKEN_REQUIRED, NULL); return(ret); } tmp = ret; while (tmp != NULL) { if (xmlStrEqual(name, tmp->name)) { xmlValidityError(ctxt, XML_DTD_DUP_TOKEN, "standalone: attribute enumeration value token %s duplicated\n", name, NULL); if (!xmlDictOwns(ctxt->dict, name)) xmlFree(name); break; } tmp = tmp->next; } if (tmp == NULL) { cur = xmlCreateEnumeration(name); if (!xmlDictOwns(ctxt->dict, name)) xmlFree(name); if (cur == NULL) { xmlFreeEnumeration(ret); return(NULL); } if (last == NULL) ret = last = cur; else { last->next = cur; last = cur; } } SKIP_BLANKS; } while (RAW == '|'); if (RAW != ')') { xmlFatalErr(ctxt, XML_ERR_ATTLIST_NOT_FINISHED, NULL); return(ret); } NEXT; return(ret); } /** * xmlParseEnumeratedType: * @ctxt: an XML parser context * @tree: the enumeration tree built while parsing * * parse an Enumerated attribute type. * * [57] EnumeratedType ::= NotationType | Enumeration * * [58] NotationType ::= 'NOTATION' S '(' S? Name (S? '|' S? Name)* S? ')' * * * Returns: XML_ATTRIBUTE_ENUMERATION or XML_ATTRIBUTE_NOTATION */ int xmlParseEnumeratedType(xmlParserCtxtPtr ctxt, xmlEnumerationPtr *tree) { if (CMP8(CUR_PTR, 'N', 'O', 'T', 'A', 'T', 'I', 'O', 'N')) { SKIP(8); if (!IS_BLANK_CH(CUR)) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "Space required after 'NOTATION'\n"); return(0); } SKIP_BLANKS; *tree = xmlParseNotationType(ctxt); if (*tree == NULL) return(0); return(XML_ATTRIBUTE_NOTATION); } *tree = xmlParseEnumerationType(ctxt); if (*tree == NULL) return(0); return(XML_ATTRIBUTE_ENUMERATION); } /** * xmlParseAttributeType: * @ctxt: an XML parser context * @tree: the enumeration tree built while parsing * * parse the Attribute list def for an element * * [54] AttType ::= StringType | TokenizedType | EnumeratedType * * [55] StringType ::= 'CDATA' * * [56] TokenizedType ::= 'ID' | 'IDREF' | 'IDREFS' | 'ENTITY' | * 'ENTITIES' | 'NMTOKEN' | 'NMTOKENS' * * Validity constraints for attribute values syntax are checked in * xmlValidateAttributeValue() * * [ VC: ID ] * Values of type ID must match the Name production. A name must not * appear more than once in an XML document as a value of this type; * i.e., ID values must uniquely identify the elements which bear them. * * [ VC: One ID per Element Type ] * No element type may have more than one ID attribute specified. * * [ VC: ID Attribute Default ] * An ID attribute must have a declared default of #IMPLIED or #REQUIRED. * * [ VC: IDREF ] * Values of type IDREF must match the Name production, and values * of type IDREFS must match Names; each IDREF Name must match the value * of an ID attribute on some element in the XML document; i.e. IDREF * values must match the value of some ID attribute. * * [ VC: Entity Name ] * Values of type ENTITY must match the Name production, values * of type ENTITIES must match Names; each Entity Name must match the * name of an unparsed entity declared in the DTD. * * [ VC: Name Token ] * Values of type NMTOKEN must match the Nmtoken production; values * of type NMTOKENS must match Nmtokens. * * Returns the attribute type */ int xmlParseAttributeType(xmlParserCtxtPtr ctxt, xmlEnumerationPtr *tree) { SHRINK; if (CMP5(CUR_PTR, 'C', 'D', 'A', 'T', 'A')) { SKIP(5); return(XML_ATTRIBUTE_CDATA); } else if (CMP6(CUR_PTR, 'I', 'D', 'R', 'E', 'F', 'S')) { SKIP(6); return(XML_ATTRIBUTE_IDREFS); } else if (CMP5(CUR_PTR, 'I', 'D', 'R', 'E', 'F')) { SKIP(5); return(XML_ATTRIBUTE_IDREF); } else if ((RAW == 'I') && (NXT(1) == 'D')) { SKIP(2); return(XML_ATTRIBUTE_ID); } else if (CMP6(CUR_PTR, 'E', 'N', 'T', 'I', 'T', 'Y')) { SKIP(6); return(XML_ATTRIBUTE_ENTITY); } else if (CMP8(CUR_PTR, 'E', 'N', 'T', 'I', 'T', 'I', 'E', 'S')) { SKIP(8); return(XML_ATTRIBUTE_ENTITIES); } else if (CMP8(CUR_PTR, 'N', 'M', 'T', 'O', 'K', 'E', 'N', 'S')) { SKIP(8); return(XML_ATTRIBUTE_NMTOKENS); } else if (CMP7(CUR_PTR, 'N', 'M', 'T', 'O', 'K', 'E', 'N')) { SKIP(7); return(XML_ATTRIBUTE_NMTOKEN); } return(xmlParseEnumeratedType(ctxt, tree)); } /** * xmlParseAttributeListDecl: * @ctxt: an XML parser context * * : parse the Attribute list def for an element * * [52] AttlistDecl ::= '<!ATTLIST' S Name AttDef* S? '>' * * [53] AttDef ::= S Name S AttType S DefaultDecl * */ void xmlParseAttributeListDecl(xmlParserCtxtPtr ctxt) { const xmlChar *elemName; const xmlChar *attrName; xmlEnumerationPtr tree; if (CMP9(CUR_PTR, '<', '!', 'A', 'T', 'T', 'L', 'I', 'S', 'T')) { xmlParserInputPtr input = ctxt->input; SKIP(9); if (!IS_BLANK_CH(CUR)) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "Space required after '<!ATTLIST'\n"); } SKIP_BLANKS; elemName = xmlParseName(ctxt); if (elemName == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED, "ATTLIST: no name for Element\n"); return; } SKIP_BLANKS; GROW; while ((RAW != '>') && (ctxt->instate != XML_PARSER_EOF)) { const xmlChar *check = CUR_PTR; int type; int def; xmlChar *defaultValue = NULL; GROW; tree = NULL; attrName = xmlParseName(ctxt); if (attrName == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED, "ATTLIST: no name for Attribute\n"); break; } GROW; if (!IS_BLANK_CH(CUR)) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "Space required after the attribute name\n"); break; } SKIP_BLANKS; type = xmlParseAttributeType(ctxt, &tree); if (type <= 0) { break; } GROW; if (!IS_BLANK_CH(CUR)) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "Space required after the attribute type\n"); if (tree != NULL) xmlFreeEnumeration(tree); break; } SKIP_BLANKS; def = xmlParseDefaultDecl(ctxt, &defaultValue); if (def <= 0) { if (defaultValue != NULL) xmlFree(defaultValue); if (tree != NULL) xmlFreeEnumeration(tree); break; } if ((type != XML_ATTRIBUTE_CDATA) && (defaultValue != NULL)) xmlAttrNormalizeSpace(defaultValue, defaultValue); GROW; if (RAW != '>') { if (!IS_BLANK_CH(CUR)) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "Space required after the attribute default value\n"); if (defaultValue != NULL) xmlFree(defaultValue); if (tree != NULL) xmlFreeEnumeration(tree); break; } SKIP_BLANKS; } if (check == CUR_PTR) { xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "in xmlParseAttributeListDecl\n"); if (defaultValue != NULL) xmlFree(defaultValue); if (tree != NULL) xmlFreeEnumeration(tree); break; } if ((ctxt->sax != NULL) && (!ctxt->disableSAX) && (ctxt->sax->attributeDecl != NULL)) ctxt->sax->attributeDecl(ctxt->userData, elemName, attrName, type, def, defaultValue, tree); else if (tree != NULL) xmlFreeEnumeration(tree); if ((ctxt->sax2) && (defaultValue != NULL) && (def != XML_ATTRIBUTE_IMPLIED) && (def != XML_ATTRIBUTE_REQUIRED)) { xmlAddDefAttrs(ctxt, elemName, attrName, defaultValue); } if (ctxt->sax2) { xmlAddSpecialAttr(ctxt, elemName, attrName, type); } if (defaultValue != NULL) xmlFree(defaultValue); GROW; } if (RAW == '>') { if (input != ctxt->input) { xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY, "Attribute list declaration doesn't start and stop in the same entity\n", NULL, NULL); } NEXT; } } } /** * xmlParseElementMixedContentDecl: * @ctxt: an XML parser context * @inputchk: the input used for the current entity, needed for boundary checks * * parse the declaration for a Mixed Element content * The leading '(' and spaces have been skipped in xmlParseElementContentDecl * * [51] Mixed ::= '(' S? '#PCDATA' (S? '|' S? Name)* S? ')*' | * '(' S? '#PCDATA' S? ')' * * [ VC: Proper Group/PE Nesting ] applies to [51] too (see [49]) * * [ VC: No Duplicate Types ] * The same name must not appear more than once in a single * mixed-content declaration. * * returns: the list of the xmlElementContentPtr describing the element choices */ xmlElementContentPtr xmlParseElementMixedContentDecl(xmlParserCtxtPtr ctxt, int inputchk) { xmlElementContentPtr ret = NULL, cur = NULL, n; const xmlChar *elem = NULL; GROW; if (CMP7(CUR_PTR, '#', 'P', 'C', 'D', 'A', 'T', 'A')) { SKIP(7); SKIP_BLANKS; SHRINK; if (RAW == ')') { if ((ctxt->validate) && (ctxt->input->id != inputchk)) { xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY, "Element content declaration doesn't start and stop in the same entity\n", NULL, NULL); } NEXT; ret = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_PCDATA); if (ret == NULL) return(NULL); if (RAW == '*') { ret->ocur = XML_ELEMENT_CONTENT_MULT; NEXT; } return(ret); } if ((RAW == '(') || (RAW == '|')) { ret = cur = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_PCDATA); if (ret == NULL) return(NULL); } while ((RAW == '|') && (ctxt->instate != XML_PARSER_EOF)) { NEXT; if (elem == NULL) { ret = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_OR); if (ret == NULL) return(NULL); ret->c1 = cur; if (cur != NULL) cur->parent = ret; cur = ret; } else { n = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_OR); if (n == NULL) return(NULL); n->c1 = xmlNewDocElementContent(ctxt->myDoc, elem, XML_ELEMENT_CONTENT_ELEMENT); if (n->c1 != NULL) n->c1->parent = n; cur->c2 = n; if (n != NULL) n->parent = cur; cur = n; } SKIP_BLANKS; elem = xmlParseName(ctxt); if (elem == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED, "xmlParseElementMixedContentDecl : Name expected\n"); xmlFreeDocElementContent(ctxt->myDoc, ret); return(NULL); } SKIP_BLANKS; GROW; } if ((RAW == ')') && (NXT(1) == '*')) { if (elem != NULL) { cur->c2 = xmlNewDocElementContent(ctxt->myDoc, elem, XML_ELEMENT_CONTENT_ELEMENT); if (cur->c2 != NULL) cur->c2->parent = cur; } if (ret != NULL) ret->ocur = XML_ELEMENT_CONTENT_MULT; if ((ctxt->validate) && (ctxt->input->id != inputchk)) { xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY, "Element content declaration doesn't start and stop in the same entity\n", NULL, NULL); } SKIP(2); } else { xmlFreeDocElementContent(ctxt->myDoc, ret); xmlFatalErr(ctxt, XML_ERR_MIXED_NOT_STARTED, NULL); return(NULL); } } else { xmlFatalErr(ctxt, XML_ERR_PCDATA_REQUIRED, NULL); } return(ret); } /** * xmlParseElementChildrenContentDeclPriv: * @ctxt: an XML parser context * @inputchk: the input used for the current entity, needed for boundary checks * @depth: the level of recursion * * parse the declaration for a Mixed Element content * The leading '(' and spaces have been skipped in xmlParseElementContentDecl * * * [47] children ::= (choice | seq) ('?' | '*' | '+')? * * [48] cp ::= (Name | choice | seq) ('?' | '*' | '+')? * * [49] choice ::= '(' S? cp ( S? '|' S? cp )* S? ')' * * [50] seq ::= '(' S? cp ( S? ',' S? cp )* S? ')' * * [ VC: Proper Group/PE Nesting ] applies to [49] and [50] * TODO Parameter-entity replacement text must be properly nested * with parenthesized groups. That is to say, if either of the * opening or closing parentheses in a choice, seq, or Mixed * construct is contained in the replacement text for a parameter * entity, both must be contained in the same replacement text. For * interoperability, if a parameter-entity reference appears in a * choice, seq, or Mixed construct, its replacement text should not * be empty, and neither the first nor last non-blank character of * the replacement text should be a connector (| or ,). * * Returns the tree of xmlElementContentPtr describing the element * hierarchy. */ static xmlElementContentPtr xmlParseElementChildrenContentDeclPriv(xmlParserCtxtPtr ctxt, int inputchk, int depth) { xmlElementContentPtr ret = NULL, cur = NULL, last = NULL, op = NULL; const xmlChar *elem; xmlChar type = 0; if (((depth > 128) && ((ctxt->options & XML_PARSE_HUGE) == 0)) || (depth > 2048)) { xmlFatalErrMsgInt(ctxt, XML_ERR_ELEMCONTENT_NOT_FINISHED, "xmlParseElementChildrenContentDecl : depth %d too deep, use XML_PARSE_HUGE\n", depth); return(NULL); } SKIP_BLANKS; GROW; if (RAW == '(') { int inputid = ctxt->input->id; /* Recurse on first child */ NEXT; SKIP_BLANKS; cur = ret = xmlParseElementChildrenContentDeclPriv(ctxt, inputid, depth + 1); SKIP_BLANKS; GROW; } else { elem = xmlParseName(ctxt); if (elem == NULL) { xmlFatalErr(ctxt, XML_ERR_ELEMCONTENT_NOT_STARTED, NULL); return(NULL); } cur = ret = xmlNewDocElementContent(ctxt->myDoc, elem, XML_ELEMENT_CONTENT_ELEMENT); if (cur == NULL) { xmlErrMemory(ctxt, NULL); return(NULL); } GROW; if (RAW == '?') { cur->ocur = XML_ELEMENT_CONTENT_OPT; NEXT; } else if (RAW == '*') { cur->ocur = XML_ELEMENT_CONTENT_MULT; NEXT; } else if (RAW == '+') { cur->ocur = XML_ELEMENT_CONTENT_PLUS; NEXT; } else { cur->ocur = XML_ELEMENT_CONTENT_ONCE; } GROW; } SKIP_BLANKS; SHRINK; while ((RAW != ')') && (ctxt->instate != XML_PARSER_EOF)) { /* * Each loop we parse one separator and one element. */ if (RAW == ',') { if (type == 0) type = CUR; /* * Detect "Name | Name , Name" error */ else if (type != CUR) { xmlFatalErrMsgInt(ctxt, XML_ERR_SEPARATOR_REQUIRED, "xmlParseElementChildrenContentDecl : '%c' expected\n", type); if ((last != NULL) && (last != ret)) xmlFreeDocElementContent(ctxt->myDoc, last); if (ret != NULL) xmlFreeDocElementContent(ctxt->myDoc, ret); return(NULL); } NEXT; op = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_SEQ); if (op == NULL) { if ((last != NULL) && (last != ret)) xmlFreeDocElementContent(ctxt->myDoc, last); xmlFreeDocElementContent(ctxt->myDoc, ret); return(NULL); } if (last == NULL) { op->c1 = ret; if (ret != NULL) ret->parent = op; ret = cur = op; } else { cur->c2 = op; if (op != NULL) op->parent = cur; op->c1 = last; if (last != NULL) last->parent = op; cur =op; last = NULL; } } else if (RAW == '|') { if (type == 0) type = CUR; /* * Detect "Name , Name | Name" error */ else if (type != CUR) { xmlFatalErrMsgInt(ctxt, XML_ERR_SEPARATOR_REQUIRED, "xmlParseElementChildrenContentDecl : '%c' expected\n", type); if ((last != NULL) && (last != ret)) xmlFreeDocElementContent(ctxt->myDoc, last); if (ret != NULL) xmlFreeDocElementContent(ctxt->myDoc, ret); return(NULL); } NEXT; op = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_OR); if (op == NULL) { if ((last != NULL) && (last != ret)) xmlFreeDocElementContent(ctxt->myDoc, last); if (ret != NULL) xmlFreeDocElementContent(ctxt->myDoc, ret); return(NULL); } if (last == NULL) { op->c1 = ret; if (ret != NULL) ret->parent = op; ret = cur = op; } else { cur->c2 = op; if (op != NULL) op->parent = cur; op->c1 = last; if (last != NULL) last->parent = op; cur =op; last = NULL; } } else { xmlFatalErr(ctxt, XML_ERR_ELEMCONTENT_NOT_FINISHED, NULL); if ((last != NULL) && (last != ret)) xmlFreeDocElementContent(ctxt->myDoc, last); if (ret != NULL) xmlFreeDocElementContent(ctxt->myDoc, ret); return(NULL); } GROW; SKIP_BLANKS; GROW; if (RAW == '(') { int inputid = ctxt->input->id; /* Recurse on second child */ NEXT; SKIP_BLANKS; last = xmlParseElementChildrenContentDeclPriv(ctxt, inputid, depth + 1); SKIP_BLANKS; } else { elem = xmlParseName(ctxt); if (elem == NULL) { xmlFatalErr(ctxt, XML_ERR_ELEMCONTENT_NOT_STARTED, NULL); if (ret != NULL) xmlFreeDocElementContent(ctxt->myDoc, ret); return(NULL); } last = xmlNewDocElementContent(ctxt->myDoc, elem, XML_ELEMENT_CONTENT_ELEMENT); if (last == NULL) { if (ret != NULL) xmlFreeDocElementContent(ctxt->myDoc, ret); return(NULL); } if (RAW == '?') { last->ocur = XML_ELEMENT_CONTENT_OPT; NEXT; } else if (RAW == '*') { last->ocur = XML_ELEMENT_CONTENT_MULT; NEXT; } else if (RAW == '+') { last->ocur = XML_ELEMENT_CONTENT_PLUS; NEXT; } else { last->ocur = XML_ELEMENT_CONTENT_ONCE; } } SKIP_BLANKS; GROW; } if ((cur != NULL) && (last != NULL)) { cur->c2 = last; if (last != NULL) last->parent = cur; } if ((ctxt->validate) && (ctxt->input->id != inputchk)) { xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY, "Element content declaration doesn't start and stop in the same entity\n", NULL, NULL); } NEXT; if (RAW == '?') { if (ret != NULL) { if ((ret->ocur == XML_ELEMENT_CONTENT_PLUS) || (ret->ocur == XML_ELEMENT_CONTENT_MULT)) ret->ocur = XML_ELEMENT_CONTENT_MULT; else ret->ocur = XML_ELEMENT_CONTENT_OPT; } NEXT; } else if (RAW == '*') { if (ret != NULL) { ret->ocur = XML_ELEMENT_CONTENT_MULT; cur = ret; /* * Some normalization: * (a | b* | c?)* == (a | b | c)* */ while ((cur != NULL) && (cur->type == XML_ELEMENT_CONTENT_OR)) { if ((cur->c1 != NULL) && ((cur->c1->ocur == XML_ELEMENT_CONTENT_OPT) || (cur->c1->ocur == XML_ELEMENT_CONTENT_MULT))) cur->c1->ocur = XML_ELEMENT_CONTENT_ONCE; if ((cur->c2 != NULL) && ((cur->c2->ocur == XML_ELEMENT_CONTENT_OPT) || (cur->c2->ocur == XML_ELEMENT_CONTENT_MULT))) cur->c2->ocur = XML_ELEMENT_CONTENT_ONCE; cur = cur->c2; } } NEXT; } else if (RAW == '+') { if (ret != NULL) { int found = 0; if ((ret->ocur == XML_ELEMENT_CONTENT_OPT) || (ret->ocur == XML_ELEMENT_CONTENT_MULT)) ret->ocur = XML_ELEMENT_CONTENT_MULT; else ret->ocur = XML_ELEMENT_CONTENT_PLUS; /* * Some normalization: * (a | b*)+ == (a | b)* * (a | b?)+ == (a | b)* */ while ((cur != NULL) && (cur->type == XML_ELEMENT_CONTENT_OR)) { if ((cur->c1 != NULL) && ((cur->c1->ocur == XML_ELEMENT_CONTENT_OPT) || (cur->c1->ocur == XML_ELEMENT_CONTENT_MULT))) { cur->c1->ocur = XML_ELEMENT_CONTENT_ONCE; found = 1; } if ((cur->c2 != NULL) && ((cur->c2->ocur == XML_ELEMENT_CONTENT_OPT) || (cur->c2->ocur == XML_ELEMENT_CONTENT_MULT))) { cur->c2->ocur = XML_ELEMENT_CONTENT_ONCE; found = 1; } cur = cur->c2; } if (found) ret->ocur = XML_ELEMENT_CONTENT_MULT; } NEXT; } return(ret); } /** * xmlParseElementChildrenContentDecl: * @ctxt: an XML parser context * @inputchk: the input used for the current entity, needed for boundary checks * * parse the declaration for a Mixed Element content * The leading '(' and spaces have been skipped in xmlParseElementContentDecl * * [47] children ::= (choice | seq) ('?' | '*' | '+')? * * [48] cp ::= (Name | choice | seq) ('?' | '*' | '+')? * * [49] choice ::= '(' S? cp ( S? '|' S? cp )* S? ')' * * [50] seq ::= '(' S? cp ( S? ',' S? cp )* S? ')' * * [ VC: Proper Group/PE Nesting ] applies to [49] and [50] * TODO Parameter-entity replacement text must be properly nested * with parenthesized groups. That is to say, if either of the * opening or closing parentheses in a choice, seq, or Mixed * construct is contained in the replacement text for a parameter * entity, both must be contained in the same replacement text. For * interoperability, if a parameter-entity reference appears in a * choice, seq, or Mixed construct, its replacement text should not * be empty, and neither the first nor last non-blank character of * the replacement text should be a connector (| or ,). * * Returns the tree of xmlElementContentPtr describing the element * hierarchy. */ xmlElementContentPtr xmlParseElementChildrenContentDecl(xmlParserCtxtPtr ctxt, int inputchk) { /* stub left for API/ABI compat */ return(xmlParseElementChildrenContentDeclPriv(ctxt, inputchk, 1)); } /** * xmlParseElementContentDecl: * @ctxt: an XML parser context * @name: the name of the element being defined. * @result: the Element Content pointer will be stored here if any * * parse the declaration for an Element content either Mixed or Children, * the cases EMPTY and ANY are handled directly in xmlParseElementDecl * * [46] contentspec ::= 'EMPTY' | 'ANY' | Mixed | children * * returns: the type of element content XML_ELEMENT_TYPE_xxx */ int xmlParseElementContentDecl(xmlParserCtxtPtr ctxt, const xmlChar *name, xmlElementContentPtr *result) { xmlElementContentPtr tree = NULL; int inputid = ctxt->input->id; int res; *result = NULL; if (RAW != '(') { xmlFatalErrMsgStr(ctxt, XML_ERR_ELEMCONTENT_NOT_STARTED, "xmlParseElementContentDecl : %s '(' expected\n", name); return(-1); } NEXT; GROW; if (ctxt->instate == XML_PARSER_EOF) return(-1); SKIP_BLANKS; if (CMP7(CUR_PTR, '#', 'P', 'C', 'D', 'A', 'T', 'A')) { tree = xmlParseElementMixedContentDecl(ctxt, inputid); res = XML_ELEMENT_TYPE_MIXED; } else { tree = xmlParseElementChildrenContentDeclPriv(ctxt, inputid, 1); res = XML_ELEMENT_TYPE_ELEMENT; } SKIP_BLANKS; *result = tree; return(res); } /** * xmlParseElementDecl: * @ctxt: an XML parser context * * parse an Element declaration. * * [45] elementdecl ::= '<!ELEMENT' S Name S contentspec S? '>' * * [ VC: Unique Element Type Declaration ] * No element type may be declared more than once * * Returns the type of the element, or -1 in case of error */ int xmlParseElementDecl(xmlParserCtxtPtr ctxt) { const xmlChar *name; int ret = -1; xmlElementContentPtr content = NULL; /* GROW; done in the caller */ if (CMP9(CUR_PTR, '<', '!', 'E', 'L', 'E', 'M', 'E', 'N', 'T')) { xmlParserInputPtr input = ctxt->input; SKIP(9); if (!IS_BLANK_CH(CUR)) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "Space required after 'ELEMENT'\n"); return(-1); } SKIP_BLANKS; name = xmlParseName(ctxt); if (name == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED, "xmlParseElementDecl: no name for Element\n"); return(-1); } while ((RAW == 0) && (ctxt->inputNr > 1)) xmlPopInput(ctxt); if (!IS_BLANK_CH(CUR)) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "Space required after the element name\n"); } SKIP_BLANKS; if (CMP5(CUR_PTR, 'E', 'M', 'P', 'T', 'Y')) { SKIP(5); /* * Element must always be empty. */ ret = XML_ELEMENT_TYPE_EMPTY; } else if ((RAW == 'A') && (NXT(1) == 'N') && (NXT(2) == 'Y')) { SKIP(3); /* * Element is a generic container. */ ret = XML_ELEMENT_TYPE_ANY; } else if (RAW == '(') { ret = xmlParseElementContentDecl(ctxt, name, &content); } else { /* * [ WFC: PEs in Internal Subset ] error handling. */ if ((RAW == '%') && (ctxt->external == 0) && (ctxt->inputNr == 1)) { xmlFatalErrMsg(ctxt, XML_ERR_PEREF_IN_INT_SUBSET, "PEReference: forbidden within markup decl in internal subset\n"); } else { xmlFatalErrMsg(ctxt, XML_ERR_ELEMCONTENT_NOT_STARTED, "xmlParseElementDecl: 'EMPTY', 'ANY' or '(' expected\n"); } return(-1); } SKIP_BLANKS; /* * Pop-up of finished entities. */ while ((RAW == 0) && (ctxt->inputNr > 1)) xmlPopInput(ctxt); SKIP_BLANKS; if (RAW != '>') { xmlFatalErr(ctxt, XML_ERR_GT_REQUIRED, NULL); if (content != NULL) { xmlFreeDocElementContent(ctxt->myDoc, content); } } else { if (input != ctxt->input) { xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY, "Element declaration doesn't start and stop in the same entity\n"); } NEXT; if ((ctxt->sax != NULL) && (!ctxt->disableSAX) && (ctxt->sax->elementDecl != NULL)) { if (content != NULL) content->parent = NULL; ctxt->sax->elementDecl(ctxt->userData, name, ret, content); if ((content != NULL) && (content->parent == NULL)) { /* * this is a trick: if xmlAddElementDecl is called, * instead of copying the full tree it is plugged directly * if called from the parser. Avoid duplicating the * interfaces or change the API/ABI */ xmlFreeDocElementContent(ctxt->myDoc, content); } } else if (content != NULL) { xmlFreeDocElementContent(ctxt->myDoc, content); } } } return(ret); } /** * xmlParseConditionalSections * @ctxt: an XML parser context * * [61] conditionalSect ::= includeSect | ignoreSect * [62] includeSect ::= '<![' S? 'INCLUDE' S? '[' extSubsetDecl ']]>' * [63] ignoreSect ::= '<![' S? 'IGNORE' S? '[' ignoreSectContents* ']]>' * [64] ignoreSectContents ::= Ignore ('<![' ignoreSectContents ']]>' Ignore)* * [65] Ignore ::= Char* - (Char* ('<![' | ']]>') Char*) */ static void xmlParseConditionalSections(xmlParserCtxtPtr ctxt) { int id = ctxt->input->id; SKIP(3); SKIP_BLANKS; if (CMP7(CUR_PTR, 'I', 'N', 'C', 'L', 'U', 'D', 'E')) { SKIP(7); SKIP_BLANKS; if (RAW != '[') { xmlFatalErr(ctxt, XML_ERR_CONDSEC_INVALID, NULL); xmlHaltParser(ctxt); return; } else { if (ctxt->input->id != id) { xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY, "All markup of the conditional section is not in the same entity\n", NULL, NULL); } NEXT; } if (xmlParserDebugEntities) { if ((ctxt->input != NULL) && (ctxt->input->filename)) xmlGenericError(xmlGenericErrorContext, "%s(%d): ", ctxt->input->filename, ctxt->input->line); xmlGenericError(xmlGenericErrorContext, "Entering INCLUDE Conditional Section\n"); } while (((RAW != 0) && ((RAW != ']') || (NXT(1) != ']') || (NXT(2) != '>'))) && (ctxt->instate != XML_PARSER_EOF)) { const xmlChar *check = CUR_PTR; unsigned int cons = ctxt->input->consumed; if ((RAW == '<') && (NXT(1) == '!') && (NXT(2) == '[')) { xmlParseConditionalSections(ctxt); } else if (IS_BLANK_CH(CUR)) { NEXT; } else if (RAW == '%') { xmlParsePEReference(ctxt); } else xmlParseMarkupDecl(ctxt); /* * Pop-up of finished entities. */ while ((RAW == 0) && (ctxt->inputNr > 1)) xmlPopInput(ctxt); if ((CUR_PTR == check) && (cons == ctxt->input->consumed)) { xmlFatalErr(ctxt, XML_ERR_EXT_SUBSET_NOT_FINISHED, NULL); xmlHaltParser(ctxt); break; } } if (xmlParserDebugEntities) { if ((ctxt->input != NULL) && (ctxt->input->filename)) xmlGenericError(xmlGenericErrorContext, "%s(%d): ", ctxt->input->filename, ctxt->input->line); xmlGenericError(xmlGenericErrorContext, "Leaving INCLUDE Conditional Section\n"); } } else if (CMP6(CUR_PTR, 'I', 'G', 'N', 'O', 'R', 'E')) { int state; xmlParserInputState instate; int depth = 0; SKIP(6); SKIP_BLANKS; if (RAW != '[') { xmlFatalErr(ctxt, XML_ERR_CONDSEC_INVALID, NULL); xmlHaltParser(ctxt); return; } else { if (ctxt->input->id != id) { xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY, "All markup of the conditional section is not in the same entity\n", NULL, NULL); } NEXT; } if (xmlParserDebugEntities) { if ((ctxt->input != NULL) && (ctxt->input->filename)) xmlGenericError(xmlGenericErrorContext, "%s(%d): ", ctxt->input->filename, ctxt->input->line); xmlGenericError(xmlGenericErrorContext, "Entering IGNORE Conditional Section\n"); } /* * Parse up to the end of the conditional section * But disable SAX event generating DTD building in the meantime */ state = ctxt->disableSAX; instate = ctxt->instate; if (ctxt->recovery == 0) ctxt->disableSAX = 1; ctxt->instate = XML_PARSER_IGNORE; while (((depth >= 0) && (RAW != 0)) && (ctxt->instate != XML_PARSER_EOF)) { if ((RAW == '<') && (NXT(1) == '!') && (NXT(2) == '[')) { depth++; SKIP(3); continue; } if ((RAW == ']') && (NXT(1) == ']') && (NXT(2) == '>')) { if (--depth >= 0) SKIP(3); continue; } NEXT; continue; } ctxt->disableSAX = state; ctxt->instate = instate; if (xmlParserDebugEntities) { if ((ctxt->input != NULL) && (ctxt->input->filename)) xmlGenericError(xmlGenericErrorContext, "%s(%d): ", ctxt->input->filename, ctxt->input->line); xmlGenericError(xmlGenericErrorContext, "Leaving IGNORE Conditional Section\n"); } } else { xmlFatalErr(ctxt, XML_ERR_CONDSEC_INVALID_KEYWORD, NULL); xmlHaltParser(ctxt); return; } if (RAW == 0) SHRINK; if (RAW == 0) { xmlFatalErr(ctxt, XML_ERR_CONDSEC_NOT_FINISHED, NULL); } else { if (ctxt->input->id != id) { xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY, "All markup of the conditional section is not in the same entity\n", NULL, NULL); } if ((ctxt-> instate != XML_PARSER_EOF) && ((ctxt->input->cur + 3) <= ctxt->input->end)) SKIP(3); } } /** * xmlParseMarkupDecl: * @ctxt: an XML parser context * * parse Markup declarations * * [29] markupdecl ::= elementdecl | AttlistDecl | EntityDecl | * NotationDecl | PI | Comment * * [ VC: Proper Declaration/PE Nesting ] * Parameter-entity replacement text must be properly nested with * markup declarations. That is to say, if either the first character * or the last character of a markup declaration (markupdecl above) is * contained in the replacement text for a parameter-entity reference, * both must be contained in the same replacement text. * * [ WFC: PEs in Internal Subset ] * In the internal DTD subset, parameter-entity references can occur * only where markup declarations can occur, not within markup declarations. * (This does not apply to references that occur in external parameter * entities or to the external subset.) */ void xmlParseMarkupDecl(xmlParserCtxtPtr ctxt) { GROW; if (CUR == '<') { if (NXT(1) == '!') { switch (NXT(2)) { case 'E': if (NXT(3) == 'L') xmlParseElementDecl(ctxt); else if (NXT(3) == 'N') xmlParseEntityDecl(ctxt); break; case 'A': xmlParseAttributeListDecl(ctxt); break; case 'N': xmlParseNotationDecl(ctxt); break; case '-': xmlParseComment(ctxt); break; default: /* there is an error but it will be detected later */ break; } } else if (NXT(1) == '?') { xmlParsePI(ctxt); } } /* * detect requirement to exit there and act accordingly * and avoid having instate overriden later on */ if (ctxt->instate == XML_PARSER_EOF) return; /* * This is only for internal subset. On external entities, * the replacement is done before parsing stage */ if ((ctxt->external == 0) && (ctxt->inputNr == 1)) xmlParsePEReference(ctxt); /* * Conditional sections are allowed from entities included * by PE References in the internal subset. */ if ((ctxt->external == 0) && (ctxt->inputNr > 1)) { if ((RAW == '<') && (NXT(1) == '!') && (NXT(2) == '[')) { xmlParseConditionalSections(ctxt); } } ctxt->instate = XML_PARSER_DTD; } /** * xmlParseTextDecl: * @ctxt: an XML parser context * * parse an XML declaration header for external entities * * [77] TextDecl ::= '<?xml' VersionInfo? EncodingDecl S? '?>' */ void xmlParseTextDecl(xmlParserCtxtPtr ctxt) { xmlChar *version; const xmlChar *encoding; /* * We know that '<?xml' is here. */ if ((CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) && (IS_BLANK_CH(NXT(5)))) { SKIP(5); } else { xmlFatalErr(ctxt, XML_ERR_XMLDECL_NOT_STARTED, NULL); return; } if (!IS_BLANK_CH(CUR)) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "Space needed after '<?xml'\n"); } SKIP_BLANKS; /* * We may have the VersionInfo here. */ version = xmlParseVersionInfo(ctxt); if (version == NULL) version = xmlCharStrdup(XML_DEFAULT_VERSION); else { if (!IS_BLANK_CH(CUR)) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "Space needed here\n"); } } ctxt->input->version = version; /* * We must have the encoding declaration */ encoding = xmlParseEncodingDecl(ctxt); if (ctxt->errNo == XML_ERR_UNSUPPORTED_ENCODING) { /* * The XML REC instructs us to stop parsing right here */ return; } if ((encoding == NULL) && (ctxt->errNo == XML_ERR_OK)) { xmlFatalErrMsg(ctxt, XML_ERR_MISSING_ENCODING, "Missing encoding in text declaration\n"); } SKIP_BLANKS; if ((RAW == '?') && (NXT(1) == '>')) { SKIP(2); } else if (RAW == '>') { /* Deprecated old WD ... */ xmlFatalErr(ctxt, XML_ERR_XMLDECL_NOT_FINISHED, NULL); NEXT; } else { xmlFatalErr(ctxt, XML_ERR_XMLDECL_NOT_FINISHED, NULL); MOVETO_ENDTAG(CUR_PTR); NEXT; } } /** * xmlParseExternalSubset: * @ctxt: an XML parser context * @ExternalID: the external identifier * @SystemID: the system identifier (or URL) * * parse Markup declarations from an external subset * * [30] extSubset ::= textDecl? extSubsetDecl * * [31] extSubsetDecl ::= (markupdecl | conditionalSect | PEReference | S) * */ void xmlParseExternalSubset(xmlParserCtxtPtr ctxt, const xmlChar *ExternalID, const xmlChar *SystemID) { xmlDetectSAX2(ctxt); GROW; if ((ctxt->encoding == NULL) && (ctxt->input->end - ctxt->input->cur >= 4)) { xmlChar start[4]; xmlCharEncoding enc; start[0] = RAW; start[1] = NXT(1); start[2] = NXT(2); start[3] = NXT(3); enc = xmlDetectCharEncoding(start, 4); if (enc != XML_CHAR_ENCODING_NONE) xmlSwitchEncoding(ctxt, enc); } if (CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) { xmlParseTextDecl(ctxt); if (ctxt->errNo == XML_ERR_UNSUPPORTED_ENCODING) { /* * The XML REC instructs us to stop parsing right here */ xmlHaltParser(ctxt); return; } } if (ctxt->myDoc == NULL) { ctxt->myDoc = xmlNewDoc(BAD_CAST "1.0"); if (ctxt->myDoc == NULL) { xmlErrMemory(ctxt, "New Doc failed"); return; } ctxt->myDoc->properties = XML_DOC_INTERNAL; } if ((ctxt->myDoc != NULL) && (ctxt->myDoc->intSubset == NULL)) xmlCreateIntSubset(ctxt->myDoc, NULL, ExternalID, SystemID); ctxt->instate = XML_PARSER_DTD; ctxt->external = 1; while (((RAW == '<') && (NXT(1) == '?')) || ((RAW == '<') && (NXT(1) == '!')) || (RAW == '%') || IS_BLANK_CH(CUR)) { const xmlChar *check = CUR_PTR; unsigned int cons = ctxt->input->consumed; GROW; if ((RAW == '<') && (NXT(1) == '!') && (NXT(2) == '[')) { xmlParseConditionalSections(ctxt); } else if (IS_BLANK_CH(CUR)) { NEXT; } else if (RAW == '%') { xmlParsePEReference(ctxt); } else xmlParseMarkupDecl(ctxt); /* * Pop-up of finished entities. */ while ((RAW == 0) && (ctxt->inputNr > 1)) xmlPopInput(ctxt); if ((CUR_PTR == check) && (cons == ctxt->input->consumed)) { xmlFatalErr(ctxt, XML_ERR_EXT_SUBSET_NOT_FINISHED, NULL); break; } } if (RAW != 0) { xmlFatalErr(ctxt, XML_ERR_EXT_SUBSET_NOT_FINISHED, NULL); } } /** * xmlParseReference: * @ctxt: an XML parser context * * parse and handle entity references in content, depending on the SAX * interface, this may end-up in a call to character() if this is a * CharRef, a predefined entity, if there is no reference() callback. * or if the parser was asked to switch to that mode. * * [67] Reference ::= EntityRef | CharRef */ void xmlParseReference(xmlParserCtxtPtr ctxt) { xmlEntityPtr ent; xmlChar *val; int was_checked; xmlNodePtr list = NULL; xmlParserErrors ret = XML_ERR_OK; if (RAW != '&') return; /* * Simple case of a CharRef */ if (NXT(1) == '#') { int i = 0; xmlChar out[10]; int hex = NXT(2); int value = xmlParseCharRef(ctxt); if (value == 0) return; if (ctxt->charset != XML_CHAR_ENCODING_UTF8) { /* * So we are using non-UTF-8 buffers * Check that the char fit on 8bits, if not * generate a CharRef. */ if (value <= 0xFF) { out[0] = value; out[1] = 0; if ((ctxt->sax != NULL) && (ctxt->sax->characters != NULL) && (!ctxt->disableSAX)) ctxt->sax->characters(ctxt->userData, out, 1); } else { if ((hex == 'x') || (hex == 'X')) snprintf((char *)out, sizeof(out), "#x%X", value); else snprintf((char *)out, sizeof(out), "#%d", value); if ((ctxt->sax != NULL) && (ctxt->sax->reference != NULL) && (!ctxt->disableSAX)) ctxt->sax->reference(ctxt->userData, out); } } else { /* * Just encode the value in UTF-8 */ COPY_BUF(0 ,out, i, value); out[i] = 0; if ((ctxt->sax != NULL) && (ctxt->sax->characters != NULL) && (!ctxt->disableSAX)) ctxt->sax->characters(ctxt->userData, out, i); } return; } /* * We are seeing an entity reference */ ent = xmlParseEntityRef(ctxt); if (ent == NULL) return; if (!ctxt->wellFormed) return; was_checked = ent->checked; /* special case of predefined entities */ if ((ent->name == NULL) || (ent->etype == XML_INTERNAL_PREDEFINED_ENTITY)) { val = ent->content; if (val == NULL) return; /* * inline the entity. */ if ((ctxt->sax != NULL) && (ctxt->sax->characters != NULL) && (!ctxt->disableSAX)) ctxt->sax->characters(ctxt->userData, val, xmlStrlen(val)); return; } /* * The first reference to the entity trigger a parsing phase * where the ent->children is filled with the result from * the parsing. * Note: external parsed entities will not be loaded, it is not * required for a non-validating parser, unless the parsing option * of validating, or substituting entities were given. Doing so is * far more secure as the parser will only process data coming from * the document entity by default. */ if (((ent->checked == 0) || ((ent->children == NULL) && (ctxt->options & XML_PARSE_NOENT))) && ((ent->etype != XML_EXTERNAL_GENERAL_PARSED_ENTITY) || (ctxt->options & (XML_PARSE_NOENT | XML_PARSE_DTDVALID)))) { unsigned long oldnbent = ctxt->nbentities; /* * This is a bit hackish but this seems the best * way to make sure both SAX and DOM entity support * behaves okay. */ void *user_data; if (ctxt->userData == ctxt) user_data = NULL; else user_data = ctxt->userData; /* * Check that this entity is well formed * 4.3.2: An internal general parsed entity is well-formed * if its replacement text matches the production labeled * content. */ if (ent->etype == XML_INTERNAL_GENERAL_ENTITY) { ctxt->depth++; ret = xmlParseBalancedChunkMemoryInternal(ctxt, ent->content, user_data, &list); ctxt->depth--; } else if (ent->etype == XML_EXTERNAL_GENERAL_PARSED_ENTITY) { ctxt->depth++; ret = xmlParseExternalEntityPrivate(ctxt->myDoc, ctxt, ctxt->sax, user_data, ctxt->depth, ent->URI, ent->ExternalID, &list); ctxt->depth--; } else { ret = XML_ERR_ENTITY_PE_INTERNAL; xmlErrMsgStr(ctxt, XML_ERR_INTERNAL_ERROR, "invalid entity type found\n", NULL); } /* * Store the number of entities needing parsing for this entity * content and do checkings */ ent->checked = (ctxt->nbentities - oldnbent + 1) * 2; if ((ent->content != NULL) && (xmlStrchr(ent->content, '<'))) ent->checked |= 1; if (ret == XML_ERR_ENTITY_LOOP) { xmlFatalErr(ctxt, XML_ERR_ENTITY_LOOP, NULL); xmlFreeNodeList(list); return; } if (xmlParserEntityCheck(ctxt, 0, ent, 0)) { xmlFreeNodeList(list); return; } if ((ret == XML_ERR_OK) && (list != NULL)) { if (((ent->etype == XML_INTERNAL_GENERAL_ENTITY) || (ent->etype == XML_EXTERNAL_GENERAL_PARSED_ENTITY))&& (ent->children == NULL)) { ent->children = list; if (ctxt->replaceEntities) { /* * Prune it directly in the generated document * except for single text nodes. */ if (((list->type == XML_TEXT_NODE) && (list->next == NULL)) || (ctxt->parseMode == XML_PARSE_READER)) { list->parent = (xmlNodePtr) ent; list = NULL; ent->owner = 1; } else { ent->owner = 0; while (list != NULL) { list->parent = (xmlNodePtr) ctxt->node; list->doc = ctxt->myDoc; if (list->next == NULL) ent->last = list; list = list->next; } list = ent->children; #ifdef LIBXML_LEGACY_ENABLED if (ent->etype == XML_EXTERNAL_GENERAL_PARSED_ENTITY) xmlAddEntityReference(ent, list, NULL); #endif /* LIBXML_LEGACY_ENABLED */ } } else { ent->owner = 1; while (list != NULL) { list->parent = (xmlNodePtr) ent; xmlSetTreeDoc(list, ent->doc); if (list->next == NULL) ent->last = list; list = list->next; } } } else { xmlFreeNodeList(list); list = NULL; } } else if ((ret != XML_ERR_OK) && (ret != XML_WAR_UNDECLARED_ENTITY)) { xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY, "Entity '%s' failed to parse\n", ent->name); xmlParserEntityCheck(ctxt, 0, ent, 0); } else if (list != NULL) { xmlFreeNodeList(list); list = NULL; } if (ent->checked == 0) ent->checked = 2; } else if (ent->checked != 1) { ctxt->nbentities += ent->checked / 2; } /* * Now that the entity content has been gathered * provide it to the application, this can take different forms based * on the parsing modes. */ if (ent->children == NULL) { /* * Probably running in SAX mode and the callbacks don't * build the entity content. So unless we already went * though parsing for first checking go though the entity * content to generate callbacks associated to the entity */ if (was_checked != 0) { void *user_data; /* * This is a bit hackish but this seems the best * way to make sure both SAX and DOM entity support * behaves okay. */ if (ctxt->userData == ctxt) user_data = NULL; else user_data = ctxt->userData; if (ent->etype == XML_INTERNAL_GENERAL_ENTITY) { ctxt->depth++; ret = xmlParseBalancedChunkMemoryInternal(ctxt, ent->content, user_data, NULL); ctxt->depth--; } else if (ent->etype == XML_EXTERNAL_GENERAL_PARSED_ENTITY) { ctxt->depth++; ret = xmlParseExternalEntityPrivate(ctxt->myDoc, ctxt, ctxt->sax, user_data, ctxt->depth, ent->URI, ent->ExternalID, NULL); ctxt->depth--; } else { ret = XML_ERR_ENTITY_PE_INTERNAL; xmlErrMsgStr(ctxt, XML_ERR_INTERNAL_ERROR, "invalid entity type found\n", NULL); } if (ret == XML_ERR_ENTITY_LOOP) { xmlFatalErr(ctxt, XML_ERR_ENTITY_LOOP, NULL); return; } } if ((ctxt->sax != NULL) && (ctxt->sax->reference != NULL) && (ctxt->replaceEntities == 0) && (!ctxt->disableSAX)) { /* * Entity reference callback comes second, it's somewhat * superfluous but a compatibility to historical behaviour */ ctxt->sax->reference(ctxt->userData, ent->name); } return; } /* * If we didn't get any children for the entity being built */ if ((ctxt->sax != NULL) && (ctxt->sax->reference != NULL) && (ctxt->replaceEntities == 0) && (!ctxt->disableSAX)) { /* * Create a node. */ ctxt->sax->reference(ctxt->userData, ent->name); return; } if ((ctxt->replaceEntities) || (ent->children == NULL)) { /* * There is a problem on the handling of _private for entities * (bug 155816): Should we copy the content of the field from * the entity (possibly overwriting some value set by the user * when a copy is created), should we leave it alone, or should * we try to take care of different situations? The problem * is exacerbated by the usage of this field by the xmlReader. * To fix this bug, we look at _private on the created node * and, if it's NULL, we copy in whatever was in the entity. * If it's not NULL we leave it alone. This is somewhat of a * hack - maybe we should have further tests to determine * what to do. */ if ((ctxt->node != NULL) && (ent->children != NULL)) { /* * Seems we are generating the DOM content, do * a simple tree copy for all references except the first * In the first occurrence list contains the replacement. */ if (((list == NULL) && (ent->owner == 0)) || (ctxt->parseMode == XML_PARSE_READER)) { xmlNodePtr nw = NULL, cur, firstChild = NULL; /* * We are copying here, make sure there is no abuse */ ctxt->sizeentcopy += ent->length + 5; if (xmlParserEntityCheck(ctxt, 0, ent, ctxt->sizeentcopy)) return; /* * when operating on a reader, the entities definitions * are always owning the entities subtree. if (ctxt->parseMode == XML_PARSE_READER) ent->owner = 1; */ cur = ent->children; while (cur != NULL) { nw = xmlDocCopyNode(cur, ctxt->myDoc, 1); if (nw != NULL) { if (nw->_private == NULL) nw->_private = cur->_private; if (firstChild == NULL){ firstChild = nw; } nw = xmlAddChild(ctxt->node, nw); } if (cur == ent->last) { /* * needed to detect some strange empty * node cases in the reader tests */ if ((ctxt->parseMode == XML_PARSE_READER) && (nw != NULL) && (nw->type == XML_ELEMENT_NODE) && (nw->children == NULL)) nw->extra = 1; break; } cur = cur->next; } #ifdef LIBXML_LEGACY_ENABLED if (ent->etype == XML_EXTERNAL_GENERAL_PARSED_ENTITY) xmlAddEntityReference(ent, firstChild, nw); #endif /* LIBXML_LEGACY_ENABLED */ } else if ((list == NULL) || (ctxt->inputNr > 0)) { xmlNodePtr nw = NULL, cur, next, last, firstChild = NULL; /* * We are copying here, make sure there is no abuse */ ctxt->sizeentcopy += ent->length + 5; if (xmlParserEntityCheck(ctxt, 0, ent, ctxt->sizeentcopy)) return; /* * Copy the entity child list and make it the new * entity child list. The goal is to make sure any * ID or REF referenced will be the one from the * document content and not the entity copy. */ cur = ent->children; ent->children = NULL; last = ent->last; ent->last = NULL; while (cur != NULL) { next = cur->next; cur->next = NULL; cur->parent = NULL; nw = xmlDocCopyNode(cur, ctxt->myDoc, 1); if (nw != NULL) { if (nw->_private == NULL) nw->_private = cur->_private; if (firstChild == NULL){ firstChild = cur; } xmlAddChild((xmlNodePtr) ent, nw); xmlAddChild(ctxt->node, cur); } if (cur == last) break; cur = next; } if (ent->owner == 0) ent->owner = 1; #ifdef LIBXML_LEGACY_ENABLED if (ent->etype == XML_EXTERNAL_GENERAL_PARSED_ENTITY) xmlAddEntityReference(ent, firstChild, nw); #endif /* LIBXML_LEGACY_ENABLED */ } else { const xmlChar *nbktext; /* * the name change is to avoid coalescing of the * node with a possible previous text one which * would make ent->children a dangling pointer */ nbktext = xmlDictLookup(ctxt->dict, BAD_CAST "nbktext", -1); if (ent->children->type == XML_TEXT_NODE) ent->children->name = nbktext; if ((ent->last != ent->children) && (ent->last->type == XML_TEXT_NODE)) ent->last->name = nbktext; xmlAddChildList(ctxt->node, ent->children); } /* * This is to avoid a nasty side effect, see * characters() in SAX.c */ ctxt->nodemem = 0; ctxt->nodelen = 0; return; } } } /** * xmlParseEntityRef: * @ctxt: an XML parser context * * parse ENTITY references declarations * * [68] EntityRef ::= '&' Name ';' * * [ WFC: Entity Declared ] * In a document without any DTD, a document with only an internal DTD * subset which contains no parameter entity references, or a document * with "standalone='yes'", the Name given in the entity reference * must match that in an entity declaration, except that well-formed * documents need not declare any of the following entities: amp, lt, * gt, apos, quot. The declaration of a parameter entity must precede * any reference to it. Similarly, the declaration of a general entity * must precede any reference to it which appears in a default value in an * attribute-list declaration. Note that if entities are declared in the * external subset or in external parameter entities, a non-validating * processor is not obligated to read and process their declarations; * for such documents, the rule that an entity must be declared is a * well-formedness constraint only if standalone='yes'. * * [ WFC: Parsed Entity ] * An entity reference must not contain the name of an unparsed entity * * Returns the xmlEntityPtr if found, or NULL otherwise. */ xmlEntityPtr xmlParseEntityRef(xmlParserCtxtPtr ctxt) { const xmlChar *name; xmlEntityPtr ent = NULL; GROW; if (ctxt->instate == XML_PARSER_EOF) return(NULL); if (RAW != '&') return(NULL); NEXT; name = xmlParseName(ctxt); if (name == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED, "xmlParseEntityRef: no name\n"); return(NULL); } if (RAW != ';') { xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL); return(NULL); } NEXT; /* * Predefined entities override any extra definition */ if ((ctxt->options & XML_PARSE_OLDSAX) == 0) { ent = xmlGetPredefinedEntity(name); if (ent != NULL) return(ent); } /* * Increase the number of entity references parsed */ ctxt->nbentities++; /* * Ask first SAX for entity resolution, otherwise try the * entities which may have stored in the parser context. */ if (ctxt->sax != NULL) { if (ctxt->sax->getEntity != NULL) ent = ctxt->sax->getEntity(ctxt->userData, name); if ((ctxt->wellFormed == 1 ) && (ent == NULL) && (ctxt->options & XML_PARSE_OLDSAX)) ent = xmlGetPredefinedEntity(name); if ((ctxt->wellFormed == 1 ) && (ent == NULL) && (ctxt->userData==ctxt)) { ent = xmlSAX2GetEntity(ctxt, name); } } if (ctxt->instate == XML_PARSER_EOF) return(NULL); /* * [ WFC: Entity Declared ] * In a document without any DTD, a document with only an * internal DTD subset which contains no parameter entity * references, or a document with "standalone='yes'", the * Name given in the entity reference must match that in an * entity declaration, except that well-formed documents * need not declare any of the following entities: amp, lt, * gt, apos, quot. * The declaration of a parameter entity must precede any * reference to it. * Similarly, the declaration of a general entity must * precede any reference to it which appears in a default * value in an attribute-list declaration. Note that if * entities are declared in the external subset or in * external parameter entities, a non-validating processor * is not obligated to read and process their declarations; * for such documents, the rule that an entity must be * declared is a well-formedness constraint only if * standalone='yes'. */ if (ent == NULL) { if ((ctxt->standalone == 1) || ((ctxt->hasExternalSubset == 0) && (ctxt->hasPErefs == 0))) { xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY, "Entity '%s' not defined\n", name); } else { xmlErrMsgStr(ctxt, XML_WAR_UNDECLARED_ENTITY, "Entity '%s' not defined\n", name); if ((ctxt->inSubset == 0) && (ctxt->sax != NULL) && (ctxt->sax->reference != NULL)) { ctxt->sax->reference(ctxt->userData, name); } } xmlParserEntityCheck(ctxt, 0, ent, 0); ctxt->valid = 0; } /* * [ WFC: Parsed Entity ] * An entity reference must not contain the name of an * unparsed entity */ else if (ent->etype == XML_EXTERNAL_GENERAL_UNPARSED_ENTITY) { xmlFatalErrMsgStr(ctxt, XML_ERR_UNPARSED_ENTITY, "Entity reference to unparsed entity %s\n", name); } /* * [ WFC: No External Entity References ] * Attribute values cannot contain direct or indirect * entity references to external entities. */ else if ((ctxt->instate == XML_PARSER_ATTRIBUTE_VALUE) && (ent->etype == XML_EXTERNAL_GENERAL_PARSED_ENTITY)) { xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_EXTERNAL, "Attribute references external entity '%s'\n", name); } /* * [ WFC: No < in Attribute Values ] * The replacement text of any entity referred to directly or * indirectly in an attribute value (other than "&lt;") must * not contain a <. */ else if ((ctxt->instate == XML_PARSER_ATTRIBUTE_VALUE) && (ent != NULL) && (ent->etype != XML_INTERNAL_PREDEFINED_ENTITY)) { if (((ent->checked & 1) || (ent->checked == 0)) && (ent->content != NULL) && (xmlStrchr(ent->content, '<'))) { xmlFatalErrMsgStr(ctxt, XML_ERR_LT_IN_ATTRIBUTE, "'<' in entity '%s' is not allowed in attributes values\n", name); } } /* * Internal check, no parameter entities here ... */ else { switch (ent->etype) { case XML_INTERNAL_PARAMETER_ENTITY: case XML_EXTERNAL_PARAMETER_ENTITY: xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_PARAMETER, "Attempt to reference the parameter entity '%s'\n", name); break; default: break; } } /* * [ WFC: No Recursion ] * A parsed entity must not contain a recursive reference * to itself, either directly or indirectly. * Done somewhere else */ return(ent); } /** * xmlParseStringEntityRef: * @ctxt: an XML parser context * @str: a pointer to an index in the string * * parse ENTITY references declarations, but this version parses it from * a string value. * * [68] EntityRef ::= '&' Name ';' * * [ WFC: Entity Declared ] * In a document without any DTD, a document with only an internal DTD * subset which contains no parameter entity references, or a document * with "standalone='yes'", the Name given in the entity reference * must match that in an entity declaration, except that well-formed * documents need not declare any of the following entities: amp, lt, * gt, apos, quot. The declaration of a parameter entity must precede * any reference to it. Similarly, the declaration of a general entity * must precede any reference to it which appears in a default value in an * attribute-list declaration. Note that if entities are declared in the * external subset or in external parameter entities, a non-validating * processor is not obligated to read and process their declarations; * for such documents, the rule that an entity must be declared is a * well-formedness constraint only if standalone='yes'. * * [ WFC: Parsed Entity ] * An entity reference must not contain the name of an unparsed entity * * Returns the xmlEntityPtr if found, or NULL otherwise. The str pointer * is updated to the current location in the string. */ static xmlEntityPtr xmlParseStringEntityRef(xmlParserCtxtPtr ctxt, const xmlChar ** str) { xmlChar *name; const xmlChar *ptr; xmlChar cur; xmlEntityPtr ent = NULL; if ((str == NULL) || (*str == NULL)) return(NULL); ptr = *str; cur = *ptr; if (cur != '&') return(NULL); ptr++; name = xmlParseStringName(ctxt, &ptr); if (name == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED, "xmlParseStringEntityRef: no name\n"); *str = ptr; return(NULL); } if (*ptr != ';') { xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL); xmlFree(name); *str = ptr; return(NULL); } ptr++; /* * Predefined entities override any extra definition */ if ((ctxt->options & XML_PARSE_OLDSAX) == 0) { ent = xmlGetPredefinedEntity(name); if (ent != NULL) { xmlFree(name); *str = ptr; return(ent); } } /* * Increate the number of entity references parsed */ ctxt->nbentities++; /* * Ask first SAX for entity resolution, otherwise try the * entities which may have stored in the parser context. */ if (ctxt->sax != NULL) { if (ctxt->sax->getEntity != NULL) ent = ctxt->sax->getEntity(ctxt->userData, name); if ((ent == NULL) && (ctxt->options & XML_PARSE_OLDSAX)) ent = xmlGetPredefinedEntity(name); if ((ent == NULL) && (ctxt->userData==ctxt)) { ent = xmlSAX2GetEntity(ctxt, name); } } if (ctxt->instate == XML_PARSER_EOF) { xmlFree(name); return(NULL); } /* * [ WFC: Entity Declared ] * In a document without any DTD, a document with only an * internal DTD subset which contains no parameter entity * references, or a document with "standalone='yes'", the * Name given in the entity reference must match that in an * entity declaration, except that well-formed documents * need not declare any of the following entities: amp, lt, * gt, apos, quot. * The declaration of a parameter entity must precede any * reference to it. * Similarly, the declaration of a general entity must * precede any reference to it which appears in a default * value in an attribute-list declaration. Note that if * entities are declared in the external subset or in * external parameter entities, a non-validating processor * is not obligated to read and process their declarations; * for such documents, the rule that an entity must be * declared is a well-formedness constraint only if * standalone='yes'. */ if (ent == NULL) { if ((ctxt->standalone == 1) || ((ctxt->hasExternalSubset == 0) && (ctxt->hasPErefs == 0))) { xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY, "Entity '%s' not defined\n", name); } else { xmlErrMsgStr(ctxt, XML_WAR_UNDECLARED_ENTITY, "Entity '%s' not defined\n", name); } xmlParserEntityCheck(ctxt, 0, ent, 0); /* TODO ? check regressions ctxt->valid = 0; */ } /* * [ WFC: Parsed Entity ] * An entity reference must not contain the name of an * unparsed entity */ else if (ent->etype == XML_EXTERNAL_GENERAL_UNPARSED_ENTITY) { xmlFatalErrMsgStr(ctxt, XML_ERR_UNPARSED_ENTITY, "Entity reference to unparsed entity %s\n", name); } /* * [ WFC: No External Entity References ] * Attribute values cannot contain direct or indirect * entity references to external entities. */ else if ((ctxt->instate == XML_PARSER_ATTRIBUTE_VALUE) && (ent->etype == XML_EXTERNAL_GENERAL_PARSED_ENTITY)) { xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_EXTERNAL, "Attribute references external entity '%s'\n", name); } /* * [ WFC: No < in Attribute Values ] * The replacement text of any entity referred to directly or * indirectly in an attribute value (other than "&lt;") must * not contain a <. */ else if ((ctxt->instate == XML_PARSER_ATTRIBUTE_VALUE) && (ent != NULL) && (ent->content != NULL) && (ent->etype != XML_INTERNAL_PREDEFINED_ENTITY) && (xmlStrchr(ent->content, '<'))) { xmlFatalErrMsgStr(ctxt, XML_ERR_LT_IN_ATTRIBUTE, "'<' in entity '%s' is not allowed in attributes values\n", name); } /* * Internal check, no parameter entities here ... */ else { switch (ent->etype) { case XML_INTERNAL_PARAMETER_ENTITY: case XML_EXTERNAL_PARAMETER_ENTITY: xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_PARAMETER, "Attempt to reference the parameter entity '%s'\n", name); break; default: break; } } /* * [ WFC: No Recursion ] * A parsed entity must not contain a recursive reference * to itself, either directly or indirectly. * Done somewhere else */ xmlFree(name); *str = ptr; return(ent); } /** * xmlParsePEReference: * @ctxt: an XML parser context * * parse PEReference declarations * The entity content is handled directly by pushing it's content as * a new input stream. * * [69] PEReference ::= '%' Name ';' * * [ WFC: No Recursion ] * A parsed entity must not contain a recursive * reference to itself, either directly or indirectly. * * [ WFC: Entity Declared ] * In a document without any DTD, a document with only an internal DTD * subset which contains no parameter entity references, or a document * with "standalone='yes'", ... ... The declaration of a parameter * entity must precede any reference to it... * * [ VC: Entity Declared ] * In a document with an external subset or external parameter entities * with "standalone='no'", ... ... The declaration of a parameter entity * must precede any reference to it... * * [ WFC: In DTD ] * Parameter-entity references may only appear in the DTD. * NOTE: misleading but this is handled. */ void xmlParsePEReference(xmlParserCtxtPtr ctxt) { const xmlChar *name; xmlEntityPtr entity = NULL; xmlParserInputPtr input; if (RAW != '%') return; NEXT; name = xmlParseName(ctxt); if (name == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED, "xmlParsePEReference: no name\n"); return; } if (RAW != ';') { xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL); return; } NEXT; /* * Increate the number of entity references parsed */ ctxt->nbentities++; /* * Request the entity from SAX */ if ((ctxt->sax != NULL) && (ctxt->sax->getParameterEntity != NULL)) entity = ctxt->sax->getParameterEntity(ctxt->userData, name); if (ctxt->instate == XML_PARSER_EOF) return; if (entity == NULL) { /* * [ WFC: Entity Declared ] * In a document without any DTD, a document with only an * internal DTD subset which contains no parameter entity * references, or a document with "standalone='yes'", ... * ... The declaration of a parameter entity must precede * any reference to it... */ if ((ctxt->standalone == 1) || ((ctxt->hasExternalSubset == 0) && (ctxt->hasPErefs == 0))) { xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY, "PEReference: %%%s; not found\n", name); } else { /* * [ VC: Entity Declared ] * In a document with an external subset or external * parameter entities with "standalone='no'", ... * ... The declaration of a parameter entity must * precede any reference to it... */ xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY, "PEReference: %%%s; not found\n", name, NULL); ctxt->valid = 0; } xmlParserEntityCheck(ctxt, 0, NULL, 0); } else { /* * Internal checking in case the entity quest barfed */ if ((entity->etype != XML_INTERNAL_PARAMETER_ENTITY) && (entity->etype != XML_EXTERNAL_PARAMETER_ENTITY)) { xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY, "Internal: %%%s; is not a parameter entity\n", name, NULL); } else if (ctxt->input->free != deallocblankswrapper) { input = xmlNewBlanksWrapperInputStream(ctxt, entity); if (xmlPushInput(ctxt, input) < 0) return; } else { if ((entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) && ((ctxt->options & XML_PARSE_NOENT) == 0) && ((ctxt->options & XML_PARSE_DTDVALID) == 0) && ((ctxt->options & XML_PARSE_DTDLOAD) == 0) && ((ctxt->options & XML_PARSE_DTDATTR) == 0) && (ctxt->replaceEntities == 0) && (ctxt->validate == 0)) return; /* * TODO !!! * handle the extra spaces added before and after * c.f. http://www.w3.org/TR/REC-xml#as-PE */ input = xmlNewEntityInputStream(ctxt, entity); if (xmlPushInput(ctxt, input) < 0) return; if ((entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) && (CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) && (IS_BLANK_CH(NXT(5)))) { xmlParseTextDecl(ctxt); if (ctxt->errNo == XML_ERR_UNSUPPORTED_ENCODING) { /* * The XML REC instructs us to stop parsing * right here */ xmlHaltParser(ctxt); return; } } } } ctxt->hasPErefs = 1; } /** * xmlLoadEntityContent: * @ctxt: an XML parser context * @entity: an unloaded system entity * * Load the original content of the given system entity from the * ExternalID/SystemID given. This is to be used for Included in Literal * http://www.w3.org/TR/REC-xml/#inliteral processing of entities references * * Returns 0 in case of success and -1 in case of failure */ static int xmlLoadEntityContent(xmlParserCtxtPtr ctxt, xmlEntityPtr entity) { xmlParserInputPtr input; xmlBufferPtr buf; int l, c; int count = 0; if ((ctxt == NULL) || (entity == NULL) || ((entity->etype != XML_EXTERNAL_PARAMETER_ENTITY) && (entity->etype != XML_EXTERNAL_GENERAL_PARSED_ENTITY)) || (entity->content != NULL)) { xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "xmlLoadEntityContent parameter error"); return(-1); } if (xmlParserDebugEntities) xmlGenericError(xmlGenericErrorContext, "Reading %s entity content input\n", entity->name); buf = xmlBufferCreate(); if (buf == NULL) { xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "xmlLoadEntityContent parameter error"); return(-1); } input = xmlNewEntityInputStream(ctxt, entity); if (input == NULL) { xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "xmlLoadEntityContent input error"); xmlBufferFree(buf); return(-1); } /* * Push the entity as the current input, read char by char * saving to the buffer until the end of the entity or an error */ if (xmlPushInput(ctxt, input) < 0) { xmlBufferFree(buf); return(-1); } GROW; c = CUR_CHAR(l); while ((ctxt->input == input) && (ctxt->input->cur < ctxt->input->end) && (IS_CHAR(c))) { xmlBufferAdd(buf, ctxt->input->cur, l); if (count++ > XML_PARSER_CHUNK_SIZE) { count = 0; GROW; if (ctxt->instate == XML_PARSER_EOF) { xmlBufferFree(buf); return(-1); } } NEXTL(l); c = CUR_CHAR(l); if (c == 0) { count = 0; GROW; if (ctxt->instate == XML_PARSER_EOF) { xmlBufferFree(buf); return(-1); } c = CUR_CHAR(l); } } if ((ctxt->input == input) && (ctxt->input->cur >= ctxt->input->end)) { xmlPopInput(ctxt); } else if (!IS_CHAR(c)) { xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR, "xmlLoadEntityContent: invalid char value %d\n", c); xmlBufferFree(buf); return(-1); } entity->content = buf->content; buf->content = NULL; xmlBufferFree(buf); return(0); } /** * xmlParseStringPEReference: * @ctxt: an XML parser context * @str: a pointer to an index in the string * * parse PEReference declarations * * [69] PEReference ::= '%' Name ';' * * [ WFC: No Recursion ] * A parsed entity must not contain a recursive * reference to itself, either directly or indirectly. * * [ WFC: Entity Declared ] * In a document without any DTD, a document with only an internal DTD * subset which contains no parameter entity references, or a document * with "standalone='yes'", ... ... The declaration of a parameter * entity must precede any reference to it... * * [ VC: Entity Declared ] * In a document with an external subset or external parameter entities * with "standalone='no'", ... ... The declaration of a parameter entity * must precede any reference to it... * * [ WFC: In DTD ] * Parameter-entity references may only appear in the DTD. * NOTE: misleading but this is handled. * * Returns the string of the entity content. * str is updated to the current value of the index */ static xmlEntityPtr xmlParseStringPEReference(xmlParserCtxtPtr ctxt, const xmlChar **str) { const xmlChar *ptr; xmlChar cur; xmlChar *name; xmlEntityPtr entity = NULL; if ((str == NULL) || (*str == NULL)) return(NULL); ptr = *str; cur = *ptr; if (cur != '%') return(NULL); ptr++; name = xmlParseStringName(ctxt, &ptr); if (name == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED, "xmlParseStringPEReference: no name\n"); *str = ptr; return(NULL); } cur = *ptr; if (cur != ';') { xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL); xmlFree(name); *str = ptr; return(NULL); } ptr++; /* * Increate the number of entity references parsed */ ctxt->nbentities++; /* * Request the entity from SAX */ if ((ctxt->sax != NULL) && (ctxt->sax->getParameterEntity != NULL)) entity = ctxt->sax->getParameterEntity(ctxt->userData, name); if (ctxt->instate == XML_PARSER_EOF) { xmlFree(name); return(NULL); } if (entity == NULL) { /* * [ WFC: Entity Declared ] * In a document without any DTD, a document with only an * internal DTD subset which contains no parameter entity * references, or a document with "standalone='yes'", ... * ... The declaration of a parameter entity must precede * any reference to it... */ if ((ctxt->standalone == 1) || ((ctxt->hasExternalSubset == 0) && (ctxt->hasPErefs == 0))) { xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY, "PEReference: %%%s; not found\n", name); } else { /* * [ VC: Entity Declared ] * In a document with an external subset or external * parameter entities with "standalone='no'", ... * ... The declaration of a parameter entity must * precede any reference to it... */ xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY, "PEReference: %%%s; not found\n", name, NULL); ctxt->valid = 0; } xmlParserEntityCheck(ctxt, 0, NULL, 0); } else { /* * Internal checking in case the entity quest barfed */ if ((entity->etype != XML_INTERNAL_PARAMETER_ENTITY) && (entity->etype != XML_EXTERNAL_PARAMETER_ENTITY)) { xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY, "%%%s; is not a parameter entity\n", name, NULL); } } ctxt->hasPErefs = 1; xmlFree(name); *str = ptr; return(entity); } /** * xmlParseDocTypeDecl: * @ctxt: an XML parser context * * parse a DOCTYPE declaration * * [28] doctypedecl ::= '<!DOCTYPE' S Name (S ExternalID)? S? * ('[' (markupdecl | PEReference | S)* ']' S?)? '>' * * [ VC: Root Element Type ] * The Name in the document type declaration must match the element * type of the root element. */ void xmlParseDocTypeDecl(xmlParserCtxtPtr ctxt) { const xmlChar *name = NULL; xmlChar *ExternalID = NULL; xmlChar *URI = NULL; /* * We know that '<!DOCTYPE' has been detected. */ SKIP(9); SKIP_BLANKS; /* * Parse the DOCTYPE name. */ name = xmlParseName(ctxt); if (name == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED, "xmlParseDocTypeDecl : no DOCTYPE name !\n"); } ctxt->intSubName = name; SKIP_BLANKS; /* * Check for SystemID and ExternalID */ URI = xmlParseExternalID(ctxt, &ExternalID, 1); if ((URI != NULL) || (ExternalID != NULL)) { ctxt->hasExternalSubset = 1; } ctxt->extSubURI = URI; ctxt->extSubSystem = ExternalID; SKIP_BLANKS; /* * Create and update the internal subset. */ if ((ctxt->sax != NULL) && (ctxt->sax->internalSubset != NULL) && (!ctxt->disableSAX)) ctxt->sax->internalSubset(ctxt->userData, name, ExternalID, URI); if (ctxt->instate == XML_PARSER_EOF) return; /* * Is there any internal subset declarations ? * they are handled separately in xmlParseInternalSubset() */ if (RAW == '[') return; /* * We should be at the end of the DOCTYPE declaration. */ if (RAW != '>') { xmlFatalErr(ctxt, XML_ERR_DOCTYPE_NOT_FINISHED, NULL); } NEXT; } /** * xmlParseInternalSubset: * @ctxt: an XML parser context * * parse the internal subset declaration * * [28 end] ('[' (markupdecl | PEReference | S)* ']' S?)? '>' */ static void xmlParseInternalSubset(xmlParserCtxtPtr ctxt) { /* * Is there any DTD definition ? */ if (RAW == '[') { ctxt->instate = XML_PARSER_DTD; NEXT; /* * Parse the succession of Markup declarations and * PEReferences. * Subsequence (markupdecl | PEReference | S)* */ while ((RAW != ']') && (ctxt->instate != XML_PARSER_EOF)) { const xmlChar *check = CUR_PTR; unsigned int cons = ctxt->input->consumed; SKIP_BLANKS; xmlParseMarkupDecl(ctxt); xmlParsePEReference(ctxt); /* * Pop-up of finished entities. */ while ((RAW == 0) && (ctxt->inputNr > 1)) xmlPopInput(ctxt); if ((CUR_PTR == check) && (cons == ctxt->input->consumed)) { xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "xmlParseInternalSubset: error detected in Markup declaration\n"); break; } } if (RAW == ']') { NEXT; SKIP_BLANKS; } } /* * We should be at the end of the DOCTYPE declaration. */ if (RAW != '>') { xmlFatalErr(ctxt, XML_ERR_DOCTYPE_NOT_FINISHED, NULL); return; } NEXT; } #ifdef LIBXML_SAX1_ENABLED /** * xmlParseAttribute: * @ctxt: an XML parser context * @value: a xmlChar ** used to store the value of the attribute * * parse an attribute * * [41] Attribute ::= Name Eq AttValue * * [ WFC: No External Entity References ] * Attribute values cannot contain direct or indirect entity references * to external entities. * * [ WFC: No < in Attribute Values ] * The replacement text of any entity referred to directly or indirectly in * an attribute value (other than "&lt;") must not contain a <. * * [ VC: Attribute Value Type ] * The attribute must have been declared; the value must be of the type * declared for it. * * [25] Eq ::= S? '=' S? * * With namespace: * * [NS 11] Attribute ::= QName Eq AttValue * * Also the case QName == xmlns:??? is handled independently as a namespace * definition. * * Returns the attribute name, and the value in *value. */ const xmlChar * xmlParseAttribute(xmlParserCtxtPtr ctxt, xmlChar **value) { const xmlChar *name; xmlChar *val; *value = NULL; GROW; name = xmlParseName(ctxt); if (name == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED, "error parsing attribute name\n"); return(NULL); } /* * read the value */ SKIP_BLANKS; if (RAW == '=') { NEXT; SKIP_BLANKS; val = xmlParseAttValue(ctxt); ctxt->instate = XML_PARSER_CONTENT; } else { xmlFatalErrMsgStr(ctxt, XML_ERR_ATTRIBUTE_WITHOUT_VALUE, "Specification mandate value for attribute %s\n", name); return(NULL); } /* * Check that xml:lang conforms to the specification * No more registered as an error, just generate a warning now * since this was deprecated in XML second edition */ if ((ctxt->pedantic) && (xmlStrEqual(name, BAD_CAST "xml:lang"))) { if (!xmlCheckLanguageID(val)) { xmlWarningMsg(ctxt, XML_WAR_LANG_VALUE, "Malformed value for xml:lang : %s\n", val, NULL); } } /* * Check that xml:space conforms to the specification */ if (xmlStrEqual(name, BAD_CAST "xml:space")) { if (xmlStrEqual(val, BAD_CAST "default")) *(ctxt->space) = 0; else if (xmlStrEqual(val, BAD_CAST "preserve")) *(ctxt->space) = 1; else { xmlWarningMsg(ctxt, XML_WAR_SPACE_VALUE, "Invalid value \"%s\" for xml:space : \"default\" or \"preserve\" expected\n", val, NULL); } } *value = val; return(name); } /** * xmlParseStartTag: * @ctxt: an XML parser context * * parse a start of tag either for rule element or * EmptyElement. In both case we don't parse the tag closing chars. * * [40] STag ::= '<' Name (S Attribute)* S? '>' * * [ WFC: Unique Att Spec ] * No attribute name may appear more than once in the same start-tag or * empty-element tag. * * [44] EmptyElemTag ::= '<' Name (S Attribute)* S? '/>' * * [ WFC: Unique Att Spec ] * No attribute name may appear more than once in the same start-tag or * empty-element tag. * * With namespace: * * [NS 8] STag ::= '<' QName (S Attribute)* S? '>' * * [NS 10] EmptyElement ::= '<' QName (S Attribute)* S? '/>' * * Returns the element name parsed */ const xmlChar * xmlParseStartTag(xmlParserCtxtPtr ctxt) { const xmlChar *name; const xmlChar *attname; xmlChar *attvalue; const xmlChar **atts = ctxt->atts; int nbatts = 0; int maxatts = ctxt->maxatts; int i; if (RAW != '<') return(NULL); NEXT1; name = xmlParseName(ctxt); if (name == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED, "xmlParseStartTag: invalid element name\n"); return(NULL); } /* * Now parse the attributes, it ends up with the ending * * (S Attribute)* S? */ SKIP_BLANKS; GROW; while (((RAW != '>') && ((RAW != '/') || (NXT(1) != '>')) && (IS_BYTE_CHAR(RAW))) && (ctxt->instate != XML_PARSER_EOF)) { const xmlChar *q = CUR_PTR; unsigned int cons = ctxt->input->consumed; attname = xmlParseAttribute(ctxt, &attvalue); if ((attname != NULL) && (attvalue != NULL)) { /* * [ WFC: Unique Att Spec ] * No attribute name may appear more than once in the same * start-tag or empty-element tag. */ for (i = 0; i < nbatts;i += 2) { if (xmlStrEqual(atts[i], attname)) { xmlErrAttributeDup(ctxt, NULL, attname); xmlFree(attvalue); goto failed; } } /* * Add the pair to atts */ if (atts == NULL) { maxatts = 22; /* allow for 10 attrs by default */ atts = (const xmlChar **) xmlMalloc(maxatts * sizeof(xmlChar *)); if (atts == NULL) { xmlErrMemory(ctxt, NULL); if (attvalue != NULL) xmlFree(attvalue); goto failed; } ctxt->atts = atts; ctxt->maxatts = maxatts; } else if (nbatts + 4 > maxatts) { const xmlChar **n; maxatts *= 2; n = (const xmlChar **) xmlRealloc((void *) atts, maxatts * sizeof(const xmlChar *)); if (n == NULL) { xmlErrMemory(ctxt, NULL); if (attvalue != NULL) xmlFree(attvalue); goto failed; } atts = n; ctxt->atts = atts; ctxt->maxatts = maxatts; } atts[nbatts++] = attname; atts[nbatts++] = attvalue; atts[nbatts] = NULL; atts[nbatts + 1] = NULL; } else { if (attvalue != NULL) xmlFree(attvalue); } failed: GROW if ((RAW == '>') || (((RAW == '/') && (NXT(1) == '>')))) break; if (!IS_BLANK_CH(RAW)) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "attributes construct error\n"); } SKIP_BLANKS; if ((cons == ctxt->input->consumed) && (q == CUR_PTR) && (attname == NULL) && (attvalue == NULL)) { xmlFatalErrMsg(ctxt, XML_ERR_INTERNAL_ERROR, "xmlParseStartTag: problem parsing attributes\n"); break; } SHRINK; GROW; } /* * SAX: Start of Element ! */ if ((ctxt->sax != NULL) && (ctxt->sax->startElement != NULL) && (!ctxt->disableSAX)) { if (nbatts > 0) ctxt->sax->startElement(ctxt->userData, name, atts); else ctxt->sax->startElement(ctxt->userData, name, NULL); } if (atts != NULL) { /* Free only the content strings */ for (i = 1;i < nbatts;i+=2) if (atts[i] != NULL) xmlFree((xmlChar *) atts[i]); } return(name); } /** * xmlParseEndTag1: * @ctxt: an XML parser context * @line: line of the start tag * @nsNr: number of namespaces on the start tag * * parse an end of tag * * [42] ETag ::= '</' Name S? '>' * * With namespace * * [NS 9] ETag ::= '</' QName S? '>' */ static void xmlParseEndTag1(xmlParserCtxtPtr ctxt, int line) { const xmlChar *name; GROW; if ((RAW != '<') || (NXT(1) != '/')) { xmlFatalErrMsg(ctxt, XML_ERR_LTSLASH_REQUIRED, "xmlParseEndTag: '</' not found\n"); return; } SKIP(2); name = xmlParseNameAndCompare(ctxt,ctxt->name); /* * We should definitely be at the ending "S? '>'" part */ GROW; SKIP_BLANKS; if ((!IS_BYTE_CHAR(RAW)) || (RAW != '>')) { xmlFatalErr(ctxt, XML_ERR_GT_REQUIRED, NULL); } else NEXT1; /* * [ WFC: Element Type Match ] * The Name in an element's end-tag must match the element type in the * start-tag. * */ if (name != (xmlChar*)1) { if (name == NULL) name = BAD_CAST "unparseable"; xmlFatalErrMsgStrIntStr(ctxt, XML_ERR_TAG_NAME_MISMATCH, "Opening and ending tag mismatch: %s line %d and %s\n", ctxt->name, line, name); } /* * SAX: End of Tag */ if ((ctxt->sax != NULL) && (ctxt->sax->endElement != NULL) && (!ctxt->disableSAX)) ctxt->sax->endElement(ctxt->userData, ctxt->name); namePop(ctxt); spacePop(ctxt); return; } /** * xmlParseEndTag: * @ctxt: an XML parser context * * parse an end of tag * * [42] ETag ::= '</' Name S? '>' * * With namespace * * [NS 9] ETag ::= '</' QName S? '>' */ void xmlParseEndTag(xmlParserCtxtPtr ctxt) { xmlParseEndTag1(ctxt, 0); } #endif /* LIBXML_SAX1_ENABLED */ /************************************************************************ * * * SAX 2 specific operations * * * ************************************************************************/ /* * xmlGetNamespace: * @ctxt: an XML parser context * @prefix: the prefix to lookup * * Lookup the namespace name for the @prefix (which ca be NULL) * The prefix must come from the @ctxt->dict dictionary * * Returns the namespace name or NULL if not bound */ static const xmlChar * xmlGetNamespace(xmlParserCtxtPtr ctxt, const xmlChar *prefix) { int i; if (prefix == ctxt->str_xml) return(ctxt->str_xml_ns); for (i = ctxt->nsNr - 2;i >= 0;i-=2) if (ctxt->nsTab[i] == prefix) { if ((prefix == NULL) && (*ctxt->nsTab[i + 1] == 0)) return(NULL); return(ctxt->nsTab[i + 1]); } return(NULL); } /** * xmlParseQName: * @ctxt: an XML parser context * @prefix: pointer to store the prefix part * * parse an XML Namespace QName * * [6] QName ::= (Prefix ':')? LocalPart * [7] Prefix ::= NCName * [8] LocalPart ::= NCName * * Returns the Name parsed or NULL */ static const xmlChar * xmlParseQName(xmlParserCtxtPtr ctxt, const xmlChar **prefix) { const xmlChar *l, *p; GROW; l = xmlParseNCName(ctxt); if (l == NULL) { if (CUR == ':') { l = xmlParseName(ctxt); if (l != NULL) { xmlNsErr(ctxt, XML_NS_ERR_QNAME, "Failed to parse QName '%s'\n", l, NULL, NULL); *prefix = NULL; return(l); } } return(NULL); } if (CUR == ':') { NEXT; p = l; l = xmlParseNCName(ctxt); if (l == NULL) { xmlChar *tmp; xmlNsErr(ctxt, XML_NS_ERR_QNAME, "Failed to parse QName '%s:'\n", p, NULL, NULL); l = xmlParseNmtoken(ctxt); if (l == NULL) tmp = xmlBuildQName(BAD_CAST "", p, NULL, 0); else { tmp = xmlBuildQName(l, p, NULL, 0); xmlFree((char *)l); } p = xmlDictLookup(ctxt->dict, tmp, -1); if (tmp != NULL) xmlFree(tmp); *prefix = NULL; return(p); } if (CUR == ':') { xmlChar *tmp; xmlNsErr(ctxt, XML_NS_ERR_QNAME, "Failed to parse QName '%s:%s:'\n", p, l, NULL); NEXT; tmp = (xmlChar *) xmlParseName(ctxt); if (tmp != NULL) { tmp = xmlBuildQName(tmp, l, NULL, 0); l = xmlDictLookup(ctxt->dict, tmp, -1); if (tmp != NULL) xmlFree(tmp); *prefix = p; return(l); } tmp = xmlBuildQName(BAD_CAST "", l, NULL, 0); l = xmlDictLookup(ctxt->dict, tmp, -1); if (tmp != NULL) xmlFree(tmp); *prefix = p; return(l); } *prefix = p; } else *prefix = NULL; return(l); } /** * xmlParseQNameAndCompare: * @ctxt: an XML parser context * @name: the localname * @prefix: the prefix, if any. * * parse an XML name and compares for match * (specialized for endtag parsing) * * Returns NULL for an illegal name, (xmlChar*) 1 for success * and the name for mismatch */ static const xmlChar * xmlParseQNameAndCompare(xmlParserCtxtPtr ctxt, xmlChar const *name, xmlChar const *prefix) { const xmlChar *cmp; const xmlChar *in; const xmlChar *ret; const xmlChar *prefix2; if (prefix == NULL) return(xmlParseNameAndCompare(ctxt, name)); GROW; in = ctxt->input->cur; cmp = prefix; while (*in != 0 && *in == *cmp) { ++in; ++cmp; } if ((*cmp == 0) && (*in == ':')) { in++; cmp = name; while (*in != 0 && *in == *cmp) { ++in; ++cmp; } if (*cmp == 0 && (*in == '>' || IS_BLANK_CH (*in))) { /* success */ ctxt->input->cur = in; return((const xmlChar*) 1); } } /* * all strings coms from the dictionary, equality can be done directly */ ret = xmlParseQName (ctxt, &prefix2); if ((ret == name) && (prefix == prefix2)) return((const xmlChar*) 1); return ret; } /** * xmlParseAttValueInternal: * @ctxt: an XML parser context * @len: attribute len result * @alloc: whether the attribute was reallocated as a new string * @normalize: if 1 then further non-CDATA normalization must be done * * parse a value for an attribute. * NOTE: if no normalization is needed, the routine will return pointers * directly from the data buffer. * * 3.3.3 Attribute-Value Normalization: * Before the value of an attribute is passed to the application or * checked for validity, the XML processor must normalize it as follows: * - a character reference is processed by appending the referenced * character to the attribute value * - an entity reference is processed by recursively processing the * replacement text of the entity * - a whitespace character (#x20, #xD, #xA, #x9) is processed by * appending #x20 to the normalized value, except that only a single * #x20 is appended for a "#xD#xA" sequence that is part of an external * parsed entity or the literal entity value of an internal parsed entity * - other characters are processed by appending them to the normalized value * If the declared value is not CDATA, then the XML processor must further * process the normalized attribute value by discarding any leading and * trailing space (#x20) characters, and by replacing sequences of space * (#x20) characters by a single space (#x20) character. * All attributes for which no declaration has been read should be treated * by a non-validating parser as if declared CDATA. * * Returns the AttValue parsed or NULL. The value has to be freed by the * caller if it was copied, this can be detected by val[*len] == 0. */ static xmlChar * xmlParseAttValueInternal(xmlParserCtxtPtr ctxt, int *len, int *alloc, int normalize) { xmlChar limit = 0; const xmlChar *in = NULL, *start, *end, *last; xmlChar *ret = NULL; int line, col; GROW; in = (xmlChar *) CUR_PTR; line = ctxt->input->line; col = ctxt->input->col; if (*in != '"' && *in != '\'') { xmlFatalErr(ctxt, XML_ERR_ATTRIBUTE_NOT_STARTED, NULL); return (NULL); } ctxt->instate = XML_PARSER_ATTRIBUTE_VALUE; /* * try to handle in this routine the most common case where no * allocation of a new string is required and where content is * pure ASCII. */ limit = *in++; col++; end = ctxt->input->end; start = in; if (in >= end) { const xmlChar *oldbase = ctxt->input->base; GROW; if (oldbase != ctxt->input->base) { long delta = ctxt->input->base - oldbase; start = start + delta; in = in + delta; } end = ctxt->input->end; } if (normalize) { /* * Skip any leading spaces */ while ((in < end) && (*in != limit) && ((*in == 0x20) || (*in == 0x9) || (*in == 0xA) || (*in == 0xD))) { if (*in == 0xA) { line++; col = 1; } else { col++; } in++; start = in; if (in >= end) { const xmlChar *oldbase = ctxt->input->base; GROW; if (ctxt->instate == XML_PARSER_EOF) return(NULL); if (oldbase != ctxt->input->base) { long delta = ctxt->input->base - oldbase; start = start + delta; in = in + delta; } end = ctxt->input->end; if (((in - start) > XML_MAX_TEXT_LENGTH) && ((ctxt->options & XML_PARSE_HUGE) == 0)) { xmlFatalErrMsg(ctxt, XML_ERR_ATTRIBUTE_NOT_FINISHED, "AttValue length too long\n"); return(NULL); } } } while ((in < end) && (*in != limit) && (*in >= 0x20) && (*in <= 0x7f) && (*in != '&') && (*in != '<')) { col++; if ((*in++ == 0x20) && (*in == 0x20)) break; if (in >= end) { const xmlChar *oldbase = ctxt->input->base; GROW; if (ctxt->instate == XML_PARSER_EOF) return(NULL); if (oldbase != ctxt->input->base) { long delta = ctxt->input->base - oldbase; start = start + delta; in = in + delta; } end = ctxt->input->end; if (((in - start) > XML_MAX_TEXT_LENGTH) && ((ctxt->options & XML_PARSE_HUGE) == 0)) { xmlFatalErrMsg(ctxt, XML_ERR_ATTRIBUTE_NOT_FINISHED, "AttValue length too long\n"); return(NULL); } } } last = in; /* * skip the trailing blanks */ while ((last[-1] == 0x20) && (last > start)) last--; while ((in < end) && (*in != limit) && ((*in == 0x20) || (*in == 0x9) || (*in == 0xA) || (*in == 0xD))) { if (*in == 0xA) { line++, col = 1; } else { col++; } in++; if (in >= end) { const xmlChar *oldbase = ctxt->input->base; GROW; if (ctxt->instate == XML_PARSER_EOF) return(NULL); if (oldbase != ctxt->input->base) { long delta = ctxt->input->base - oldbase; start = start + delta; in = in + delta; last = last + delta; } end = ctxt->input->end; if (((in - start) > XML_MAX_TEXT_LENGTH) && ((ctxt->options & XML_PARSE_HUGE) == 0)) { xmlFatalErrMsg(ctxt, XML_ERR_ATTRIBUTE_NOT_FINISHED, "AttValue length too long\n"); return(NULL); } } } if (((in - start) > XML_MAX_TEXT_LENGTH) && ((ctxt->options & XML_PARSE_HUGE) == 0)) { xmlFatalErrMsg(ctxt, XML_ERR_ATTRIBUTE_NOT_FINISHED, "AttValue length too long\n"); return(NULL); } if (*in != limit) goto need_complex; } else { while ((in < end) && (*in != limit) && (*in >= 0x20) && (*in <= 0x7f) && (*in != '&') && (*in != '<')) { in++; col++; if (in >= end) { const xmlChar *oldbase = ctxt->input->base; GROW; if (ctxt->instate == XML_PARSER_EOF) return(NULL); if (oldbase != ctxt->input->base) { long delta = ctxt->input->base - oldbase; start = start + delta; in = in + delta; } end = ctxt->input->end; if (((in - start) > XML_MAX_TEXT_LENGTH) && ((ctxt->options & XML_PARSE_HUGE) == 0)) { xmlFatalErrMsg(ctxt, XML_ERR_ATTRIBUTE_NOT_FINISHED, "AttValue length too long\n"); return(NULL); } } } last = in; if (((in - start) > XML_MAX_TEXT_LENGTH) && ((ctxt->options & XML_PARSE_HUGE) == 0)) { xmlFatalErrMsg(ctxt, XML_ERR_ATTRIBUTE_NOT_FINISHED, "AttValue length too long\n"); return(NULL); } if (*in != limit) goto need_complex; } in++; col++; if (len != NULL) { *len = last - start; ret = (xmlChar *) start; } else { if (alloc) *alloc = 1; ret = xmlStrndup(start, last - start); } CUR_PTR = in; ctxt->input->line = line; ctxt->input->col = col; if (alloc) *alloc = 0; return ret; need_complex: if (alloc) *alloc = 1; return xmlParseAttValueComplex(ctxt, len, normalize); } /** * xmlParseAttribute2: * @ctxt: an XML parser context * @pref: the element prefix * @elem: the element name * @prefix: a xmlChar ** used to store the value of the attribute prefix * @value: a xmlChar ** used to store the value of the attribute * @len: an int * to save the length of the attribute * @alloc: an int * to indicate if the attribute was allocated * * parse an attribute in the new SAX2 framework. * * Returns the attribute name, and the value in *value, . */ static const xmlChar * xmlParseAttribute2(xmlParserCtxtPtr ctxt, const xmlChar * pref, const xmlChar * elem, const xmlChar ** prefix, xmlChar ** value, int *len, int *alloc) { const xmlChar *name; xmlChar *val, *internal_val = NULL; int normalize = 0; *value = NULL; GROW; name = xmlParseQName(ctxt, prefix); if (name == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED, "error parsing attribute name\n"); return (NULL); } /* * get the type if needed */ if (ctxt->attsSpecial != NULL) { int type; type = (int) (long) xmlHashQLookup2(ctxt->attsSpecial, pref, elem, *prefix, name); if (type != 0) normalize = 1; } /* * read the value */ SKIP_BLANKS; if (RAW == '=') { NEXT; SKIP_BLANKS; val = xmlParseAttValueInternal(ctxt, len, alloc, normalize); if (normalize) { /* * Sometimes a second normalisation pass for spaces is needed * but that only happens if charrefs or entities refernces * have been used in the attribute value, i.e. the attribute * value have been extracted in an allocated string already. */ if (*alloc) { const xmlChar *val2; val2 = xmlAttrNormalizeSpace2(ctxt, val, len); if ((val2 != NULL) && (val2 != val)) { xmlFree(val); val = (xmlChar *) val2; } } } ctxt->instate = XML_PARSER_CONTENT; } else { xmlFatalErrMsgStr(ctxt, XML_ERR_ATTRIBUTE_WITHOUT_VALUE, "Specification mandate value for attribute %s\n", name); return (NULL); } if (*prefix == ctxt->str_xml) { /* * Check that xml:lang conforms to the specification * No more registered as an error, just generate a warning now * since this was deprecated in XML second edition */ if ((ctxt->pedantic) && (xmlStrEqual(name, BAD_CAST "lang"))) { internal_val = xmlStrndup(val, *len); if (!xmlCheckLanguageID(internal_val)) { xmlWarningMsg(ctxt, XML_WAR_LANG_VALUE, "Malformed value for xml:lang : %s\n", internal_val, NULL); } } /* * Check that xml:space conforms to the specification */ if (xmlStrEqual(name, BAD_CAST "space")) { internal_val = xmlStrndup(val, *len); if (xmlStrEqual(internal_val, BAD_CAST "default")) *(ctxt->space) = 0; else if (xmlStrEqual(internal_val, BAD_CAST "preserve")) *(ctxt->space) = 1; else { xmlWarningMsg(ctxt, XML_WAR_SPACE_VALUE, "Invalid value \"%s\" for xml:space : \"default\" or \"preserve\" expected\n", internal_val, NULL); } } if (internal_val) { xmlFree(internal_val); } } *value = val; return (name); } /** * xmlParseStartTag2: * @ctxt: an XML parser context * * parse a start of tag either for rule element or * EmptyElement. In both case we don't parse the tag closing chars. * This routine is called when running SAX2 parsing * * [40] STag ::= '<' Name (S Attribute)* S? '>' * * [ WFC: Unique Att Spec ] * No attribute name may appear more than once in the same start-tag or * empty-element tag. * * [44] EmptyElemTag ::= '<' Name (S Attribute)* S? '/>' * * [ WFC: Unique Att Spec ] * No attribute name may appear more than once in the same start-tag or * empty-element tag. * * With namespace: * * [NS 8] STag ::= '<' QName (S Attribute)* S? '>' * * [NS 10] EmptyElement ::= '<' QName (S Attribute)* S? '/>' * * Returns the element name parsed */ static const xmlChar * xmlParseStartTag2(xmlParserCtxtPtr ctxt, const xmlChar **pref, const xmlChar **URI, int *tlen) { const xmlChar *localname; const xmlChar *prefix; const xmlChar *attname; const xmlChar *aprefix; const xmlChar *nsname; xmlChar *attvalue; const xmlChar **atts = ctxt->atts; int maxatts = ctxt->maxatts; int nratts, nbatts, nbdef; int i, j, nbNs, attval; unsigned long cur; int nsNr = ctxt->nsNr; if (RAW != '<') return(NULL); NEXT1; /* * NOTE: it is crucial with the SAX2 API to never call SHRINK beyond that * point since the attribute values may be stored as pointers to * the buffer and calling SHRINK would destroy them ! * The Shrinking is only possible once the full set of attribute * callbacks have been done. */ SHRINK; cur = ctxt->input->cur - ctxt->input->base; nbatts = 0; nratts = 0; nbdef = 0; nbNs = 0; attval = 0; /* Forget any namespaces added during an earlier parse of this element. */ ctxt->nsNr = nsNr; localname = xmlParseQName(ctxt, &prefix); if (localname == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED, "StartTag: invalid element name\n"); return(NULL); } *tlen = ctxt->input->cur - ctxt->input->base - cur; /* * Now parse the attributes, it ends up with the ending * * (S Attribute)* S? */ SKIP_BLANKS; GROW; while (((RAW != '>') && ((RAW != '/') || (NXT(1) != '>')) && (IS_BYTE_CHAR(RAW))) && (ctxt->instate != XML_PARSER_EOF)) { const xmlChar *q = CUR_PTR; unsigned int cons = ctxt->input->consumed; int len = -1, alloc = 0; attname = xmlParseAttribute2(ctxt, prefix, localname, &aprefix, &attvalue, &len, &alloc); if ((attname == NULL) || (attvalue == NULL)) goto next_attr; if (len < 0) len = xmlStrlen(attvalue); if ((attname == ctxt->str_xmlns) && (aprefix == NULL)) { const xmlChar *URL = xmlDictLookup(ctxt->dict, attvalue, len); xmlURIPtr uri; if (URL == NULL) { xmlErrMemory(ctxt, "dictionary allocation failure"); if ((attvalue != NULL) && (alloc != 0)) xmlFree(attvalue); return(NULL); } if (*URL != 0) { uri = xmlParseURI((const char *) URL); if (uri == NULL) { xmlNsErr(ctxt, XML_WAR_NS_URI, "xmlns: '%s' is not a valid URI\n", URL, NULL, NULL); } else { if (uri->scheme == NULL) { xmlNsWarn(ctxt, XML_WAR_NS_URI_RELATIVE, "xmlns: URI %s is not absolute\n", URL, NULL, NULL); } xmlFreeURI(uri); } if (URL == ctxt->str_xml_ns) { if (attname != ctxt->str_xml) { xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE, "xml namespace URI cannot be the default namespace\n", NULL, NULL, NULL); } goto next_attr; } if ((len == 29) && (xmlStrEqual(URL, BAD_CAST "http://www.w3.org/2000/xmlns/"))) { xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE, "reuse of the xmlns namespace name is forbidden\n", NULL, NULL, NULL); goto next_attr; } } /* * check that it's not a defined namespace */ for (j = 1;j <= nbNs;j++) if (ctxt->nsTab[ctxt->nsNr - 2 * j] == NULL) break; if (j <= nbNs) xmlErrAttributeDup(ctxt, NULL, attname); else if (nsPush(ctxt, NULL, URL) > 0) nbNs++; } else if (aprefix == ctxt->str_xmlns) { const xmlChar *URL = xmlDictLookup(ctxt->dict, attvalue, len); xmlURIPtr uri; if (attname == ctxt->str_xml) { if (URL != ctxt->str_xml_ns) { xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE, "xml namespace prefix mapped to wrong URI\n", NULL, NULL, NULL); } /* * Do not keep a namespace definition node */ goto next_attr; } if (URL == ctxt->str_xml_ns) { if (attname != ctxt->str_xml) { xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE, "xml namespace URI mapped to wrong prefix\n", NULL, NULL, NULL); } goto next_attr; } if (attname == ctxt->str_xmlns) { xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE, "redefinition of the xmlns prefix is forbidden\n", NULL, NULL, NULL); goto next_attr; } if ((len == 29) && (xmlStrEqual(URL, BAD_CAST "http://www.w3.org/2000/xmlns/"))) { xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE, "reuse of the xmlns namespace name is forbidden\n", NULL, NULL, NULL); goto next_attr; } if ((URL == NULL) || (URL[0] == 0)) { xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE, "xmlns:%s: Empty XML namespace is not allowed\n", attname, NULL, NULL); goto next_attr; } else { uri = xmlParseURI((const char *) URL); if (uri == NULL) { xmlNsErr(ctxt, XML_WAR_NS_URI, "xmlns:%s: '%s' is not a valid URI\n", attname, URL, NULL); } else { if ((ctxt->pedantic) && (uri->scheme == NULL)) { xmlNsWarn(ctxt, XML_WAR_NS_URI_RELATIVE, "xmlns:%s: URI %s is not absolute\n", attname, URL, NULL); } xmlFreeURI(uri); } } /* * check that it's not a defined namespace */ for (j = 1;j <= nbNs;j++) if (ctxt->nsTab[ctxt->nsNr - 2 * j] == attname) break; if (j <= nbNs) xmlErrAttributeDup(ctxt, aprefix, attname); else if (nsPush(ctxt, attname, URL) > 0) nbNs++; } else { /* * Add the pair to atts */ if ((atts == NULL) || (nbatts + 5 > maxatts)) { if (xmlCtxtGrowAttrs(ctxt, nbatts + 5) < 0) { goto next_attr; } maxatts = ctxt->maxatts; atts = ctxt->atts; } ctxt->attallocs[nratts++] = alloc; atts[nbatts++] = attname; atts[nbatts++] = aprefix; /* * The namespace URI field is used temporarily to point at the * base of the current input buffer for non-alloced attributes. * When the input buffer is reallocated, all the pointers become * invalid, but they can be reconstructed later. */ if (alloc) atts[nbatts++] = NULL; else atts[nbatts++] = ctxt->input->base; atts[nbatts++] = attvalue; attvalue += len; atts[nbatts++] = attvalue; /* * tag if some deallocation is needed */ if (alloc != 0) attval = 1; attvalue = NULL; /* moved into atts */ } next_attr: if ((attvalue != NULL) && (alloc != 0)) { xmlFree(attvalue); attvalue = NULL; } GROW if (ctxt->instate == XML_PARSER_EOF) break; if ((RAW == '>') || (((RAW == '/') && (NXT(1) == '>')))) break; if (!IS_BLANK_CH(RAW)) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "attributes construct error\n"); break; } SKIP_BLANKS; if ((cons == ctxt->input->consumed) && (q == CUR_PTR) && (attname == NULL) && (attvalue == NULL)) { xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "xmlParseStartTag: problem parsing attributes\n"); break; } GROW; } /* Reconstruct attribute value pointers. */ for (i = 0, j = 0; j < nratts; i += 5, j++) { if (atts[i+2] != NULL) { /* * Arithmetic on dangling pointers is technically undefined * behavior, but well... */ ptrdiff_t offset = ctxt->input->base - atts[i+2]; atts[i+2] = NULL; /* Reset repurposed namespace URI */ atts[i+3] += offset; /* value */ atts[i+4] += offset; /* valuend */ } } /* * The attributes defaulting */ if (ctxt->attsDefault != NULL) { xmlDefAttrsPtr defaults; defaults = xmlHashLookup2(ctxt->attsDefault, localname, prefix); if (defaults != NULL) { for (i = 0;i < defaults->nbAttrs;i++) { attname = defaults->values[5 * i]; aprefix = defaults->values[5 * i + 1]; /* * special work for namespaces defaulted defs */ if ((attname == ctxt->str_xmlns) && (aprefix == NULL)) { /* * check that it's not a defined namespace */ for (j = 1;j <= nbNs;j++) if (ctxt->nsTab[ctxt->nsNr - 2 * j] == NULL) break; if (j <= nbNs) continue; nsname = xmlGetNamespace(ctxt, NULL); if (nsname != defaults->values[5 * i + 2]) { if (nsPush(ctxt, NULL, defaults->values[5 * i + 2]) > 0) nbNs++; } } else if (aprefix == ctxt->str_xmlns) { /* * check that it's not a defined namespace */ for (j = 1;j <= nbNs;j++) if (ctxt->nsTab[ctxt->nsNr - 2 * j] == attname) break; if (j <= nbNs) continue; nsname = xmlGetNamespace(ctxt, attname); if (nsname != defaults->values[2]) { if (nsPush(ctxt, attname, defaults->values[5 * i + 2]) > 0) nbNs++; } } else { /* * check that it's not a defined attribute */ for (j = 0;j < nbatts;j+=5) { if ((attname == atts[j]) && (aprefix == atts[j+1])) break; } if (j < nbatts) continue; if ((atts == NULL) || (nbatts + 5 > maxatts)) { if (xmlCtxtGrowAttrs(ctxt, nbatts + 5) < 0) { return(NULL); } maxatts = ctxt->maxatts; atts = ctxt->atts; } atts[nbatts++] = attname; atts[nbatts++] = aprefix; if (aprefix == NULL) atts[nbatts++] = NULL; else atts[nbatts++] = xmlGetNamespace(ctxt, aprefix); atts[nbatts++] = defaults->values[5 * i + 2]; atts[nbatts++] = defaults->values[5 * i + 3]; if ((ctxt->standalone == 1) && (defaults->values[5 * i + 4] != NULL)) { xmlValidityError(ctxt, XML_DTD_STANDALONE_DEFAULTED, "standalone: attribute %s on %s defaulted from external subset\n", attname, localname); } nbdef++; } } } } /* * The attributes checkings */ for (i = 0; i < nbatts;i += 5) { /* * The default namespace does not apply to attribute names. */ if (atts[i + 1] != NULL) { nsname = xmlGetNamespace(ctxt, atts[i + 1]); if (nsname == NULL) { xmlNsErr(ctxt, XML_NS_ERR_UNDEFINED_NAMESPACE, "Namespace prefix %s for %s on %s is not defined\n", atts[i + 1], atts[i], localname); } atts[i + 2] = nsname; } else nsname = NULL; /* * [ WFC: Unique Att Spec ] * No attribute name may appear more than once in the same * start-tag or empty-element tag. * As extended by the Namespace in XML REC. */ for (j = 0; j < i;j += 5) { if (atts[i] == atts[j]) { if (atts[i+1] == atts[j+1]) { xmlErrAttributeDup(ctxt, atts[i+1], atts[i]); break; } if ((nsname != NULL) && (atts[j + 2] == nsname)) { xmlNsErr(ctxt, XML_NS_ERR_ATTRIBUTE_REDEFINED, "Namespaced Attribute %s in '%s' redefined\n", atts[i], nsname, NULL); break; } } } } nsname = xmlGetNamespace(ctxt, prefix); if ((prefix != NULL) && (nsname == NULL)) { xmlNsErr(ctxt, XML_NS_ERR_UNDEFINED_NAMESPACE, "Namespace prefix %s on %s is not defined\n", prefix, localname, NULL); } *pref = prefix; *URI = nsname; /* * SAX: Start of Element ! */ if ((ctxt->sax != NULL) && (ctxt->sax->startElementNs != NULL) && (!ctxt->disableSAX)) { if (nbNs > 0) ctxt->sax->startElementNs(ctxt->userData, localname, prefix, nsname, nbNs, &ctxt->nsTab[ctxt->nsNr - 2 * nbNs], nbatts / 5, nbdef, atts); else ctxt->sax->startElementNs(ctxt->userData, localname, prefix, nsname, 0, NULL, nbatts / 5, nbdef, atts); } /* * Free up attribute allocated strings if needed */ if (attval != 0) { for (i = 3,j = 0; j < nratts;i += 5,j++) if ((ctxt->attallocs[j] != 0) && (atts[i] != NULL)) xmlFree((xmlChar *) atts[i]); } return(localname); } /** * xmlParseEndTag2: * @ctxt: an XML parser context * @line: line of the start tag * @nsNr: number of namespaces on the start tag * * parse an end of tag * * [42] ETag ::= '</' Name S? '>' * * With namespace * * [NS 9] ETag ::= '</' QName S? '>' */ static void xmlParseEndTag2(xmlParserCtxtPtr ctxt, const xmlChar *prefix, const xmlChar *URI, int line, int nsNr, int tlen) { const xmlChar *name; size_t curLength; GROW; if ((RAW != '<') || (NXT(1) != '/')) { xmlFatalErr(ctxt, XML_ERR_LTSLASH_REQUIRED, NULL); return; } SKIP(2); curLength = ctxt->input->end - ctxt->input->cur; if ((tlen > 0) && (curLength >= (size_t)tlen) && (xmlStrncmp(ctxt->input->cur, ctxt->name, tlen) == 0)) { if ((curLength >= (size_t)(tlen + 1)) && (ctxt->input->cur[tlen] == '>')) { ctxt->input->cur += tlen + 1; ctxt->input->col += tlen + 1; goto done; } ctxt->input->cur += tlen; ctxt->input->col += tlen; name = (xmlChar*)1; } else { if (prefix == NULL) name = xmlParseNameAndCompare(ctxt, ctxt->name); else name = xmlParseQNameAndCompare(ctxt, ctxt->name, prefix); } /* * We should definitely be at the ending "S? '>'" part */ GROW; if (ctxt->instate == XML_PARSER_EOF) return; SKIP_BLANKS; if ((!IS_BYTE_CHAR(RAW)) || (RAW != '>')) { xmlFatalErr(ctxt, XML_ERR_GT_REQUIRED, NULL); } else NEXT1; /* * [ WFC: Element Type Match ] * The Name in an element's end-tag must match the element type in the * start-tag. * */ if (name != (xmlChar*)1) { if (name == NULL) name = BAD_CAST "unparseable"; if ((line == 0) && (ctxt->node != NULL)) line = ctxt->node->line; xmlFatalErrMsgStrIntStr(ctxt, XML_ERR_TAG_NAME_MISMATCH, "Opening and ending tag mismatch: %s line %d and %s\n", ctxt->name, line, name); } /* * SAX: End of Tag */ done: if ((ctxt->sax != NULL) && (ctxt->sax->endElementNs != NULL) && (!ctxt->disableSAX)) ctxt->sax->endElementNs(ctxt->userData, ctxt->name, prefix, URI); spacePop(ctxt); if (nsNr != 0) nsPop(ctxt, nsNr); return; } /** * xmlParseCDSect: * @ctxt: an XML parser context * * Parse escaped pure raw content. * * [18] CDSect ::= CDStart CData CDEnd * * [19] CDStart ::= '<![CDATA[' * * [20] Data ::= (Char* - (Char* ']]>' Char*)) * * [21] CDEnd ::= ']]>' */ void xmlParseCDSect(xmlParserCtxtPtr ctxt) { xmlChar *buf = NULL; int len = 0; int size = XML_PARSER_BUFFER_SIZE; int r, rl; int s, sl; int cur, l; int count = 0; /* Check 2.6.0 was NXT(0) not RAW */ if (CMP9(CUR_PTR, '<', '!', '[', 'C', 'D', 'A', 'T', 'A', '[')) { SKIP(9); } else return; ctxt->instate = XML_PARSER_CDATA_SECTION; r = CUR_CHAR(rl); if (!IS_CHAR(r)) { xmlFatalErr(ctxt, XML_ERR_CDATA_NOT_FINISHED, NULL); ctxt->instate = XML_PARSER_CONTENT; return; } NEXTL(rl); s = CUR_CHAR(sl); if (!IS_CHAR(s)) { xmlFatalErr(ctxt, XML_ERR_CDATA_NOT_FINISHED, NULL); ctxt->instate = XML_PARSER_CONTENT; return; } NEXTL(sl); cur = CUR_CHAR(l); buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar)); if (buf == NULL) { xmlErrMemory(ctxt, NULL); return; } while (IS_CHAR(cur) && ((r != ']') || (s != ']') || (cur != '>'))) { if (len + 5 >= size) { xmlChar *tmp; if ((size > XML_MAX_TEXT_LENGTH) && ((ctxt->options & XML_PARSE_HUGE) == 0)) { xmlFatalErrMsgStr(ctxt, XML_ERR_CDATA_NOT_FINISHED, "CData section too big found", NULL); xmlFree (buf); return; } tmp = (xmlChar *) xmlRealloc(buf, size * 2 * sizeof(xmlChar)); if (tmp == NULL) { xmlFree(buf); xmlErrMemory(ctxt, NULL); return; } buf = tmp; size *= 2; } COPY_BUF(rl,buf,len,r); r = s; rl = sl; s = cur; sl = l; count++; if (count > 50) { GROW; if (ctxt->instate == XML_PARSER_EOF) { xmlFree(buf); return; } count = 0; } NEXTL(l); cur = CUR_CHAR(l); } buf[len] = 0; ctxt->instate = XML_PARSER_CONTENT; if (cur != '>') { xmlFatalErrMsgStr(ctxt, XML_ERR_CDATA_NOT_FINISHED, "CData section not finished\n%.50s\n", buf); xmlFree(buf); return; } NEXTL(l); /* * OK the buffer is to be consumed as cdata. */ if ((ctxt->sax != NULL) && (!ctxt->disableSAX)) { if (ctxt->sax->cdataBlock != NULL) ctxt->sax->cdataBlock(ctxt->userData, buf, len); else if (ctxt->sax->characters != NULL) ctxt->sax->characters(ctxt->userData, buf, len); } xmlFree(buf); } /** * xmlParseContent: * @ctxt: an XML parser context * * Parse a content: * * [43] content ::= (element | CharData | Reference | CDSect | PI | Comment)* */ void xmlParseContent(xmlParserCtxtPtr ctxt) { GROW; while ((RAW != 0) && ((RAW != '<') || (NXT(1) != '/')) && (ctxt->instate != XML_PARSER_EOF)) { const xmlChar *test = CUR_PTR; unsigned int cons = ctxt->input->consumed; const xmlChar *cur = ctxt->input->cur; /* * First case : a Processing Instruction. */ if ((*cur == '<') && (cur[1] == '?')) { xmlParsePI(ctxt); } /* * Second case : a CDSection */ /* 2.6.0 test was *cur not RAW */ else if (CMP9(CUR_PTR, '<', '!', '[', 'C', 'D', 'A', 'T', 'A', '[')) { xmlParseCDSect(ctxt); } /* * Third case : a comment */ else if ((*cur == '<') && (NXT(1) == '!') && (NXT(2) == '-') && (NXT(3) == '-')) { xmlParseComment(ctxt); ctxt->instate = XML_PARSER_CONTENT; } /* * Fourth case : a sub-element. */ else if (*cur == '<') { xmlParseElement(ctxt); } /* * Fifth case : a reference. If if has not been resolved, * parsing returns it's Name, create the node */ else if (*cur == '&') { xmlParseReference(ctxt); } /* * Last case, text. Note that References are handled directly. */ else { xmlParseCharData(ctxt, 0); } GROW; /* * Pop-up of finished entities. */ while ((RAW == 0) && (ctxt->inputNr > 1)) xmlPopInput(ctxt); SHRINK; if ((cons == ctxt->input->consumed) && (test == CUR_PTR)) { xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "detected an error in element content\n"); xmlHaltParser(ctxt); break; } } } /** * xmlParseElement: * @ctxt: an XML parser context * * parse an XML element, this is highly recursive * * [39] element ::= EmptyElemTag | STag content ETag * * [ WFC: Element Type Match ] * The Name in an element's end-tag must match the element type in the * start-tag. * */ void xmlParseElement(xmlParserCtxtPtr ctxt) { const xmlChar *name; const xmlChar *prefix = NULL; const xmlChar *URI = NULL; xmlParserNodeInfo node_info; int line, tlen = 0; xmlNodePtr ret; int nsNr = ctxt->nsNr; if (((unsigned int) ctxt->nameNr > xmlParserMaxDepth) && ((ctxt->options & XML_PARSE_HUGE) == 0)) { xmlFatalErrMsgInt(ctxt, XML_ERR_INTERNAL_ERROR, "Excessive depth in document: %d use XML_PARSE_HUGE option\n", xmlParserMaxDepth); xmlHaltParser(ctxt); return; } /* Capture start position */ if (ctxt->record_info) { node_info.begin_pos = ctxt->input->consumed + (CUR_PTR - ctxt->input->base); node_info.begin_line = ctxt->input->line; } if (ctxt->spaceNr == 0) spacePush(ctxt, -1); else if (*ctxt->space == -2) spacePush(ctxt, -1); else spacePush(ctxt, *ctxt->space); line = ctxt->input->line; #ifdef LIBXML_SAX1_ENABLED if (ctxt->sax2) #endif /* LIBXML_SAX1_ENABLED */ name = xmlParseStartTag2(ctxt, &prefix, &URI, &tlen); #ifdef LIBXML_SAX1_ENABLED else name = xmlParseStartTag(ctxt); #endif /* LIBXML_SAX1_ENABLED */ if (ctxt->instate == XML_PARSER_EOF) return; if (name == NULL) { spacePop(ctxt); return; } namePush(ctxt, name); ret = ctxt->node; #ifdef LIBXML_VALID_ENABLED /* * [ VC: Root Element Type ] * The Name in the document type declaration must match the element * type of the root element. */ if (ctxt->validate && ctxt->wellFormed && ctxt->myDoc && ctxt->node && (ctxt->node == ctxt->myDoc->children)) ctxt->valid &= xmlValidateRoot(&ctxt->vctxt, ctxt->myDoc); #endif /* LIBXML_VALID_ENABLED */ /* * Check for an Empty Element. */ if ((RAW == '/') && (NXT(1) == '>')) { SKIP(2); if (ctxt->sax2) { if ((ctxt->sax != NULL) && (ctxt->sax->endElementNs != NULL) && (!ctxt->disableSAX)) ctxt->sax->endElementNs(ctxt->userData, name, prefix, URI); #ifdef LIBXML_SAX1_ENABLED } else { if ((ctxt->sax != NULL) && (ctxt->sax->endElement != NULL) && (!ctxt->disableSAX)) ctxt->sax->endElement(ctxt->userData, name); #endif /* LIBXML_SAX1_ENABLED */ } namePop(ctxt); spacePop(ctxt); if (nsNr != ctxt->nsNr) nsPop(ctxt, ctxt->nsNr - nsNr); if ( ret != NULL && ctxt->record_info ) { node_info.end_pos = ctxt->input->consumed + (CUR_PTR - ctxt->input->base); node_info.end_line = ctxt->input->line; node_info.node = ret; xmlParserAddNodeInfo(ctxt, &node_info); } return; } if (RAW == '>') { NEXT1; } else { xmlFatalErrMsgStrIntStr(ctxt, XML_ERR_GT_REQUIRED, "Couldn't find end of Start Tag %s line %d\n", name, line, NULL); /* * end of parsing of this node. */ nodePop(ctxt); namePop(ctxt); spacePop(ctxt); if (nsNr != ctxt->nsNr) nsPop(ctxt, ctxt->nsNr - nsNr); /* * Capture end position and add node */ if ( ret != NULL && ctxt->record_info ) { node_info.end_pos = ctxt->input->consumed + (CUR_PTR - ctxt->input->base); node_info.end_line = ctxt->input->line; node_info.node = ret; xmlParserAddNodeInfo(ctxt, &node_info); } return; } /* * Parse the content of the element: */ xmlParseContent(ctxt); if (ctxt->instate == XML_PARSER_EOF) return; if (!IS_BYTE_CHAR(RAW)) { xmlFatalErrMsgStrIntStr(ctxt, XML_ERR_TAG_NOT_FINISHED, "Premature end of data in tag %s line %d\n", name, line, NULL); /* * end of parsing of this node. */ nodePop(ctxt); namePop(ctxt); spacePop(ctxt); if (nsNr != ctxt->nsNr) nsPop(ctxt, ctxt->nsNr - nsNr); return; } /* * parse the end of tag: '</' should be here. */ if (ctxt->sax2) { xmlParseEndTag2(ctxt, prefix, URI, line, ctxt->nsNr - nsNr, tlen); namePop(ctxt); } #ifdef LIBXML_SAX1_ENABLED else xmlParseEndTag1(ctxt, line); #endif /* LIBXML_SAX1_ENABLED */ /* * Capture end position and add node */ if ( ret != NULL && ctxt->record_info ) { node_info.end_pos = ctxt->input->consumed + (CUR_PTR - ctxt->input->base); node_info.end_line = ctxt->input->line; node_info.node = ret; xmlParserAddNodeInfo(ctxt, &node_info); } } /** * xmlParseVersionNum: * @ctxt: an XML parser context * * parse the XML version value. * * [26] VersionNum ::= '1.' [0-9]+ * * In practice allow [0-9].[0-9]+ at that level * * Returns the string giving the XML version number, or NULL */ xmlChar * xmlParseVersionNum(xmlParserCtxtPtr ctxt) { xmlChar *buf = NULL; int len = 0; int size = 10; xmlChar cur; buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar)); if (buf == NULL) { xmlErrMemory(ctxt, NULL); return(NULL); } cur = CUR; if (!((cur >= '0') && (cur <= '9'))) { xmlFree(buf); return(NULL); } buf[len++] = cur; NEXT; cur=CUR; if (cur != '.') { xmlFree(buf); return(NULL); } buf[len++] = cur; NEXT; cur=CUR; while ((cur >= '0') && (cur <= '9')) { if (len + 1 >= size) { xmlChar *tmp; size *= 2; tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar)); if (tmp == NULL) { xmlFree(buf); xmlErrMemory(ctxt, NULL); return(NULL); } buf = tmp; } buf[len++] = cur; NEXT; cur=CUR; } buf[len] = 0; return(buf); } /** * xmlParseVersionInfo: * @ctxt: an XML parser context * * parse the XML version. * * [24] VersionInfo ::= S 'version' Eq (' VersionNum ' | " VersionNum ") * * [25] Eq ::= S? '=' S? * * Returns the version string, e.g. "1.0" */ xmlChar * xmlParseVersionInfo(xmlParserCtxtPtr ctxt) { xmlChar *version = NULL; if (CMP7(CUR_PTR, 'v', 'e', 'r', 's', 'i', 'o', 'n')) { SKIP(7); SKIP_BLANKS; if (RAW != '=') { xmlFatalErr(ctxt, XML_ERR_EQUAL_REQUIRED, NULL); return(NULL); } NEXT; SKIP_BLANKS; if (RAW == '"') { NEXT; version = xmlParseVersionNum(ctxt); if (RAW != '"') { xmlFatalErr(ctxt, XML_ERR_STRING_NOT_CLOSED, NULL); } else NEXT; } else if (RAW == '\''){ NEXT; version = xmlParseVersionNum(ctxt); if (RAW != '\'') { xmlFatalErr(ctxt, XML_ERR_STRING_NOT_CLOSED, NULL); } else NEXT; } else { xmlFatalErr(ctxt, XML_ERR_STRING_NOT_STARTED, NULL); } } return(version); } /** * xmlParseEncName: * @ctxt: an XML parser context * * parse the XML encoding name * * [81] EncName ::= [A-Za-z] ([A-Za-z0-9._] | '-')* * * Returns the encoding name value or NULL */ xmlChar * xmlParseEncName(xmlParserCtxtPtr ctxt) { xmlChar *buf = NULL; int len = 0; int size = 10; xmlChar cur; cur = CUR; if (((cur >= 'a') && (cur <= 'z')) || ((cur >= 'A') && (cur <= 'Z'))) { buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar)); if (buf == NULL) { xmlErrMemory(ctxt, NULL); return(NULL); } buf[len++] = cur; NEXT; cur = CUR; while (((cur >= 'a') && (cur <= 'z')) || ((cur >= 'A') && (cur <= 'Z')) || ((cur >= '0') && (cur <= '9')) || (cur == '.') || (cur == '_') || (cur == '-')) { if (len + 1 >= size) { xmlChar *tmp; size *= 2; tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar)); if (tmp == NULL) { xmlErrMemory(ctxt, NULL); xmlFree(buf); return(NULL); } buf = tmp; } buf[len++] = cur; NEXT; cur = CUR; if (cur == 0) { SHRINK; GROW; cur = CUR; } } buf[len] = 0; } else { xmlFatalErr(ctxt, XML_ERR_ENCODING_NAME, NULL); } return(buf); } /** * xmlParseEncodingDecl: * @ctxt: an XML parser context * * parse the XML encoding declaration * * [80] EncodingDecl ::= S 'encoding' Eq ('"' EncName '"' | "'" EncName "'") * * this setups the conversion filters. * * Returns the encoding value or NULL */ const xmlChar * xmlParseEncodingDecl(xmlParserCtxtPtr ctxt) { xmlChar *encoding = NULL; SKIP_BLANKS; if (CMP8(CUR_PTR, 'e', 'n', 'c', 'o', 'd', 'i', 'n', 'g')) { SKIP(8); SKIP_BLANKS; if (RAW != '=') { xmlFatalErr(ctxt, XML_ERR_EQUAL_REQUIRED, NULL); return(NULL); } NEXT; SKIP_BLANKS; if (RAW == '"') { NEXT; encoding = xmlParseEncName(ctxt); if (RAW != '"') { xmlFatalErr(ctxt, XML_ERR_STRING_NOT_CLOSED, NULL); xmlFree((xmlChar *) encoding); return(NULL); } else NEXT; } else if (RAW == '\''){ NEXT; encoding = xmlParseEncName(ctxt); if (RAW != '\'') { xmlFatalErr(ctxt, XML_ERR_STRING_NOT_CLOSED, NULL); xmlFree((xmlChar *) encoding); return(NULL); } else NEXT; } else { xmlFatalErr(ctxt, XML_ERR_STRING_NOT_STARTED, NULL); } /* * Non standard parsing, allowing the user to ignore encoding */ if (ctxt->options & XML_PARSE_IGNORE_ENC) { xmlFree((xmlChar *) encoding); return(NULL); } /* * UTF-16 encoding stwich has already taken place at this stage, * more over the little-endian/big-endian selection is already done */ if ((encoding != NULL) && ((!xmlStrcasecmp(encoding, BAD_CAST "UTF-16")) || (!xmlStrcasecmp(encoding, BAD_CAST "UTF16")))) { /* * If no encoding was passed to the parser, that we are * using UTF-16 and no decoder is present i.e. the * document is apparently UTF-8 compatible, then raise an * encoding mismatch fatal error */ if ((ctxt->encoding == NULL) && (ctxt->input->buf != NULL) && (ctxt->input->buf->encoder == NULL)) { xmlFatalErrMsg(ctxt, XML_ERR_INVALID_ENCODING, "Document labelled UTF-16 but has UTF-8 content\n"); } if (ctxt->encoding != NULL) xmlFree((xmlChar *) ctxt->encoding); ctxt->encoding = encoding; } /* * UTF-8 encoding is handled natively */ else if ((encoding != NULL) && ((!xmlStrcasecmp(encoding, BAD_CAST "UTF-8")) || (!xmlStrcasecmp(encoding, BAD_CAST "UTF8")))) { if (ctxt->encoding != NULL) xmlFree((xmlChar *) ctxt->encoding); ctxt->encoding = encoding; } else if (encoding != NULL) { xmlCharEncodingHandlerPtr handler; if (ctxt->input->encoding != NULL) xmlFree((xmlChar *) ctxt->input->encoding); ctxt->input->encoding = encoding; handler = xmlFindCharEncodingHandler((const char *) encoding); if (handler != NULL) { if (xmlSwitchToEncoding(ctxt, handler) < 0) { /* failed to convert */ ctxt->errNo = XML_ERR_UNSUPPORTED_ENCODING; return(NULL); } } else { xmlFatalErrMsgStr(ctxt, XML_ERR_UNSUPPORTED_ENCODING, "Unsupported encoding %s\n", encoding); return(NULL); } } } return(encoding); } /** * xmlParseSDDecl: * @ctxt: an XML parser context * * parse the XML standalone declaration * * [32] SDDecl ::= S 'standalone' Eq * (("'" ('yes' | 'no') "'") | ('"' ('yes' | 'no')'"')) * * [ VC: Standalone Document Declaration ] * TODO The standalone document declaration must have the value "no" * if any external markup declarations contain declarations of: * - attributes with default values, if elements to which these * attributes apply appear in the document without specifications * of values for these attributes, or * - entities (other than amp, lt, gt, apos, quot), if references * to those entities appear in the document, or * - attributes with values subject to normalization, where the * attribute appears in the document with a value which will change * as a result of normalization, or * - element types with element content, if white space occurs directly * within any instance of those types. * * Returns: * 1 if standalone="yes" * 0 if standalone="no" * -2 if standalone attribute is missing or invalid * (A standalone value of -2 means that the XML declaration was found, * but no value was specified for the standalone attribute). */ int xmlParseSDDecl(xmlParserCtxtPtr ctxt) { int standalone = -2; SKIP_BLANKS; if (CMP10(CUR_PTR, 's', 't', 'a', 'n', 'd', 'a', 'l', 'o', 'n', 'e')) { SKIP(10); SKIP_BLANKS; if (RAW != '=') { xmlFatalErr(ctxt, XML_ERR_EQUAL_REQUIRED, NULL); return(standalone); } NEXT; SKIP_BLANKS; if (RAW == '\''){ NEXT; if ((RAW == 'n') && (NXT(1) == 'o')) { standalone = 0; SKIP(2); } else if ((RAW == 'y') && (NXT(1) == 'e') && (NXT(2) == 's')) { standalone = 1; SKIP(3); } else { xmlFatalErr(ctxt, XML_ERR_STANDALONE_VALUE, NULL); } if (RAW != '\'') { xmlFatalErr(ctxt, XML_ERR_STRING_NOT_CLOSED, NULL); } else NEXT; } else if (RAW == '"'){ NEXT; if ((RAW == 'n') && (NXT(1) == 'o')) { standalone = 0; SKIP(2); } else if ((RAW == 'y') && (NXT(1) == 'e') && (NXT(2) == 's')) { standalone = 1; SKIP(3); } else { xmlFatalErr(ctxt, XML_ERR_STANDALONE_VALUE, NULL); } if (RAW != '"') { xmlFatalErr(ctxt, XML_ERR_STRING_NOT_CLOSED, NULL); } else NEXT; } else { xmlFatalErr(ctxt, XML_ERR_STRING_NOT_STARTED, NULL); } } return(standalone); } /** * xmlParseXMLDecl: * @ctxt: an XML parser context * * parse an XML declaration header * * [23] XMLDecl ::= '<?xml' VersionInfo EncodingDecl? SDDecl? S? '?>' */ void xmlParseXMLDecl(xmlParserCtxtPtr ctxt) { xmlChar *version; /* * This value for standalone indicates that the document has an * XML declaration but it does not have a standalone attribute. * It will be overwritten later if a standalone attribute is found. */ ctxt->input->standalone = -2; /* * We know that '<?xml' is here. */ SKIP(5); if (!IS_BLANK_CH(RAW)) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "Blank needed after '<?xml'\n"); } SKIP_BLANKS; /* * We must have the VersionInfo here. */ version = xmlParseVersionInfo(ctxt); if (version == NULL) { xmlFatalErr(ctxt, XML_ERR_VERSION_MISSING, NULL); } else { if (!xmlStrEqual(version, (const xmlChar *) XML_DEFAULT_VERSION)) { /* * Changed here for XML-1.0 5th edition */ if (ctxt->options & XML_PARSE_OLD10) { xmlFatalErrMsgStr(ctxt, XML_ERR_UNKNOWN_VERSION, "Unsupported version '%s'\n", version); } else { if ((version[0] == '1') && ((version[1] == '.'))) { xmlWarningMsg(ctxt, XML_WAR_UNKNOWN_VERSION, "Unsupported version '%s'\n", version, NULL); } else { xmlFatalErrMsgStr(ctxt, XML_ERR_UNKNOWN_VERSION, "Unsupported version '%s'\n", version); } } } if (ctxt->version != NULL) xmlFree((void *) ctxt->version); ctxt->version = version; } /* * We may have the encoding declaration */ if (!IS_BLANK_CH(RAW)) { if ((RAW == '?') && (NXT(1) == '>')) { SKIP(2); return; } xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "Blank needed here\n"); } xmlParseEncodingDecl(ctxt); if ((ctxt->errNo == XML_ERR_UNSUPPORTED_ENCODING) || (ctxt->instate == XML_PARSER_EOF)) { /* * The XML REC instructs us to stop parsing right here */ return; } /* * We may have the standalone status. */ if ((ctxt->input->encoding != NULL) && (!IS_BLANK_CH(RAW))) { if ((RAW == '?') && (NXT(1) == '>')) { SKIP(2); return; } xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "Blank needed here\n"); } /* * We can grow the input buffer freely at that point */ GROW; SKIP_BLANKS; ctxt->input->standalone = xmlParseSDDecl(ctxt); SKIP_BLANKS; if ((RAW == '?') && (NXT(1) == '>')) { SKIP(2); } else if (RAW == '>') { /* Deprecated old WD ... */ xmlFatalErr(ctxt, XML_ERR_XMLDECL_NOT_FINISHED, NULL); NEXT; } else { xmlFatalErr(ctxt, XML_ERR_XMLDECL_NOT_FINISHED, NULL); MOVETO_ENDTAG(CUR_PTR); NEXT; } } /** * xmlParseMisc: * @ctxt: an XML parser context * * parse an XML Misc* optional field. * * [27] Misc ::= Comment | PI | S */ void xmlParseMisc(xmlParserCtxtPtr ctxt) { while ((ctxt->instate != XML_PARSER_EOF) && (((RAW == '<') && (NXT(1) == '?')) || (CMP4(CUR_PTR, '<', '!', '-', '-')) || IS_BLANK_CH(CUR))) { if ((RAW == '<') && (NXT(1) == '?')) { xmlParsePI(ctxt); } else if (IS_BLANK_CH(CUR)) { NEXT; } else xmlParseComment(ctxt); } } /** * xmlParseDocument: * @ctxt: an XML parser context * * parse an XML document (and build a tree if using the standard SAX * interface). * * [1] document ::= prolog element Misc* * * [22] prolog ::= XMLDecl? Misc* (doctypedecl Misc*)? * * Returns 0, -1 in case of error. the parser context is augmented * as a result of the parsing. */ int xmlParseDocument(xmlParserCtxtPtr ctxt) { xmlChar start[4]; xmlCharEncoding enc; xmlInitParser(); if ((ctxt == NULL) || (ctxt->input == NULL)) return(-1); GROW; /* * SAX: detecting the level. */ xmlDetectSAX2(ctxt); /* * SAX: beginning of the document processing. */ if ((ctxt->sax) && (ctxt->sax->setDocumentLocator)) ctxt->sax->setDocumentLocator(ctxt->userData, &xmlDefaultSAXLocator); if (ctxt->instate == XML_PARSER_EOF) return(-1); if ((ctxt->encoding == NULL) && ((ctxt->input->end - ctxt->input->cur) >= 4)) { /* * Get the 4 first bytes and decode the charset * if enc != XML_CHAR_ENCODING_NONE * plug some encoding conversion routines. */ start[0] = RAW; start[1] = NXT(1); start[2] = NXT(2); start[3] = NXT(3); enc = xmlDetectCharEncoding(&start[0], 4); if (enc != XML_CHAR_ENCODING_NONE) { xmlSwitchEncoding(ctxt, enc); } } if (CUR == 0) { xmlFatalErr(ctxt, XML_ERR_DOCUMENT_EMPTY, NULL); return(-1); } /* * Check for the XMLDecl in the Prolog. * do not GROW here to avoid the detected encoder to decode more * than just the first line, unless the amount of data is really * too small to hold "<?xml version="1.0" encoding="foo" */ if ((ctxt->input->end - ctxt->input->cur) < 35) { GROW; } if ((CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) && (IS_BLANK_CH(NXT(5)))) { /* * Note that we will switch encoding on the fly. */ xmlParseXMLDecl(ctxt); if ((ctxt->errNo == XML_ERR_UNSUPPORTED_ENCODING) || (ctxt->instate == XML_PARSER_EOF)) { /* * The XML REC instructs us to stop parsing right here */ return(-1); } ctxt->standalone = ctxt->input->standalone; SKIP_BLANKS; } else { ctxt->version = xmlCharStrdup(XML_DEFAULT_VERSION); } if ((ctxt->sax) && (ctxt->sax->startDocument) && (!ctxt->disableSAX)) ctxt->sax->startDocument(ctxt->userData); if (ctxt->instate == XML_PARSER_EOF) return(-1); if ((ctxt->myDoc != NULL) && (ctxt->input != NULL) && (ctxt->input->buf != NULL) && (ctxt->input->buf->compressed >= 0)) { ctxt->myDoc->compression = ctxt->input->buf->compressed; } /* * The Misc part of the Prolog */ GROW; xmlParseMisc(ctxt); /* * Then possibly doc type declaration(s) and more Misc * (doctypedecl Misc*)? */ GROW; if (CMP9(CUR_PTR, '<', '!', 'D', 'O', 'C', 'T', 'Y', 'P', 'E')) { ctxt->inSubset = 1; xmlParseDocTypeDecl(ctxt); if (RAW == '[') { ctxt->instate = XML_PARSER_DTD; xmlParseInternalSubset(ctxt); if (ctxt->instate == XML_PARSER_EOF) return(-1); } /* * Create and update the external subset. */ ctxt->inSubset = 2; if ((ctxt->sax != NULL) && (ctxt->sax->externalSubset != NULL) && (!ctxt->disableSAX)) ctxt->sax->externalSubset(ctxt->userData, ctxt->intSubName, ctxt->extSubSystem, ctxt->extSubURI); if (ctxt->instate == XML_PARSER_EOF) return(-1); ctxt->inSubset = 0; xmlCleanSpecialAttr(ctxt); ctxt->instate = XML_PARSER_PROLOG; xmlParseMisc(ctxt); } /* * Time to start parsing the tree itself */ GROW; if (RAW != '<') { xmlFatalErrMsg(ctxt, XML_ERR_DOCUMENT_EMPTY, "Start tag expected, '<' not found\n"); } else { ctxt->instate = XML_PARSER_CONTENT; xmlParseElement(ctxt); ctxt->instate = XML_PARSER_EPILOG; /* * The Misc part at the end */ xmlParseMisc(ctxt); if (RAW != 0) { xmlFatalErr(ctxt, XML_ERR_DOCUMENT_END, NULL); } ctxt->instate = XML_PARSER_EOF; } /* * SAX: end of the document processing. */ if ((ctxt->sax) && (ctxt->sax->endDocument != NULL)) ctxt->sax->endDocument(ctxt->userData); /* * Remove locally kept entity definitions if the tree was not built */ if ((ctxt->myDoc != NULL) && (xmlStrEqual(ctxt->myDoc->version, SAX_COMPAT_MODE))) { xmlFreeDoc(ctxt->myDoc); ctxt->myDoc = NULL; } if ((ctxt->wellFormed) && (ctxt->myDoc != NULL)) { ctxt->myDoc->properties |= XML_DOC_WELLFORMED; if (ctxt->valid) ctxt->myDoc->properties |= XML_DOC_DTDVALID; if (ctxt->nsWellFormed) ctxt->myDoc->properties |= XML_DOC_NSVALID; if (ctxt->options & XML_PARSE_OLD10) ctxt->myDoc->properties |= XML_DOC_OLD10; } if (! ctxt->wellFormed) { ctxt->valid = 0; return(-1); } return(0); } /** * xmlParseExtParsedEnt: * @ctxt: an XML parser context * * parse a general parsed entity * An external general parsed entity is well-formed if it matches the * production labeled extParsedEnt. * * [78] extParsedEnt ::= TextDecl? content * * Returns 0, -1 in case of error. the parser context is augmented * as a result of the parsing. */ int xmlParseExtParsedEnt(xmlParserCtxtPtr ctxt) { xmlChar start[4]; xmlCharEncoding enc; if ((ctxt == NULL) || (ctxt->input == NULL)) return(-1); xmlDefaultSAXHandlerInit(); xmlDetectSAX2(ctxt); GROW; /* * SAX: beginning of the document processing. */ if ((ctxt->sax) && (ctxt->sax->setDocumentLocator)) ctxt->sax->setDocumentLocator(ctxt->userData, &xmlDefaultSAXLocator); /* * Get the 4 first bytes and decode the charset * if enc != XML_CHAR_ENCODING_NONE * plug some encoding conversion routines. */ if ((ctxt->input->end - ctxt->input->cur) >= 4) { start[0] = RAW; start[1] = NXT(1); start[2] = NXT(2); start[3] = NXT(3); enc = xmlDetectCharEncoding(start, 4); if (enc != XML_CHAR_ENCODING_NONE) { xmlSwitchEncoding(ctxt, enc); } } if (CUR == 0) { xmlFatalErr(ctxt, XML_ERR_DOCUMENT_EMPTY, NULL); } /* * Check for the XMLDecl in the Prolog. */ GROW; if ((CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) && (IS_BLANK_CH(NXT(5)))) { /* * Note that we will switch encoding on the fly. */ xmlParseXMLDecl(ctxt); if (ctxt->errNo == XML_ERR_UNSUPPORTED_ENCODING) { /* * The XML REC instructs us to stop parsing right here */ return(-1); } SKIP_BLANKS; } else { ctxt->version = xmlCharStrdup(XML_DEFAULT_VERSION); } if ((ctxt->sax) && (ctxt->sax->startDocument) && (!ctxt->disableSAX)) ctxt->sax->startDocument(ctxt->userData); if (ctxt->instate == XML_PARSER_EOF) return(-1); /* * Doing validity checking on chunk doesn't make sense */ ctxt->instate = XML_PARSER_CONTENT; ctxt->validate = 0; ctxt->loadsubset = 0; ctxt->depth = 0; xmlParseContent(ctxt); if (ctxt->instate == XML_PARSER_EOF) return(-1); if ((RAW == '<') && (NXT(1) == '/')) { xmlFatalErr(ctxt, XML_ERR_NOT_WELL_BALANCED, NULL); } else if (RAW != 0) { xmlFatalErr(ctxt, XML_ERR_EXTRA_CONTENT, NULL); } /* * SAX: end of the document processing. */ if ((ctxt->sax) && (ctxt->sax->endDocument != NULL)) ctxt->sax->endDocument(ctxt->userData); if (! ctxt->wellFormed) return(-1); return(0); } #ifdef LIBXML_PUSH_ENABLED /************************************************************************ * * * Progressive parsing interfaces * * * ************************************************************************/ /** * xmlParseLookupSequence: * @ctxt: an XML parser context * @first: the first char to lookup * @next: the next char to lookup or zero * @third: the next char to lookup or zero * * Try to find if a sequence (first, next, third) or just (first next) or * (first) is available in the input stream. * This function has a side effect of (possibly) incrementing ctxt->checkIndex * to avoid rescanning sequences of bytes, it DOES change the state of the * parser, do not use liberally. * * Returns the index to the current parsing point if the full sequence * is available, -1 otherwise. */ static int xmlParseLookupSequence(xmlParserCtxtPtr ctxt, xmlChar first, xmlChar next, xmlChar third) { int base, len; xmlParserInputPtr in; const xmlChar *buf; in = ctxt->input; if (in == NULL) return(-1); base = in->cur - in->base; if (base < 0) return(-1); if (ctxt->checkIndex > base) base = ctxt->checkIndex; if (in->buf == NULL) { buf = in->base; len = in->length; } else { buf = xmlBufContent(in->buf->buffer); len = xmlBufUse(in->buf->buffer); } /* take into account the sequence length */ if (third) len -= 2; else if (next) len --; for (;base < len;base++) { if (buf[base] == first) { if (third != 0) { if ((buf[base + 1] != next) || (buf[base + 2] != third)) continue; } else if (next != 0) { if (buf[base + 1] != next) continue; } ctxt->checkIndex = 0; #ifdef DEBUG_PUSH if (next == 0) xmlGenericError(xmlGenericErrorContext, "PP: lookup '%c' found at %d\n", first, base); else if (third == 0) xmlGenericError(xmlGenericErrorContext, "PP: lookup '%c%c' found at %d\n", first, next, base); else xmlGenericError(xmlGenericErrorContext, "PP: lookup '%c%c%c' found at %d\n", first, next, third, base); #endif return(base - (in->cur - in->base)); } } ctxt->checkIndex = base; #ifdef DEBUG_PUSH if (next == 0) xmlGenericError(xmlGenericErrorContext, "PP: lookup '%c' failed\n", first); else if (third == 0) xmlGenericError(xmlGenericErrorContext, "PP: lookup '%c%c' failed\n", first, next); else xmlGenericError(xmlGenericErrorContext, "PP: lookup '%c%c%c' failed\n", first, next, third); #endif return(-1); } /** * xmlParseGetLasts: * @ctxt: an XML parser context * @lastlt: pointer to store the last '<' from the input * @lastgt: pointer to store the last '>' from the input * * Lookup the last < and > in the current chunk */ static void xmlParseGetLasts(xmlParserCtxtPtr ctxt, const xmlChar **lastlt, const xmlChar **lastgt) { const xmlChar *tmp; if ((ctxt == NULL) || (lastlt == NULL) || (lastgt == NULL)) { xmlGenericError(xmlGenericErrorContext, "Internal error: xmlParseGetLasts\n"); return; } if ((ctxt->progressive != 0) && (ctxt->inputNr == 1)) { tmp = ctxt->input->end; tmp--; while ((tmp >= ctxt->input->base) && (*tmp != '<')) tmp--; if (tmp < ctxt->input->base) { *lastlt = NULL; *lastgt = NULL; } else { *lastlt = tmp; tmp++; while ((tmp < ctxt->input->end) && (*tmp != '>')) { if (*tmp == '\'') { tmp++; while ((tmp < ctxt->input->end) && (*tmp != '\'')) tmp++; if (tmp < ctxt->input->end) tmp++; } else if (*tmp == '"') { tmp++; while ((tmp < ctxt->input->end) && (*tmp != '"')) tmp++; if (tmp < ctxt->input->end) tmp++; } else tmp++; } if (tmp < ctxt->input->end) *lastgt = tmp; else { tmp = *lastlt; tmp--; while ((tmp >= ctxt->input->base) && (*tmp != '>')) tmp--; if (tmp >= ctxt->input->base) *lastgt = tmp; else *lastgt = NULL; } } } else { *lastlt = NULL; *lastgt = NULL; } } /** * xmlCheckCdataPush: * @cur: pointer to the block of characters * @len: length of the block in bytes * @complete: 1 if complete CDATA block is passed in, 0 if partial block * * Check that the block of characters is okay as SCdata content [20] * * Returns the number of bytes to pass if okay, a negative index where an * UTF-8 error occured otherwise */ static int xmlCheckCdataPush(const xmlChar *utf, int len, int complete) { int ix; unsigned char c; int codepoint; if ((utf == NULL) || (len <= 0)) return(0); for (ix = 0; ix < len;) { /* string is 0-terminated */ c = utf[ix]; if ((c & 0x80) == 0x00) { /* 1-byte code, starts with 10 */ if (c >= 0x20) ix++; else if ((c == 0xA) || (c == 0xD) || (c == 0x9)) ix++; else return(-ix); } else if ((c & 0xe0) == 0xc0) {/* 2-byte code, starts with 110 */ if (ix + 2 > len) return(complete ? -ix : ix); if ((utf[ix+1] & 0xc0 ) != 0x80) return(-ix); codepoint = (utf[ix] & 0x1f) << 6; codepoint |= utf[ix+1] & 0x3f; if (!xmlIsCharQ(codepoint)) return(-ix); ix += 2; } else if ((c & 0xf0) == 0xe0) {/* 3-byte code, starts with 1110 */ if (ix + 3 > len) return(complete ? -ix : ix); if (((utf[ix+1] & 0xc0) != 0x80) || ((utf[ix+2] & 0xc0) != 0x80)) return(-ix); codepoint = (utf[ix] & 0xf) << 12; codepoint |= (utf[ix+1] & 0x3f) << 6; codepoint |= utf[ix+2] & 0x3f; if (!xmlIsCharQ(codepoint)) return(-ix); ix += 3; } else if ((c & 0xf8) == 0xf0) {/* 4-byte code, starts with 11110 */ if (ix + 4 > len) return(complete ? -ix : ix); if (((utf[ix+1] & 0xc0) != 0x80) || ((utf[ix+2] & 0xc0) != 0x80) || ((utf[ix+3] & 0xc0) != 0x80)) return(-ix); codepoint = (utf[ix] & 0x7) << 18; codepoint |= (utf[ix+1] & 0x3f) << 12; codepoint |= (utf[ix+2] & 0x3f) << 6; codepoint |= utf[ix+3] & 0x3f; if (!xmlIsCharQ(codepoint)) return(-ix); ix += 4; } else /* unknown encoding */ return(-ix); } return(ix); } /** * xmlParseTryOrFinish: * @ctxt: an XML parser context * @terminate: last chunk indicator * * Try to progress on parsing * * Returns zero if no parsing was possible */ static int xmlParseTryOrFinish(xmlParserCtxtPtr ctxt, int terminate) { int ret = 0; int avail, tlen; xmlChar cur, next; const xmlChar *lastlt, *lastgt; if (ctxt->input == NULL) return(0); #ifdef DEBUG_PUSH switch (ctxt->instate) { case XML_PARSER_EOF: xmlGenericError(xmlGenericErrorContext, "PP: try EOF\n"); break; case XML_PARSER_START: xmlGenericError(xmlGenericErrorContext, "PP: try START\n"); break; case XML_PARSER_MISC: xmlGenericError(xmlGenericErrorContext, "PP: try MISC\n");break; case XML_PARSER_COMMENT: xmlGenericError(xmlGenericErrorContext, "PP: try COMMENT\n");break; case XML_PARSER_PROLOG: xmlGenericError(xmlGenericErrorContext, "PP: try PROLOG\n");break; case XML_PARSER_START_TAG: xmlGenericError(xmlGenericErrorContext, "PP: try START_TAG\n");break; case XML_PARSER_CONTENT: xmlGenericError(xmlGenericErrorContext, "PP: try CONTENT\n");break; case XML_PARSER_CDATA_SECTION: xmlGenericError(xmlGenericErrorContext, "PP: try CDATA_SECTION\n");break; case XML_PARSER_END_TAG: xmlGenericError(xmlGenericErrorContext, "PP: try END_TAG\n");break; case XML_PARSER_ENTITY_DECL: xmlGenericError(xmlGenericErrorContext, "PP: try ENTITY_DECL\n");break; case XML_PARSER_ENTITY_VALUE: xmlGenericError(xmlGenericErrorContext, "PP: try ENTITY_VALUE\n");break; case XML_PARSER_ATTRIBUTE_VALUE: xmlGenericError(xmlGenericErrorContext, "PP: try ATTRIBUTE_VALUE\n");break; case XML_PARSER_DTD: xmlGenericError(xmlGenericErrorContext, "PP: try DTD\n");break; case XML_PARSER_EPILOG: xmlGenericError(xmlGenericErrorContext, "PP: try EPILOG\n");break; case XML_PARSER_PI: xmlGenericError(xmlGenericErrorContext, "PP: try PI\n");break; case XML_PARSER_IGNORE: xmlGenericError(xmlGenericErrorContext, "PP: try IGNORE\n");break; } #endif if ((ctxt->input != NULL) && (ctxt->input->cur - ctxt->input->base > 4096)) { xmlSHRINK(ctxt); ctxt->checkIndex = 0; } xmlParseGetLasts(ctxt, &lastlt, &lastgt); while (ctxt->instate != XML_PARSER_EOF) { if ((ctxt->errNo != XML_ERR_OK) && (ctxt->disableSAX == 1)) return(0); /* * Pop-up of finished entities. */ while ((RAW == 0) && (ctxt->inputNr > 1)) xmlPopInput(ctxt); if (ctxt->input == NULL) break; if (ctxt->input->buf == NULL) avail = ctxt->input->length - (ctxt->input->cur - ctxt->input->base); else { /* * If we are operating on converted input, try to flush * remainng chars to avoid them stalling in the non-converted * buffer. But do not do this in document start where * encoding="..." may not have been read and we work on a * guessed encoding. */ if ((ctxt->instate != XML_PARSER_START) && (ctxt->input->buf->raw != NULL) && (xmlBufIsEmpty(ctxt->input->buf->raw) == 0)) { size_t base = xmlBufGetInputBase(ctxt->input->buf->buffer, ctxt->input); size_t current = ctxt->input->cur - ctxt->input->base; xmlParserInputBufferPush(ctxt->input->buf, 0, ""); xmlBufSetInputBaseCur(ctxt->input->buf->buffer, ctxt->input, base, current); } avail = xmlBufUse(ctxt->input->buf->buffer) - (ctxt->input->cur - ctxt->input->base); } if (avail < 1) goto done; switch (ctxt->instate) { case XML_PARSER_EOF: /* * Document parsing is done ! */ goto done; case XML_PARSER_START: if (ctxt->charset == XML_CHAR_ENCODING_NONE) { xmlChar start[4]; xmlCharEncoding enc; /* * Very first chars read from the document flow. */ if (avail < 4) goto done; /* * Get the 4 first bytes and decode the charset * if enc != XML_CHAR_ENCODING_NONE * plug some encoding conversion routines, * else xmlSwitchEncoding will set to (default) * UTF8. */ start[0] = RAW; start[1] = NXT(1); start[2] = NXT(2); start[3] = NXT(3); enc = xmlDetectCharEncoding(start, 4); xmlSwitchEncoding(ctxt, enc); break; } if (avail < 2) goto done; cur = ctxt->input->cur[0]; next = ctxt->input->cur[1]; if (cur == 0) { if ((ctxt->sax) && (ctxt->sax->setDocumentLocator)) ctxt->sax->setDocumentLocator(ctxt->userData, &xmlDefaultSAXLocator); xmlFatalErr(ctxt, XML_ERR_DOCUMENT_EMPTY, NULL); xmlHaltParser(ctxt); #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering EOF\n"); #endif if ((ctxt->sax) && (ctxt->sax->endDocument != NULL)) ctxt->sax->endDocument(ctxt->userData); goto done; } if ((cur == '<') && (next == '?')) { /* PI or XML decl */ if (avail < 5) return(ret); if ((!terminate) && (xmlParseLookupSequence(ctxt, '?', '>', 0) < 0)) return(ret); if ((ctxt->sax) && (ctxt->sax->setDocumentLocator)) ctxt->sax->setDocumentLocator(ctxt->userData, &xmlDefaultSAXLocator); if ((ctxt->input->cur[2] == 'x') && (ctxt->input->cur[3] == 'm') && (ctxt->input->cur[4] == 'l') && (IS_BLANK_CH(ctxt->input->cur[5]))) { ret += 5; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: Parsing XML Decl\n"); #endif xmlParseXMLDecl(ctxt); if (ctxt->errNo == XML_ERR_UNSUPPORTED_ENCODING) { /* * The XML REC instructs us to stop parsing right * here */ xmlHaltParser(ctxt); return(0); } ctxt->standalone = ctxt->input->standalone; if ((ctxt->encoding == NULL) && (ctxt->input->encoding != NULL)) ctxt->encoding = xmlStrdup(ctxt->input->encoding); if ((ctxt->sax) && (ctxt->sax->startDocument) && (!ctxt->disableSAX)) ctxt->sax->startDocument(ctxt->userData); ctxt->instate = XML_PARSER_MISC; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering MISC\n"); #endif } else { ctxt->version = xmlCharStrdup(XML_DEFAULT_VERSION); if ((ctxt->sax) && (ctxt->sax->startDocument) && (!ctxt->disableSAX)) ctxt->sax->startDocument(ctxt->userData); ctxt->instate = XML_PARSER_MISC; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering MISC\n"); #endif } } else { if ((ctxt->sax) && (ctxt->sax->setDocumentLocator)) ctxt->sax->setDocumentLocator(ctxt->userData, &xmlDefaultSAXLocator); ctxt->version = xmlCharStrdup(XML_DEFAULT_VERSION); if (ctxt->version == NULL) { xmlErrMemory(ctxt, NULL); break; } if ((ctxt->sax) && (ctxt->sax->startDocument) && (!ctxt->disableSAX)) ctxt->sax->startDocument(ctxt->userData); ctxt->instate = XML_PARSER_MISC; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering MISC\n"); #endif } break; case XML_PARSER_START_TAG: { const xmlChar *name; const xmlChar *prefix = NULL; const xmlChar *URI = NULL; int nsNr = ctxt->nsNr; if ((avail < 2) && (ctxt->inputNr == 1)) goto done; cur = ctxt->input->cur[0]; if (cur != '<') { xmlFatalErr(ctxt, XML_ERR_DOCUMENT_EMPTY, NULL); xmlHaltParser(ctxt); if ((ctxt->sax) && (ctxt->sax->endDocument != NULL)) ctxt->sax->endDocument(ctxt->userData); goto done; } if (!terminate) { if (ctxt->progressive) { /* > can be found unescaped in attribute values */ if ((lastgt == NULL) || (ctxt->input->cur >= lastgt)) goto done; } else if (xmlParseLookupSequence(ctxt, '>', 0, 0) < 0) { goto done; } } if (ctxt->spaceNr == 0) spacePush(ctxt, -1); else if (*ctxt->space == -2) spacePush(ctxt, -1); else spacePush(ctxt, *ctxt->space); #ifdef LIBXML_SAX1_ENABLED if (ctxt->sax2) #endif /* LIBXML_SAX1_ENABLED */ name = xmlParseStartTag2(ctxt, &prefix, &URI, &tlen); #ifdef LIBXML_SAX1_ENABLED else name = xmlParseStartTag(ctxt); #endif /* LIBXML_SAX1_ENABLED */ if (ctxt->instate == XML_PARSER_EOF) goto done; if (name == NULL) { spacePop(ctxt); xmlHaltParser(ctxt); if ((ctxt->sax) && (ctxt->sax->endDocument != NULL)) ctxt->sax->endDocument(ctxt->userData); goto done; } #ifdef LIBXML_VALID_ENABLED /* * [ VC: Root Element Type ] * The Name in the document type declaration must match * the element type of the root element. */ if (ctxt->validate && ctxt->wellFormed && ctxt->myDoc && ctxt->node && (ctxt->node == ctxt->myDoc->children)) ctxt->valid &= xmlValidateRoot(&ctxt->vctxt, ctxt->myDoc); #endif /* LIBXML_VALID_ENABLED */ /* * Check for an Empty Element. */ if ((RAW == '/') && (NXT(1) == '>')) { SKIP(2); if (ctxt->sax2) { if ((ctxt->sax != NULL) && (ctxt->sax->endElementNs != NULL) && (!ctxt->disableSAX)) ctxt->sax->endElementNs(ctxt->userData, name, prefix, URI); if (ctxt->nsNr - nsNr > 0) nsPop(ctxt, ctxt->nsNr - nsNr); #ifdef LIBXML_SAX1_ENABLED } else { if ((ctxt->sax != NULL) && (ctxt->sax->endElement != NULL) && (!ctxt->disableSAX)) ctxt->sax->endElement(ctxt->userData, name); #endif /* LIBXML_SAX1_ENABLED */ } if (ctxt->instate == XML_PARSER_EOF) goto done; spacePop(ctxt); if (ctxt->nameNr == 0) { ctxt->instate = XML_PARSER_EPILOG; } else { ctxt->instate = XML_PARSER_CONTENT; } ctxt->progressive = 1; break; } if (RAW == '>') { NEXT; } else { xmlFatalErrMsgStr(ctxt, XML_ERR_GT_REQUIRED, "Couldn't find end of Start Tag %s\n", name); nodePop(ctxt); spacePop(ctxt); } if (ctxt->sax2) nameNsPush(ctxt, name, prefix, URI, ctxt->nsNr - nsNr); #ifdef LIBXML_SAX1_ENABLED else namePush(ctxt, name); #endif /* LIBXML_SAX1_ENABLED */ ctxt->instate = XML_PARSER_CONTENT; ctxt->progressive = 1; break; } case XML_PARSER_CONTENT: { const xmlChar *test; unsigned int cons; if ((avail < 2) && (ctxt->inputNr == 1)) goto done; cur = ctxt->input->cur[0]; next = ctxt->input->cur[1]; test = CUR_PTR; cons = ctxt->input->consumed; if ((cur == '<') && (next == '/')) { ctxt->instate = XML_PARSER_END_TAG; break; } else if ((cur == '<') && (next == '?')) { if ((!terminate) && (xmlParseLookupSequence(ctxt, '?', '>', 0) < 0)) { ctxt->progressive = XML_PARSER_PI; goto done; } xmlParsePI(ctxt); ctxt->instate = XML_PARSER_CONTENT; ctxt->progressive = 1; } else if ((cur == '<') && (next != '!')) { ctxt->instate = XML_PARSER_START_TAG; break; } else if ((cur == '<') && (next == '!') && (ctxt->input->cur[2] == '-') && (ctxt->input->cur[3] == '-')) { int term; if (avail < 4) goto done; ctxt->input->cur += 4; term = xmlParseLookupSequence(ctxt, '-', '-', '>'); ctxt->input->cur -= 4; if ((!terminate) && (term < 0)) { ctxt->progressive = XML_PARSER_COMMENT; goto done; } xmlParseComment(ctxt); ctxt->instate = XML_PARSER_CONTENT; ctxt->progressive = 1; } else if ((cur == '<') && (ctxt->input->cur[1] == '!') && (ctxt->input->cur[2] == '[') && (ctxt->input->cur[3] == 'C') && (ctxt->input->cur[4] == 'D') && (ctxt->input->cur[5] == 'A') && (ctxt->input->cur[6] == 'T') && (ctxt->input->cur[7] == 'A') && (ctxt->input->cur[8] == '[')) { SKIP(9); ctxt->instate = XML_PARSER_CDATA_SECTION; break; } else if ((cur == '<') && (next == '!') && (avail < 9)) { goto done; } else if (cur == '&') { if ((!terminate) && (xmlParseLookupSequence(ctxt, ';', 0, 0) < 0)) goto done; xmlParseReference(ctxt); } else { /* TODO Avoid the extra copy, handle directly !!! */ /* * Goal of the following test is: * - minimize calls to the SAX 'character' callback * when they are mergeable * - handle an problem for isBlank when we only parse * a sequence of blank chars and the next one is * not available to check against '<' presence. * - tries to homogenize the differences in SAX * callbacks between the push and pull versions * of the parser. */ if ((ctxt->inputNr == 1) && (avail < XML_PARSER_BIG_BUFFER_SIZE)) { if (!terminate) { if (ctxt->progressive) { if ((lastlt == NULL) || (ctxt->input->cur > lastlt)) goto done; } else if (xmlParseLookupSequence(ctxt, '<', 0, 0) < 0) { goto done; } } } ctxt->checkIndex = 0; xmlParseCharData(ctxt, 0); } /* * Pop-up of finished entities. */ while ((RAW == 0) && (ctxt->inputNr > 1)) xmlPopInput(ctxt); if ((cons == ctxt->input->consumed) && (test == CUR_PTR)) { xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "detected an error in element content\n"); xmlHaltParser(ctxt); break; } break; } case XML_PARSER_END_TAG: if (avail < 2) goto done; if (!terminate) { if (ctxt->progressive) { /* > can be found unescaped in attribute values */ if ((lastgt == NULL) || (ctxt->input->cur >= lastgt)) goto done; } else if (xmlParseLookupSequence(ctxt, '>', 0, 0) < 0) { goto done; } } if (ctxt->sax2) { xmlParseEndTag2(ctxt, (void *) ctxt->pushTab[ctxt->nameNr * 3 - 3], (void *) ctxt->pushTab[ctxt->nameNr * 3 - 2], 0, (int) (long) ctxt->pushTab[ctxt->nameNr * 3 - 1], 0); nameNsPop(ctxt); } #ifdef LIBXML_SAX1_ENABLED else xmlParseEndTag1(ctxt, 0); #endif /* LIBXML_SAX1_ENABLED */ if (ctxt->instate == XML_PARSER_EOF) { /* Nothing */ } else if (ctxt->nameNr == 0) { ctxt->instate = XML_PARSER_EPILOG; } else { ctxt->instate = XML_PARSER_CONTENT; } break; case XML_PARSER_CDATA_SECTION: { /* * The Push mode need to have the SAX callback for * cdataBlock merge back contiguous callbacks. */ int base; base = xmlParseLookupSequence(ctxt, ']', ']', '>'); if (base < 0) { if (avail >= XML_PARSER_BIG_BUFFER_SIZE + 2) { int tmp; tmp = xmlCheckCdataPush(ctxt->input->cur, XML_PARSER_BIG_BUFFER_SIZE, 0); if (tmp < 0) { tmp = -tmp; ctxt->input->cur += tmp; goto encoding_error; } if ((ctxt->sax != NULL) && (!ctxt->disableSAX)) { if (ctxt->sax->cdataBlock != NULL) ctxt->sax->cdataBlock(ctxt->userData, ctxt->input->cur, tmp); else if (ctxt->sax->characters != NULL) ctxt->sax->characters(ctxt->userData, ctxt->input->cur, tmp); } if (ctxt->instate == XML_PARSER_EOF) goto done; SKIPL(tmp); ctxt->checkIndex = 0; } goto done; } else { int tmp; tmp = xmlCheckCdataPush(ctxt->input->cur, base, 1); if ((tmp < 0) || (tmp != base)) { tmp = -tmp; ctxt->input->cur += tmp; goto encoding_error; } if ((ctxt->sax != NULL) && (base == 0) && (ctxt->sax->cdataBlock != NULL) && (!ctxt->disableSAX)) { /* * Special case to provide identical behaviour * between pull and push parsers on enpty CDATA * sections */ if ((ctxt->input->cur - ctxt->input->base >= 9) && (!strncmp((const char *)&ctxt->input->cur[-9], "<![CDATA[", 9))) ctxt->sax->cdataBlock(ctxt->userData, BAD_CAST "", 0); } else if ((ctxt->sax != NULL) && (base > 0) && (!ctxt->disableSAX)) { if (ctxt->sax->cdataBlock != NULL) ctxt->sax->cdataBlock(ctxt->userData, ctxt->input->cur, base); else if (ctxt->sax->characters != NULL) ctxt->sax->characters(ctxt->userData, ctxt->input->cur, base); } if (ctxt->instate == XML_PARSER_EOF) goto done; SKIPL(base + 3); ctxt->checkIndex = 0; ctxt->instate = XML_PARSER_CONTENT; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering CONTENT\n"); #endif } break; } case XML_PARSER_MISC: SKIP_BLANKS; if (ctxt->input->buf == NULL) avail = ctxt->input->length - (ctxt->input->cur - ctxt->input->base); else avail = xmlBufUse(ctxt->input->buf->buffer) - (ctxt->input->cur - ctxt->input->base); if (avail < 2) goto done; cur = ctxt->input->cur[0]; next = ctxt->input->cur[1]; if ((cur == '<') && (next == '?')) { if ((!terminate) && (xmlParseLookupSequence(ctxt, '?', '>', 0) < 0)) { ctxt->progressive = XML_PARSER_PI; goto done; } #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: Parsing PI\n"); #endif xmlParsePI(ctxt); if (ctxt->instate == XML_PARSER_EOF) goto done; ctxt->instate = XML_PARSER_MISC; ctxt->progressive = 1; ctxt->checkIndex = 0; } else if ((cur == '<') && (next == '!') && (ctxt->input->cur[2] == '-') && (ctxt->input->cur[3] == '-')) { if ((!terminate) && (xmlParseLookupSequence(ctxt, '-', '-', '>') < 0)) { ctxt->progressive = XML_PARSER_COMMENT; goto done; } #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: Parsing Comment\n"); #endif xmlParseComment(ctxt); if (ctxt->instate == XML_PARSER_EOF) goto done; ctxt->instate = XML_PARSER_MISC; ctxt->progressive = 1; ctxt->checkIndex = 0; } else if ((cur == '<') && (next == '!') && (ctxt->input->cur[2] == 'D') && (ctxt->input->cur[3] == 'O') && (ctxt->input->cur[4] == 'C') && (ctxt->input->cur[5] == 'T') && (ctxt->input->cur[6] == 'Y') && (ctxt->input->cur[7] == 'P') && (ctxt->input->cur[8] == 'E')) { if ((!terminate) && (xmlParseLookupSequence(ctxt, '>', 0, 0) < 0)) { ctxt->progressive = XML_PARSER_DTD; goto done; } #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: Parsing internal subset\n"); #endif ctxt->inSubset = 1; ctxt->progressive = 0; ctxt->checkIndex = 0; xmlParseDocTypeDecl(ctxt); if (ctxt->instate == XML_PARSER_EOF) goto done; if (RAW == '[') { ctxt->instate = XML_PARSER_DTD; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering DTD\n"); #endif } else { /* * Create and update the external subset. */ ctxt->inSubset = 2; if ((ctxt->sax != NULL) && (!ctxt->disableSAX) && (ctxt->sax->externalSubset != NULL)) ctxt->sax->externalSubset(ctxt->userData, ctxt->intSubName, ctxt->extSubSystem, ctxt->extSubURI); ctxt->inSubset = 0; xmlCleanSpecialAttr(ctxt); ctxt->instate = XML_PARSER_PROLOG; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering PROLOG\n"); #endif } } else if ((cur == '<') && (next == '!') && (avail < 9)) { goto done; } else { ctxt->instate = XML_PARSER_START_TAG; ctxt->progressive = XML_PARSER_START_TAG; xmlParseGetLasts(ctxt, &lastlt, &lastgt); #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering START_TAG\n"); #endif } break; case XML_PARSER_PROLOG: SKIP_BLANKS; if (ctxt->input->buf == NULL) avail = ctxt->input->length - (ctxt->input->cur - ctxt->input->base); else avail = xmlBufUse(ctxt->input->buf->buffer) - (ctxt->input->cur - ctxt->input->base); if (avail < 2) goto done; cur = ctxt->input->cur[0]; next = ctxt->input->cur[1]; if ((cur == '<') && (next == '?')) { if ((!terminate) && (xmlParseLookupSequence(ctxt, '?', '>', 0) < 0)) { ctxt->progressive = XML_PARSER_PI; goto done; } #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: Parsing PI\n"); #endif xmlParsePI(ctxt); if (ctxt->instate == XML_PARSER_EOF) goto done; ctxt->instate = XML_PARSER_PROLOG; ctxt->progressive = 1; } else if ((cur == '<') && (next == '!') && (ctxt->input->cur[2] == '-') && (ctxt->input->cur[3] == '-')) { if ((!terminate) && (xmlParseLookupSequence(ctxt, '-', '-', '>') < 0)) { ctxt->progressive = XML_PARSER_COMMENT; goto done; } #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: Parsing Comment\n"); #endif xmlParseComment(ctxt); if (ctxt->instate == XML_PARSER_EOF) goto done; ctxt->instate = XML_PARSER_PROLOG; ctxt->progressive = 1; } else if ((cur == '<') && (next == '!') && (avail < 4)) { goto done; } else { ctxt->instate = XML_PARSER_START_TAG; if (ctxt->progressive == 0) ctxt->progressive = XML_PARSER_START_TAG; xmlParseGetLasts(ctxt, &lastlt, &lastgt); #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering START_TAG\n"); #endif } break; case XML_PARSER_EPILOG: SKIP_BLANKS; if (ctxt->input->buf == NULL) avail = ctxt->input->length - (ctxt->input->cur - ctxt->input->base); else avail = xmlBufUse(ctxt->input->buf->buffer) - (ctxt->input->cur - ctxt->input->base); if (avail < 2) goto done; cur = ctxt->input->cur[0]; next = ctxt->input->cur[1]; if ((cur == '<') && (next == '?')) { if ((!terminate) && (xmlParseLookupSequence(ctxt, '?', '>', 0) < 0)) { ctxt->progressive = XML_PARSER_PI; goto done; } #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: Parsing PI\n"); #endif xmlParsePI(ctxt); if (ctxt->instate == XML_PARSER_EOF) goto done; ctxt->instate = XML_PARSER_EPILOG; ctxt->progressive = 1; } else if ((cur == '<') && (next == '!') && (ctxt->input->cur[2] == '-') && (ctxt->input->cur[3] == '-')) { if ((!terminate) && (xmlParseLookupSequence(ctxt, '-', '-', '>') < 0)) { ctxt->progressive = XML_PARSER_COMMENT; goto done; } #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: Parsing Comment\n"); #endif xmlParseComment(ctxt); if (ctxt->instate == XML_PARSER_EOF) goto done; ctxt->instate = XML_PARSER_EPILOG; ctxt->progressive = 1; } else if ((cur == '<') && (next == '!') && (avail < 4)) { goto done; } else { xmlFatalErr(ctxt, XML_ERR_DOCUMENT_END, NULL); xmlHaltParser(ctxt); #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering EOF\n"); #endif if ((ctxt->sax) && (ctxt->sax->endDocument != NULL)) ctxt->sax->endDocument(ctxt->userData); goto done; } break; case XML_PARSER_DTD: { /* * Sorry but progressive parsing of the internal subset * is not expected to be supported. We first check that * the full content of the internal subset is available and * the parsing is launched only at that point. * Internal subset ends up with "']' S? '>'" in an unescaped * section and not in a ']]>' sequence which are conditional * sections (whoever argued to keep that crap in XML deserve * a place in hell !). */ int base, i; xmlChar *buf; xmlChar quote = 0; size_t use; base = ctxt->input->cur - ctxt->input->base; if (base < 0) return(0); if (ctxt->checkIndex > base) base = ctxt->checkIndex; buf = xmlBufContent(ctxt->input->buf->buffer); use = xmlBufUse(ctxt->input->buf->buffer); for (;(unsigned int) base < use; base++) { if (quote != 0) { if (buf[base] == quote) quote = 0; continue; } if ((quote == 0) && (buf[base] == '<')) { int found = 0; /* special handling of comments */ if (((unsigned int) base + 4 < use) && (buf[base + 1] == '!') && (buf[base + 2] == '-') && (buf[base + 3] == '-')) { for (;(unsigned int) base + 3 < use; base++) { if ((buf[base] == '-') && (buf[base + 1] == '-') && (buf[base + 2] == '>')) { found = 1; base += 2; break; } } if (!found) { #if 0 fprintf(stderr, "unfinished comment\n"); #endif break; /* for */ } continue; } } if (buf[base] == '"') { quote = '"'; continue; } if (buf[base] == '\'') { quote = '\''; continue; } if (buf[base] == ']') { #if 0 fprintf(stderr, "%c%c%c%c: ", buf[base], buf[base + 1], buf[base + 2], buf[base + 3]); #endif if ((unsigned int) base +1 >= use) break; if (buf[base + 1] == ']') { /* conditional crap, skip both ']' ! */ base++; continue; } for (i = 1; (unsigned int) base + i < use; i++) { if (buf[base + i] == '>') { #if 0 fprintf(stderr, "found\n"); #endif goto found_end_int_subset; } if (!IS_BLANK_CH(buf[base + i])) { #if 0 fprintf(stderr, "not found\n"); #endif goto not_end_of_int_subset; } } #if 0 fprintf(stderr, "end of stream\n"); #endif break; } not_end_of_int_subset: continue; /* for */ } /* * We didn't found the end of the Internal subset */ if (quote == 0) ctxt->checkIndex = base; else ctxt->checkIndex = 0; #ifdef DEBUG_PUSH if (next == 0) xmlGenericError(xmlGenericErrorContext, "PP: lookup of int subset end filed\n"); #endif goto done; found_end_int_subset: ctxt->checkIndex = 0; xmlParseInternalSubset(ctxt); if (ctxt->instate == XML_PARSER_EOF) goto done; ctxt->inSubset = 2; if ((ctxt->sax != NULL) && (!ctxt->disableSAX) && (ctxt->sax->externalSubset != NULL)) ctxt->sax->externalSubset(ctxt->userData, ctxt->intSubName, ctxt->extSubSystem, ctxt->extSubURI); ctxt->inSubset = 0; xmlCleanSpecialAttr(ctxt); if (ctxt->instate == XML_PARSER_EOF) goto done; ctxt->instate = XML_PARSER_PROLOG; ctxt->checkIndex = 0; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering PROLOG\n"); #endif break; } case XML_PARSER_COMMENT: xmlGenericError(xmlGenericErrorContext, "PP: internal error, state == COMMENT\n"); ctxt->instate = XML_PARSER_CONTENT; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering CONTENT\n"); #endif break; case XML_PARSER_IGNORE: xmlGenericError(xmlGenericErrorContext, "PP: internal error, state == IGNORE"); ctxt->instate = XML_PARSER_DTD; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering DTD\n"); #endif break; case XML_PARSER_PI: xmlGenericError(xmlGenericErrorContext, "PP: internal error, state == PI\n"); ctxt->instate = XML_PARSER_CONTENT; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering CONTENT\n"); #endif break; case XML_PARSER_ENTITY_DECL: xmlGenericError(xmlGenericErrorContext, "PP: internal error, state == ENTITY_DECL\n"); ctxt->instate = XML_PARSER_DTD; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering DTD\n"); #endif break; case XML_PARSER_ENTITY_VALUE: xmlGenericError(xmlGenericErrorContext, "PP: internal error, state == ENTITY_VALUE\n"); ctxt->instate = XML_PARSER_CONTENT; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering DTD\n"); #endif break; case XML_PARSER_ATTRIBUTE_VALUE: xmlGenericError(xmlGenericErrorContext, "PP: internal error, state == ATTRIBUTE_VALUE\n"); ctxt->instate = XML_PARSER_START_TAG; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering START_TAG\n"); #endif break; case XML_PARSER_SYSTEM_LITERAL: xmlGenericError(xmlGenericErrorContext, "PP: internal error, state == SYSTEM_LITERAL\n"); ctxt->instate = XML_PARSER_START_TAG; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering START_TAG\n"); #endif break; case XML_PARSER_PUBLIC_LITERAL: xmlGenericError(xmlGenericErrorContext, "PP: internal error, state == PUBLIC_LITERAL\n"); ctxt->instate = XML_PARSER_START_TAG; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering START_TAG\n"); #endif break; } } done: #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: done %d\n", ret); #endif return(ret); encoding_error: { char buffer[150]; snprintf(buffer, 149, "Bytes: 0x%02X 0x%02X 0x%02X 0x%02X\n", ctxt->input->cur[0], ctxt->input->cur[1], ctxt->input->cur[2], ctxt->input->cur[3]); __xmlErrEncoding(ctxt, XML_ERR_INVALID_CHAR, "Input is not proper UTF-8, indicate encoding !\n%s", BAD_CAST buffer, NULL); } return(0); } /** * xmlParseCheckTransition: * @ctxt: an XML parser context * @chunk: a char array * @size: the size in byte of the chunk * * Check depending on the current parser state if the chunk given must be * processed immediately or one need more data to advance on parsing. * * Returns -1 in case of error, 0 if the push is not needed and 1 if needed */ static int xmlParseCheckTransition(xmlParserCtxtPtr ctxt, const char *chunk, int size) { if ((ctxt == NULL) || (chunk == NULL) || (size < 0)) return(-1); if (ctxt->instate == XML_PARSER_START_TAG) { if (memchr(chunk, '>', size) != NULL) return(1); return(0); } if (ctxt->progressive == XML_PARSER_COMMENT) { if (memchr(chunk, '>', size) != NULL) return(1); return(0); } if (ctxt->instate == XML_PARSER_CDATA_SECTION) { if (memchr(chunk, '>', size) != NULL) return(1); return(0); } if (ctxt->progressive == XML_PARSER_PI) { if (memchr(chunk, '>', size) != NULL) return(1); return(0); } if (ctxt->instate == XML_PARSER_END_TAG) { if (memchr(chunk, '>', size) != NULL) return(1); return(0); } if ((ctxt->progressive == XML_PARSER_DTD) || (ctxt->instate == XML_PARSER_DTD)) { if (memchr(chunk, '>', size) != NULL) return(1); return(0); } return(1); } /** * xmlParseChunk: * @ctxt: an XML parser context * @chunk: an char array * @size: the size in byte of the chunk * @terminate: last chunk indicator * * Parse a Chunk of memory * * Returns zero if no error, the xmlParserErrors otherwise. */ int xmlParseChunk(xmlParserCtxtPtr ctxt, const char *chunk, int size, int terminate) { int end_in_lf = 0; int remain = 0; size_t old_avail = 0; size_t avail = 0; if (ctxt == NULL) return(XML_ERR_INTERNAL_ERROR); if ((ctxt->errNo != XML_ERR_OK) && (ctxt->disableSAX == 1)) return(ctxt->errNo); if (ctxt->instate == XML_PARSER_EOF) return(-1); if (ctxt->instate == XML_PARSER_START) xmlDetectSAX2(ctxt); if ((size > 0) && (chunk != NULL) && (!terminate) && (chunk[size - 1] == '\r')) { end_in_lf = 1; size--; } xmldecl_done: if ((size > 0) && (chunk != NULL) && (ctxt->input != NULL) && (ctxt->input->buf != NULL) && (ctxt->instate != XML_PARSER_EOF)) { size_t base = xmlBufGetInputBase(ctxt->input->buf->buffer, ctxt->input); size_t cur = ctxt->input->cur - ctxt->input->base; int res; old_avail = xmlBufUse(ctxt->input->buf->buffer); /* * Specific handling if we autodetected an encoding, we should not * push more than the first line ... which depend on the encoding * And only push the rest once the final encoding was detected */ if ((ctxt->instate == XML_PARSER_START) && (ctxt->input != NULL) && (ctxt->input->buf != NULL) && (ctxt->input->buf->encoder != NULL)) { unsigned int len = 45; if ((xmlStrcasestr(BAD_CAST ctxt->input->buf->encoder->name, BAD_CAST "UTF-16")) || (xmlStrcasestr(BAD_CAST ctxt->input->buf->encoder->name, BAD_CAST "UTF16"))) len = 90; else if ((xmlStrcasestr(BAD_CAST ctxt->input->buf->encoder->name, BAD_CAST "UCS-4")) || (xmlStrcasestr(BAD_CAST ctxt->input->buf->encoder->name, BAD_CAST "UCS4"))) len = 180; if (ctxt->input->buf->rawconsumed < len) len -= ctxt->input->buf->rawconsumed; /* * Change size for reading the initial declaration only * if size is greater than len. Otherwise, memmove in xmlBufferAdd * will blindly copy extra bytes from memory. */ if ((unsigned int) size > len) { remain = size - len; size = len; } else { remain = 0; } } res = xmlParserInputBufferPush(ctxt->input->buf, size, chunk); if (res < 0) { ctxt->errNo = XML_PARSER_EOF; xmlHaltParser(ctxt); return (XML_PARSER_EOF); } xmlBufSetInputBaseCur(ctxt->input->buf->buffer, ctxt->input, base, cur); #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: pushed %d\n", size); #endif } else if (ctxt->instate != XML_PARSER_EOF) { if ((ctxt->input != NULL) && ctxt->input->buf != NULL) { xmlParserInputBufferPtr in = ctxt->input->buf; if ((in->encoder != NULL) && (in->buffer != NULL) && (in->raw != NULL)) { int nbchars; size_t base = xmlBufGetInputBase(in->buffer, ctxt->input); size_t current = ctxt->input->cur - ctxt->input->base; nbchars = xmlCharEncInput(in, terminate); if (nbchars < 0) { /* TODO 2.6.0 */ xmlGenericError(xmlGenericErrorContext, "xmlParseChunk: encoder error\n"); return(XML_ERR_INVALID_ENCODING); } xmlBufSetInputBaseCur(in->buffer, ctxt->input, base, current); } } } if (remain != 0) { xmlParseTryOrFinish(ctxt, 0); } else { if ((ctxt->input != NULL) && (ctxt->input->buf != NULL)) avail = xmlBufUse(ctxt->input->buf->buffer); /* * Depending on the current state it may not be such * a good idea to try parsing if there is nothing in the chunk * which would be worth doing a parser state transition and we * need to wait for more data */ if ((terminate) || (avail > XML_MAX_TEXT_LENGTH) || (old_avail == 0) || (avail == 0) || (xmlParseCheckTransition(ctxt, (const char *)&ctxt->input->base[old_avail], avail - old_avail))) xmlParseTryOrFinish(ctxt, terminate); } if (ctxt->instate == XML_PARSER_EOF) return(ctxt->errNo); if ((ctxt->input != NULL) && (((ctxt->input->end - ctxt->input->cur) > XML_MAX_LOOKUP_LIMIT) || ((ctxt->input->cur - ctxt->input->base) > XML_MAX_LOOKUP_LIMIT)) && ((ctxt->options & XML_PARSE_HUGE) == 0)) { xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "Huge input lookup"); xmlHaltParser(ctxt); } if ((ctxt->errNo != XML_ERR_OK) && (ctxt->disableSAX == 1)) return(ctxt->errNo); if (remain != 0) { chunk += size; size = remain; remain = 0; goto xmldecl_done; } if ((end_in_lf == 1) && (ctxt->input != NULL) && (ctxt->input->buf != NULL)) { size_t base = xmlBufGetInputBase(ctxt->input->buf->buffer, ctxt->input); size_t current = ctxt->input->cur - ctxt->input->base; xmlParserInputBufferPush(ctxt->input->buf, 1, "\r"); xmlBufSetInputBaseCur(ctxt->input->buf->buffer, ctxt->input, base, current); } if (terminate) { /* * Check for termination */ int cur_avail = 0; if (ctxt->input != NULL) { if (ctxt->input->buf == NULL) cur_avail = ctxt->input->length - (ctxt->input->cur - ctxt->input->base); else cur_avail = xmlBufUse(ctxt->input->buf->buffer) - (ctxt->input->cur - ctxt->input->base); } if ((ctxt->instate != XML_PARSER_EOF) && (ctxt->instate != XML_PARSER_EPILOG)) { xmlFatalErr(ctxt, XML_ERR_DOCUMENT_END, NULL); } if ((ctxt->instate == XML_PARSER_EPILOG) && (cur_avail > 0)) { xmlFatalErr(ctxt, XML_ERR_DOCUMENT_END, NULL); } if (ctxt->instate != XML_PARSER_EOF) { if ((ctxt->sax) && (ctxt->sax->endDocument != NULL)) ctxt->sax->endDocument(ctxt->userData); } ctxt->instate = XML_PARSER_EOF; } if (ctxt->wellFormed == 0) return((xmlParserErrors) ctxt->errNo); else return(0); } /************************************************************************ * * * I/O front end functions to the parser * * * ************************************************************************/ /** * xmlCreatePushParserCtxt: * @sax: a SAX handler * @user_data: The user data returned on SAX callbacks * @chunk: a pointer to an array of chars * @size: number of chars in the array * @filename: an optional file name or URI * * Create a parser context for using the XML parser in push mode. * If @buffer and @size are non-NULL, the data is used to detect * the encoding. The remaining characters will be parsed so they * don't need to be fed in again through xmlParseChunk. * To allow content encoding detection, @size should be >= 4 * The value of @filename is used for fetching external entities * and error/warning reports. * * Returns the new parser context or NULL */ xmlParserCtxtPtr xmlCreatePushParserCtxt(xmlSAXHandlerPtr sax, void *user_data, const char *chunk, int size, const char *filename) { xmlParserCtxtPtr ctxt; xmlParserInputPtr inputStream; xmlParserInputBufferPtr buf; xmlCharEncoding enc = XML_CHAR_ENCODING_NONE; /* * plug some encoding conversion routines */ if ((chunk != NULL) && (size >= 4)) enc = xmlDetectCharEncoding((const xmlChar *) chunk, size); buf = xmlAllocParserInputBuffer(enc); if (buf == NULL) return(NULL); ctxt = xmlNewParserCtxt(); if (ctxt == NULL) { xmlErrMemory(NULL, "creating parser: out of memory\n"); xmlFreeParserInputBuffer(buf); return(NULL); } ctxt->dictNames = 1; ctxt->pushTab = (void **) xmlMalloc(ctxt->nameMax * 3 * sizeof(xmlChar *)); if (ctxt->pushTab == NULL) { xmlErrMemory(ctxt, NULL); xmlFreeParserInputBuffer(buf); xmlFreeParserCtxt(ctxt); return(NULL); } if (sax != NULL) { #ifdef LIBXML_SAX1_ENABLED if (ctxt->sax != (xmlSAXHandlerPtr) &xmlDefaultSAXHandler) #endif /* LIBXML_SAX1_ENABLED */ xmlFree(ctxt->sax); ctxt->sax = (xmlSAXHandlerPtr) xmlMalloc(sizeof(xmlSAXHandler)); if (ctxt->sax == NULL) { xmlErrMemory(ctxt, NULL); xmlFreeParserInputBuffer(buf); xmlFreeParserCtxt(ctxt); return(NULL); } memset(ctxt->sax, 0, sizeof(xmlSAXHandler)); if (sax->initialized == XML_SAX2_MAGIC) memcpy(ctxt->sax, sax, sizeof(xmlSAXHandler)); else memcpy(ctxt->sax, sax, sizeof(xmlSAXHandlerV1)); if (user_data != NULL) ctxt->userData = user_data; } if (filename == NULL) { ctxt->directory = NULL; } else { ctxt->directory = xmlParserGetDirectory(filename); } inputStream = xmlNewInputStream(ctxt); if (inputStream == NULL) { xmlFreeParserCtxt(ctxt); xmlFreeParserInputBuffer(buf); return(NULL); } if (filename == NULL) inputStream->filename = NULL; else { inputStream->filename = (char *) xmlCanonicPath((const xmlChar *) filename); if (inputStream->filename == NULL) { xmlFreeParserCtxt(ctxt); xmlFreeParserInputBuffer(buf); return(NULL); } } inputStream->buf = buf; xmlBufResetInput(inputStream->buf->buffer, inputStream); inputPush(ctxt, inputStream); /* * If the caller didn't provide an initial 'chunk' for determining * the encoding, we set the context to XML_CHAR_ENCODING_NONE so * that it can be automatically determined later */ if ((size == 0) || (chunk == NULL)) { ctxt->charset = XML_CHAR_ENCODING_NONE; } else if ((ctxt->input != NULL) && (ctxt->input->buf != NULL)) { size_t base = xmlBufGetInputBase(ctxt->input->buf->buffer, ctxt->input); size_t cur = ctxt->input->cur - ctxt->input->base; xmlParserInputBufferPush(ctxt->input->buf, size, chunk); xmlBufSetInputBaseCur(ctxt->input->buf->buffer, ctxt->input, base, cur); #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: pushed %d\n", size); #endif } if (enc != XML_CHAR_ENCODING_NONE) { xmlSwitchEncoding(ctxt, enc); } return(ctxt); } #endif /* LIBXML_PUSH_ENABLED */ /** * xmlHaltParser: * @ctxt: an XML parser context * * Blocks further parser processing don't override error * for internal use */ static void xmlHaltParser(xmlParserCtxtPtr ctxt) { if (ctxt == NULL) return; ctxt->instate = XML_PARSER_EOF; ctxt->disableSAX = 1; if (ctxt->input != NULL) { /* * in case there was a specific allocation deallocate before * overriding base */ if (ctxt->input->free != NULL) { ctxt->input->free((xmlChar *) ctxt->input->base); ctxt->input->free = NULL; } ctxt->input->cur = BAD_CAST""; ctxt->input->base = ctxt->input->cur; } } /** * xmlStopParser: * @ctxt: an XML parser context * * Blocks further parser processing */ void xmlStopParser(xmlParserCtxtPtr ctxt) { if (ctxt == NULL) return; xmlHaltParser(ctxt); ctxt->errNo = XML_ERR_USER_STOP; } /** * xmlCreateIOParserCtxt: * @sax: a SAX handler * @user_data: The user data returned on SAX callbacks * @ioread: an I/O read function * @ioclose: an I/O close function * @ioctx: an I/O handler * @enc: the charset encoding if known * * Create a parser context for using the XML parser with an existing * I/O stream * * Returns the new parser context or NULL */ xmlParserCtxtPtr xmlCreateIOParserCtxt(xmlSAXHandlerPtr sax, void *user_data, xmlInputReadCallback ioread, xmlInputCloseCallback ioclose, void *ioctx, xmlCharEncoding enc) { xmlParserCtxtPtr ctxt; xmlParserInputPtr inputStream; xmlParserInputBufferPtr buf; if (ioread == NULL) return(NULL); buf = xmlParserInputBufferCreateIO(ioread, ioclose, ioctx, enc); if (buf == NULL) { if (ioclose != NULL) ioclose(ioctx); return (NULL); } ctxt = xmlNewParserCtxt(); if (ctxt == NULL) { xmlFreeParserInputBuffer(buf); return(NULL); } if (sax != NULL) { #ifdef LIBXML_SAX1_ENABLED if (ctxt->sax != (xmlSAXHandlerPtr) &xmlDefaultSAXHandler) #endif /* LIBXML_SAX1_ENABLED */ xmlFree(ctxt->sax); ctxt->sax = (xmlSAXHandlerPtr) xmlMalloc(sizeof(xmlSAXHandler)); if (ctxt->sax == NULL) { xmlErrMemory(ctxt, NULL); xmlFreeParserCtxt(ctxt); return(NULL); } memset(ctxt->sax, 0, sizeof(xmlSAXHandler)); if (sax->initialized == XML_SAX2_MAGIC) memcpy(ctxt->sax, sax, sizeof(xmlSAXHandler)); else memcpy(ctxt->sax, sax, sizeof(xmlSAXHandlerV1)); if (user_data != NULL) ctxt->userData = user_data; } inputStream = xmlNewIOInputStream(ctxt, buf, enc); if (inputStream == NULL) { xmlFreeParserCtxt(ctxt); return(NULL); } inputPush(ctxt, inputStream); return(ctxt); } #ifdef LIBXML_VALID_ENABLED /************************************************************************ * * * Front ends when parsing a DTD * * * ************************************************************************/ /** * xmlIOParseDTD: * @sax: the SAX handler block or NULL * @input: an Input Buffer * @enc: the charset encoding if known * * Load and parse a DTD * * Returns the resulting xmlDtdPtr or NULL in case of error. * @input will be freed by the function in any case. */ xmlDtdPtr xmlIOParseDTD(xmlSAXHandlerPtr sax, xmlParserInputBufferPtr input, xmlCharEncoding enc) { xmlDtdPtr ret = NULL; xmlParserCtxtPtr ctxt; xmlParserInputPtr pinput = NULL; xmlChar start[4]; if (input == NULL) return(NULL); ctxt = xmlNewParserCtxt(); if (ctxt == NULL) { xmlFreeParserInputBuffer(input); return(NULL); } /* We are loading a DTD */ ctxt->options |= XML_PARSE_DTDLOAD; /* * Set-up the SAX context */ if (sax != NULL) { if (ctxt->sax != NULL) xmlFree(ctxt->sax); ctxt->sax = sax; ctxt->userData = ctxt; } xmlDetectSAX2(ctxt); /* * generate a parser input from the I/O handler */ pinput = xmlNewIOInputStream(ctxt, input, XML_CHAR_ENCODING_NONE); if (pinput == NULL) { if (sax != NULL) ctxt->sax = NULL; xmlFreeParserInputBuffer(input); xmlFreeParserCtxt(ctxt); return(NULL); } /* * plug some encoding conversion routines here. */ if (xmlPushInput(ctxt, pinput) < 0) { if (sax != NULL) ctxt->sax = NULL; xmlFreeParserCtxt(ctxt); return(NULL); } if (enc != XML_CHAR_ENCODING_NONE) { xmlSwitchEncoding(ctxt, enc); } pinput->filename = NULL; pinput->line = 1; pinput->col = 1; pinput->base = ctxt->input->cur; pinput->cur = ctxt->input->cur; pinput->free = NULL; /* * let's parse that entity knowing it's an external subset. */ ctxt->inSubset = 2; ctxt->myDoc = xmlNewDoc(BAD_CAST "1.0"); if (ctxt->myDoc == NULL) { xmlErrMemory(ctxt, "New Doc failed"); return(NULL); } ctxt->myDoc->properties = XML_DOC_INTERNAL; ctxt->myDoc->extSubset = xmlNewDtd(ctxt->myDoc, BAD_CAST "none", BAD_CAST "none", BAD_CAST "none"); if ((enc == XML_CHAR_ENCODING_NONE) && ((ctxt->input->end - ctxt->input->cur) >= 4)) { /* * Get the 4 first bytes and decode the charset * if enc != XML_CHAR_ENCODING_NONE * plug some encoding conversion routines. */ start[0] = RAW; start[1] = NXT(1); start[2] = NXT(2); start[3] = NXT(3); enc = xmlDetectCharEncoding(start, 4); if (enc != XML_CHAR_ENCODING_NONE) { xmlSwitchEncoding(ctxt, enc); } } xmlParseExternalSubset(ctxt, BAD_CAST "none", BAD_CAST "none"); if (ctxt->myDoc != NULL) { if (ctxt->wellFormed) { ret = ctxt->myDoc->extSubset; ctxt->myDoc->extSubset = NULL; if (ret != NULL) { xmlNodePtr tmp; ret->doc = NULL; tmp = ret->children; while (tmp != NULL) { tmp->doc = NULL; tmp = tmp->next; } } } else { ret = NULL; } xmlFreeDoc(ctxt->myDoc); ctxt->myDoc = NULL; } if (sax != NULL) ctxt->sax = NULL; xmlFreeParserCtxt(ctxt); return(ret); } /** * xmlSAXParseDTD: * @sax: the SAX handler block * @ExternalID: a NAME* containing the External ID of the DTD * @SystemID: a NAME* containing the URL to the DTD * * Load and parse an external subset. * * Returns the resulting xmlDtdPtr or NULL in case of error. */ xmlDtdPtr xmlSAXParseDTD(xmlSAXHandlerPtr sax, const xmlChar *ExternalID, const xmlChar *SystemID) { xmlDtdPtr ret = NULL; xmlParserCtxtPtr ctxt; xmlParserInputPtr input = NULL; xmlCharEncoding enc; xmlChar* systemIdCanonic; if ((ExternalID == NULL) && (SystemID == NULL)) return(NULL); ctxt = xmlNewParserCtxt(); if (ctxt == NULL) { return(NULL); } /* We are loading a DTD */ ctxt->options |= XML_PARSE_DTDLOAD; /* * Set-up the SAX context */ if (sax != NULL) { if (ctxt->sax != NULL) xmlFree(ctxt->sax); ctxt->sax = sax; ctxt->userData = ctxt; } /* * Canonicalise the system ID */ systemIdCanonic = xmlCanonicPath(SystemID); if ((SystemID != NULL) && (systemIdCanonic == NULL)) { xmlFreeParserCtxt(ctxt); return(NULL); } /* * Ask the Entity resolver to load the damn thing */ if ((ctxt->sax != NULL) && (ctxt->sax->resolveEntity != NULL)) input = ctxt->sax->resolveEntity(ctxt->userData, ExternalID, systemIdCanonic); if (input == NULL) { if (sax != NULL) ctxt->sax = NULL; xmlFreeParserCtxt(ctxt); if (systemIdCanonic != NULL) xmlFree(systemIdCanonic); return(NULL); } /* * plug some encoding conversion routines here. */ if (xmlPushInput(ctxt, input) < 0) { if (sax != NULL) ctxt->sax = NULL; xmlFreeParserCtxt(ctxt); if (systemIdCanonic != NULL) xmlFree(systemIdCanonic); return(NULL); } if ((ctxt->input->end - ctxt->input->cur) >= 4) { enc = xmlDetectCharEncoding(ctxt->input->cur, 4); xmlSwitchEncoding(ctxt, enc); } if (input->filename == NULL) input->filename = (char *) systemIdCanonic; else xmlFree(systemIdCanonic); input->line = 1; input->col = 1; input->base = ctxt->input->cur; input->cur = ctxt->input->cur; input->free = NULL; /* * let's parse that entity knowing it's an external subset. */ ctxt->inSubset = 2; ctxt->myDoc = xmlNewDoc(BAD_CAST "1.0"); if (ctxt->myDoc == NULL) { xmlErrMemory(ctxt, "New Doc failed"); if (sax != NULL) ctxt->sax = NULL; xmlFreeParserCtxt(ctxt); return(NULL); } ctxt->myDoc->properties = XML_DOC_INTERNAL; ctxt->myDoc->extSubset = xmlNewDtd(ctxt->myDoc, BAD_CAST "none", ExternalID, SystemID); xmlParseExternalSubset(ctxt, ExternalID, SystemID); if (ctxt->myDoc != NULL) { if (ctxt->wellFormed) { ret = ctxt->myDoc->extSubset; ctxt->myDoc->extSubset = NULL; if (ret != NULL) { xmlNodePtr tmp; ret->doc = NULL; tmp = ret->children; while (tmp != NULL) { tmp->doc = NULL; tmp = tmp->next; } } } else { ret = NULL; } xmlFreeDoc(ctxt->myDoc); ctxt->myDoc = NULL; } if (sax != NULL) ctxt->sax = NULL; xmlFreeParserCtxt(ctxt); return(ret); } /** * xmlParseDTD: * @ExternalID: a NAME* containing the External ID of the DTD * @SystemID: a NAME* containing the URL to the DTD * * Load and parse an external subset. * * Returns the resulting xmlDtdPtr or NULL in case of error. */ xmlDtdPtr xmlParseDTD(const xmlChar *ExternalID, const xmlChar *SystemID) { return(xmlSAXParseDTD(NULL, ExternalID, SystemID)); } #endif /* LIBXML_VALID_ENABLED */ /************************************************************************ * * * Front ends when parsing an Entity * * * ************************************************************************/ /** * xmlParseCtxtExternalEntity: * @ctx: the existing parsing context * @URL: the URL for the entity to load * @ID: the System ID for the entity to load * @lst: the return value for the set of parsed nodes * * Parse an external general entity within an existing parsing context * An external general parsed entity is well-formed if it matches the * production labeled extParsedEnt. * * [78] extParsedEnt ::= TextDecl? content * * Returns 0 if the entity is well formed, -1 in case of args problem and * the parser error code otherwise */ int xmlParseCtxtExternalEntity(xmlParserCtxtPtr ctx, const xmlChar *URL, const xmlChar *ID, xmlNodePtr *lst) { xmlParserCtxtPtr ctxt; xmlDocPtr newDoc; xmlNodePtr newRoot; xmlSAXHandlerPtr oldsax = NULL; int ret = 0; xmlChar start[4]; xmlCharEncoding enc; if (ctx == NULL) return(-1); if (((ctx->depth > 40) && ((ctx->options & XML_PARSE_HUGE) == 0)) || (ctx->depth > 1024)) { return(XML_ERR_ENTITY_LOOP); } if (lst != NULL) *lst = NULL; if ((URL == NULL) && (ID == NULL)) return(-1); if (ctx->myDoc == NULL) /* @@ relax but check for dereferences */ return(-1); ctxt = xmlCreateEntityParserCtxtInternal(URL, ID, NULL, ctx); if (ctxt == NULL) { return(-1); } oldsax = ctxt->sax; ctxt->sax = ctx->sax; xmlDetectSAX2(ctxt); newDoc = xmlNewDoc(BAD_CAST "1.0"); if (newDoc == NULL) { xmlFreeParserCtxt(ctxt); return(-1); } newDoc->properties = XML_DOC_INTERNAL; if (ctx->myDoc->dict) { newDoc->dict = ctx->myDoc->dict; xmlDictReference(newDoc->dict); } if (ctx->myDoc != NULL) { newDoc->intSubset = ctx->myDoc->intSubset; newDoc->extSubset = ctx->myDoc->extSubset; } if (ctx->myDoc->URL != NULL) { newDoc->URL = xmlStrdup(ctx->myDoc->URL); } newRoot = xmlNewDocNode(newDoc, NULL, BAD_CAST "pseudoroot", NULL); if (newRoot == NULL) { ctxt->sax = oldsax; xmlFreeParserCtxt(ctxt); newDoc->intSubset = NULL; newDoc->extSubset = NULL; xmlFreeDoc(newDoc); return(-1); } xmlAddChild((xmlNodePtr) newDoc, newRoot); nodePush(ctxt, newDoc->children); if (ctx->myDoc == NULL) { ctxt->myDoc = newDoc; } else { ctxt->myDoc = ctx->myDoc; newDoc->children->doc = ctx->myDoc; } /* * Get the 4 first bytes and decode the charset * if enc != XML_CHAR_ENCODING_NONE * plug some encoding conversion routines. */ GROW if ((ctxt->input->end - ctxt->input->cur) >= 4) { start[0] = RAW; start[1] = NXT(1); start[2] = NXT(2); start[3] = NXT(3); enc = xmlDetectCharEncoding(start, 4); if (enc != XML_CHAR_ENCODING_NONE) { xmlSwitchEncoding(ctxt, enc); } } /* * Parse a possible text declaration first */ if ((CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) && (IS_BLANK_CH(NXT(5)))) { xmlParseTextDecl(ctxt); /* * An XML-1.0 document can't reference an entity not XML-1.0 */ if ((xmlStrEqual(ctx->version, BAD_CAST "1.0")) && (!xmlStrEqual(ctxt->input->version, BAD_CAST "1.0"))) { xmlFatalErrMsg(ctxt, XML_ERR_VERSION_MISMATCH, "Version mismatch between document and entity\n"); } } /* * If the user provided its own SAX callbacks then reuse the * useData callback field, otherwise the expected setup in a * DOM builder is to have userData == ctxt */ if (ctx->userData == ctx) ctxt->userData = ctxt; else ctxt->userData = ctx->userData; /* * Doing validity checking on chunk doesn't make sense */ ctxt->instate = XML_PARSER_CONTENT; ctxt->validate = ctx->validate; ctxt->valid = ctx->valid; ctxt->loadsubset = ctx->loadsubset; ctxt->depth = ctx->depth + 1; ctxt->replaceEntities = ctx->replaceEntities; if (ctxt->validate) { ctxt->vctxt.error = ctx->vctxt.error; ctxt->vctxt.warning = ctx->vctxt.warning; } else { ctxt->vctxt.error = NULL; ctxt->vctxt.warning = NULL; } ctxt->vctxt.nodeTab = NULL; ctxt->vctxt.nodeNr = 0; ctxt->vctxt.nodeMax = 0; ctxt->vctxt.node = NULL; if (ctxt->dict != NULL) xmlDictFree(ctxt->dict); ctxt->dict = ctx->dict; ctxt->str_xml = xmlDictLookup(ctxt->dict, BAD_CAST "xml", 3); ctxt->str_xmlns = xmlDictLookup(ctxt->dict, BAD_CAST "xmlns", 5); ctxt->str_xml_ns = xmlDictLookup(ctxt->dict, XML_XML_NAMESPACE, 36); ctxt->dictNames = ctx->dictNames; ctxt->attsDefault = ctx->attsDefault; ctxt->attsSpecial = ctx->attsSpecial; ctxt->linenumbers = ctx->linenumbers; xmlParseContent(ctxt); ctx->validate = ctxt->validate; ctx->valid = ctxt->valid; if ((RAW == '<') && (NXT(1) == '/')) { xmlFatalErr(ctxt, XML_ERR_NOT_WELL_BALANCED, NULL); } else if (RAW != 0) { xmlFatalErr(ctxt, XML_ERR_EXTRA_CONTENT, NULL); } if (ctxt->node != newDoc->children) { xmlFatalErr(ctxt, XML_ERR_NOT_WELL_BALANCED, NULL); } if (!ctxt->wellFormed) { if (ctxt->errNo == 0) ret = 1; else ret = ctxt->errNo; } else { if (lst != NULL) { xmlNodePtr cur; /* * Return the newly created nodeset after unlinking it from * they pseudo parent. */ cur = newDoc->children->children; *lst = cur; while (cur != NULL) { cur->parent = NULL; cur = cur->next; } newDoc->children->children = NULL; } ret = 0; } ctxt->sax = oldsax; ctxt->dict = NULL; ctxt->attsDefault = NULL; ctxt->attsSpecial = NULL; xmlFreeParserCtxt(ctxt); newDoc->intSubset = NULL; newDoc->extSubset = NULL; xmlFreeDoc(newDoc); return(ret); } /** * xmlParseExternalEntityPrivate: * @doc: the document the chunk pertains to * @oldctxt: the previous parser context if available * @sax: the SAX handler bloc (possibly NULL) * @user_data: The user data returned on SAX callbacks (possibly NULL) * @depth: Used for loop detection, use 0 * @URL: the URL for the entity to load * @ID: the System ID for the entity to load * @list: the return value for the set of parsed nodes * * Private version of xmlParseExternalEntity() * * Returns 0 if the entity is well formed, -1 in case of args problem and * the parser error code otherwise */ static xmlParserErrors xmlParseExternalEntityPrivate(xmlDocPtr doc, xmlParserCtxtPtr oldctxt, xmlSAXHandlerPtr sax, void *user_data, int depth, const xmlChar *URL, const xmlChar *ID, xmlNodePtr *list) { xmlParserCtxtPtr ctxt; xmlDocPtr newDoc; xmlNodePtr newRoot; xmlSAXHandlerPtr oldsax = NULL; xmlParserErrors ret = XML_ERR_OK; xmlChar start[4]; xmlCharEncoding enc; if (((depth > 40) && ((oldctxt == NULL) || (oldctxt->options & XML_PARSE_HUGE) == 0)) || (depth > 1024)) { return(XML_ERR_ENTITY_LOOP); } if (list != NULL) *list = NULL; if ((URL == NULL) && (ID == NULL)) return(XML_ERR_INTERNAL_ERROR); if (doc == NULL) return(XML_ERR_INTERNAL_ERROR); ctxt = xmlCreateEntityParserCtxtInternal(URL, ID, NULL, oldctxt); if (ctxt == NULL) return(XML_WAR_UNDECLARED_ENTITY); ctxt->userData = ctxt; if (oldctxt != NULL) { ctxt->_private = oldctxt->_private; ctxt->loadsubset = oldctxt->loadsubset; ctxt->validate = oldctxt->validate; ctxt->external = oldctxt->external; ctxt->record_info = oldctxt->record_info; ctxt->node_seq.maximum = oldctxt->node_seq.maximum; ctxt->node_seq.length = oldctxt->node_seq.length; ctxt->node_seq.buffer = oldctxt->node_seq.buffer; } else { /* * Doing validity checking on chunk without context * doesn't make sense */ ctxt->_private = NULL; ctxt->validate = 0; ctxt->external = 2; ctxt->loadsubset = 0; } if (sax != NULL) { oldsax = ctxt->sax; ctxt->sax = sax; if (user_data != NULL) ctxt->userData = user_data; } xmlDetectSAX2(ctxt); newDoc = xmlNewDoc(BAD_CAST "1.0"); if (newDoc == NULL) { ctxt->node_seq.maximum = 0; ctxt->node_seq.length = 0; ctxt->node_seq.buffer = NULL; xmlFreeParserCtxt(ctxt); return(XML_ERR_INTERNAL_ERROR); } newDoc->properties = XML_DOC_INTERNAL; newDoc->intSubset = doc->intSubset; newDoc->extSubset = doc->extSubset; newDoc->dict = doc->dict; xmlDictReference(newDoc->dict); if (doc->URL != NULL) { newDoc->URL = xmlStrdup(doc->URL); } newRoot = xmlNewDocNode(newDoc, NULL, BAD_CAST "pseudoroot", NULL); if (newRoot == NULL) { if (sax != NULL) ctxt->sax = oldsax; ctxt->node_seq.maximum = 0; ctxt->node_seq.length = 0; ctxt->node_seq.buffer = NULL; xmlFreeParserCtxt(ctxt); newDoc->intSubset = NULL; newDoc->extSubset = NULL; xmlFreeDoc(newDoc); return(XML_ERR_INTERNAL_ERROR); } xmlAddChild((xmlNodePtr) newDoc, newRoot); nodePush(ctxt, newDoc->children); ctxt->myDoc = doc; newRoot->doc = doc; /* * Get the 4 first bytes and decode the charset * if enc != XML_CHAR_ENCODING_NONE * plug some encoding conversion routines. */ GROW; if ((ctxt->input->end - ctxt->input->cur) >= 4) { start[0] = RAW; start[1] = NXT(1); start[2] = NXT(2); start[3] = NXT(3); enc = xmlDetectCharEncoding(start, 4); if (enc != XML_CHAR_ENCODING_NONE) { xmlSwitchEncoding(ctxt, enc); } } /* * Parse a possible text declaration first */ if ((CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) && (IS_BLANK_CH(NXT(5)))) { xmlParseTextDecl(ctxt); } ctxt->instate = XML_PARSER_CONTENT; ctxt->depth = depth; xmlParseContent(ctxt); if ((RAW == '<') && (NXT(1) == '/')) { xmlFatalErr(ctxt, XML_ERR_NOT_WELL_BALANCED, NULL); } else if (RAW != 0) { xmlFatalErr(ctxt, XML_ERR_EXTRA_CONTENT, NULL); } if (ctxt->node != newDoc->children) { xmlFatalErr(ctxt, XML_ERR_NOT_WELL_BALANCED, NULL); } if (!ctxt->wellFormed) { if (ctxt->errNo == 0) ret = XML_ERR_INTERNAL_ERROR; else ret = (xmlParserErrors)ctxt->errNo; } else { if (list != NULL) { xmlNodePtr cur; /* * Return the newly created nodeset after unlinking it from * they pseudo parent. */ cur = newDoc->children->children; *list = cur; while (cur != NULL) { cur->parent = NULL; cur = cur->next; } newDoc->children->children = NULL; } ret = XML_ERR_OK; } /* * Record in the parent context the number of entities replacement * done when parsing that reference. */ if (oldctxt != NULL) oldctxt->nbentities += ctxt->nbentities; /* * Also record the size of the entity parsed */ if (ctxt->input != NULL && oldctxt != NULL) { oldctxt->sizeentities += ctxt->input->consumed; oldctxt->sizeentities += (ctxt->input->cur - ctxt->input->base); } /* * And record the last error if any */ if (ctxt->lastError.code != XML_ERR_OK) xmlCopyError(&ctxt->lastError, &oldctxt->lastError); if (sax != NULL) ctxt->sax = oldsax; if (oldctxt != NULL) { oldctxt->node_seq.maximum = ctxt->node_seq.maximum; oldctxt->node_seq.length = ctxt->node_seq.length; oldctxt->node_seq.buffer = ctxt->node_seq.buffer; } ctxt->node_seq.maximum = 0; ctxt->node_seq.length = 0; ctxt->node_seq.buffer = NULL; xmlFreeParserCtxt(ctxt); newDoc->intSubset = NULL; newDoc->extSubset = NULL; xmlFreeDoc(newDoc); return(ret); } #ifdef LIBXML_SAX1_ENABLED /** * xmlParseExternalEntity: * @doc: the document the chunk pertains to * @sax: the SAX handler bloc (possibly NULL) * @user_data: The user data returned on SAX callbacks (possibly NULL) * @depth: Used for loop detection, use 0 * @URL: the URL for the entity to load * @ID: the System ID for the entity to load * @lst: the return value for the set of parsed nodes * * Parse an external general entity * An external general parsed entity is well-formed if it matches the * production labeled extParsedEnt. * * [78] extParsedEnt ::= TextDecl? content * * Returns 0 if the entity is well formed, -1 in case of args problem and * the parser error code otherwise */ int xmlParseExternalEntity(xmlDocPtr doc, xmlSAXHandlerPtr sax, void *user_data, int depth, const xmlChar *URL, const xmlChar *ID, xmlNodePtr *lst) { return(xmlParseExternalEntityPrivate(doc, NULL, sax, user_data, depth, URL, ID, lst)); } /** * xmlParseBalancedChunkMemory: * @doc: the document the chunk pertains to * @sax: the SAX handler bloc (possibly NULL) * @user_data: The user data returned on SAX callbacks (possibly NULL) * @depth: Used for loop detection, use 0 * @string: the input string in UTF8 or ISO-Latin (zero terminated) * @lst: the return value for the set of parsed nodes * * Parse a well-balanced chunk of an XML document * called by the parser * The allowed sequence for the Well Balanced Chunk is the one defined by * the content production in the XML grammar: * * [43] content ::= (element | CharData | Reference | CDSect | PI | Comment)* * * Returns 0 if the chunk is well balanced, -1 in case of args problem and * the parser error code otherwise */ int xmlParseBalancedChunkMemory(xmlDocPtr doc, xmlSAXHandlerPtr sax, void *user_data, int depth, const xmlChar *string, xmlNodePtr *lst) { return xmlParseBalancedChunkMemoryRecover( doc, sax, user_data, depth, string, lst, 0 ); } #endif /* LIBXML_SAX1_ENABLED */ /** * xmlParseBalancedChunkMemoryInternal: * @oldctxt: the existing parsing context * @string: the input string in UTF8 or ISO-Latin (zero terminated) * @user_data: the user data field for the parser context * @lst: the return value for the set of parsed nodes * * * Parse a well-balanced chunk of an XML document * called by the parser * The allowed sequence for the Well Balanced Chunk is the one defined by * the content production in the XML grammar: * * [43] content ::= (element | CharData | Reference | CDSect | PI | Comment)* * * Returns XML_ERR_OK if the chunk is well balanced, and the parser * error code otherwise * * In case recover is set to 1, the nodelist will not be empty even if * the parsed chunk is not well balanced. */ static xmlParserErrors xmlParseBalancedChunkMemoryInternal(xmlParserCtxtPtr oldctxt, const xmlChar *string, void *user_data, xmlNodePtr *lst) { xmlParserCtxtPtr ctxt; xmlDocPtr newDoc = NULL; xmlNodePtr newRoot; xmlSAXHandlerPtr oldsax = NULL; xmlNodePtr content = NULL; xmlNodePtr last = NULL; int size; xmlParserErrors ret = XML_ERR_OK; #ifdef SAX2 int i; #endif if (((oldctxt->depth > 40) && ((oldctxt->options & XML_PARSE_HUGE) == 0)) || (oldctxt->depth > 1024)) { return(XML_ERR_ENTITY_LOOP); } if (lst != NULL) *lst = NULL; if (string == NULL) return(XML_ERR_INTERNAL_ERROR); size = xmlStrlen(string); ctxt = xmlCreateMemoryParserCtxt((char *) string, size); if (ctxt == NULL) return(XML_WAR_UNDECLARED_ENTITY); if (user_data != NULL) ctxt->userData = user_data; else ctxt->userData = ctxt; if (ctxt->dict != NULL) xmlDictFree(ctxt->dict); ctxt->dict = oldctxt->dict; ctxt->str_xml = xmlDictLookup(ctxt->dict, BAD_CAST "xml", 3); ctxt->str_xmlns = xmlDictLookup(ctxt->dict, BAD_CAST "xmlns", 5); ctxt->str_xml_ns = xmlDictLookup(ctxt->dict, XML_XML_NAMESPACE, 36); #ifdef SAX2 /* propagate namespaces down the entity */ for (i = 0;i < oldctxt->nsNr;i += 2) { nsPush(ctxt, oldctxt->nsTab[i], oldctxt->nsTab[i+1]); } #endif oldsax = ctxt->sax; ctxt->sax = oldctxt->sax; xmlDetectSAX2(ctxt); ctxt->replaceEntities = oldctxt->replaceEntities; ctxt->options = oldctxt->options; ctxt->_private = oldctxt->_private; if (oldctxt->myDoc == NULL) { newDoc = xmlNewDoc(BAD_CAST "1.0"); if (newDoc == NULL) { ctxt->sax = oldsax; ctxt->dict = NULL; xmlFreeParserCtxt(ctxt); return(XML_ERR_INTERNAL_ERROR); } newDoc->properties = XML_DOC_INTERNAL; newDoc->dict = ctxt->dict; xmlDictReference(newDoc->dict); ctxt->myDoc = newDoc; } else { ctxt->myDoc = oldctxt->myDoc; content = ctxt->myDoc->children; last = ctxt->myDoc->last; } newRoot = xmlNewDocNode(ctxt->myDoc, NULL, BAD_CAST "pseudoroot", NULL); if (newRoot == NULL) { ctxt->sax = oldsax; ctxt->dict = NULL; xmlFreeParserCtxt(ctxt); if (newDoc != NULL) { xmlFreeDoc(newDoc); } return(XML_ERR_INTERNAL_ERROR); } ctxt->myDoc->children = NULL; ctxt->myDoc->last = NULL; xmlAddChild((xmlNodePtr) ctxt->myDoc, newRoot); nodePush(ctxt, ctxt->myDoc->children); ctxt->instate = XML_PARSER_CONTENT; ctxt->depth = oldctxt->depth + 1; ctxt->validate = 0; ctxt->loadsubset = oldctxt->loadsubset; if ((oldctxt->validate) || (oldctxt->replaceEntities != 0)) { /* * ID/IDREF registration will be done in xmlValidateElement below */ ctxt->loadsubset |= XML_SKIP_IDS; } ctxt->dictNames = oldctxt->dictNames; ctxt->attsDefault = oldctxt->attsDefault; ctxt->attsSpecial = oldctxt->attsSpecial; xmlParseContent(ctxt); if ((RAW == '<') && (NXT(1) == '/')) { xmlFatalErr(ctxt, XML_ERR_NOT_WELL_BALANCED, NULL); } else if (RAW != 0) { xmlFatalErr(ctxt, XML_ERR_EXTRA_CONTENT, NULL); } if (ctxt->node != ctxt->myDoc->children) { xmlFatalErr(ctxt, XML_ERR_NOT_WELL_BALANCED, NULL); } if (!ctxt->wellFormed) { if (ctxt->errNo == 0) ret = XML_ERR_INTERNAL_ERROR; else ret = (xmlParserErrors)ctxt->errNo; } else { ret = XML_ERR_OK; } if ((lst != NULL) && (ret == XML_ERR_OK)) { xmlNodePtr cur; /* * Return the newly created nodeset after unlinking it from * they pseudo parent. */ cur = ctxt->myDoc->children->children; *lst = cur; while (cur != NULL) { #ifdef LIBXML_VALID_ENABLED if ((oldctxt->validate) && (oldctxt->wellFormed) && (oldctxt->myDoc) && (oldctxt->myDoc->intSubset) && (cur->type == XML_ELEMENT_NODE)) { oldctxt->valid &= xmlValidateElement(&oldctxt->vctxt, oldctxt->myDoc, cur); } #endif /* LIBXML_VALID_ENABLED */ cur->parent = NULL; cur = cur->next; } ctxt->myDoc->children->children = NULL; } if (ctxt->myDoc != NULL) { xmlFreeNode(ctxt->myDoc->children); ctxt->myDoc->children = content; ctxt->myDoc->last = last; } /* * Record in the parent context the number of entities replacement * done when parsing that reference. */ if (oldctxt != NULL) oldctxt->nbentities += ctxt->nbentities; /* * Also record the last error if any */ if (ctxt->lastError.code != XML_ERR_OK) xmlCopyError(&ctxt->lastError, &oldctxt->lastError); ctxt->sax = oldsax; ctxt->dict = NULL; ctxt->attsDefault = NULL; ctxt->attsSpecial = NULL; xmlFreeParserCtxt(ctxt); if (newDoc != NULL) { xmlFreeDoc(newDoc); } return(ret); } /** * xmlParseInNodeContext: * @node: the context node * @data: the input string * @datalen: the input string length in bytes * @options: a combination of xmlParserOption * @lst: the return value for the set of parsed nodes * * Parse a well-balanced chunk of an XML document * within the context (DTD, namespaces, etc ...) of the given node. * * The allowed sequence for the data is a Well Balanced Chunk defined by * the content production in the XML grammar: * * [43] content ::= (element | CharData | Reference | CDSect | PI | Comment)* * * Returns XML_ERR_OK if the chunk is well balanced, and the parser * error code otherwise */ xmlParserErrors xmlParseInNodeContext(xmlNodePtr node, const char *data, int datalen, int options, xmlNodePtr *lst) { #ifdef SAX2 xmlParserCtxtPtr ctxt; xmlDocPtr doc = NULL; xmlNodePtr fake, cur; int nsnr = 0; xmlParserErrors ret = XML_ERR_OK; /* * check all input parameters, grab the document */ if ((lst == NULL) || (node == NULL) || (data == NULL) || (datalen < 0)) return(XML_ERR_INTERNAL_ERROR); switch (node->type) { case XML_ELEMENT_NODE: case XML_ATTRIBUTE_NODE: case XML_TEXT_NODE: case XML_CDATA_SECTION_NODE: case XML_ENTITY_REF_NODE: case XML_PI_NODE: case XML_COMMENT_NODE: case XML_DOCUMENT_NODE: case XML_HTML_DOCUMENT_NODE: break; default: return(XML_ERR_INTERNAL_ERROR); } while ((node != NULL) && (node->type != XML_ELEMENT_NODE) && (node->type != XML_DOCUMENT_NODE) && (node->type != XML_HTML_DOCUMENT_NODE)) node = node->parent; if (node == NULL) return(XML_ERR_INTERNAL_ERROR); if (node->type == XML_ELEMENT_NODE) doc = node->doc; else doc = (xmlDocPtr) node; if (doc == NULL) return(XML_ERR_INTERNAL_ERROR); /* * allocate a context and set-up everything not related to the * node position in the tree */ if (doc->type == XML_DOCUMENT_NODE) ctxt = xmlCreateMemoryParserCtxt((char *) data, datalen); #ifdef LIBXML_HTML_ENABLED else if (doc->type == XML_HTML_DOCUMENT_NODE) { ctxt = htmlCreateMemoryParserCtxt((char *) data, datalen); /* * When parsing in context, it makes no sense to add implied * elements like html/body/etc... */ options |= HTML_PARSE_NOIMPLIED; } #endif else return(XML_ERR_INTERNAL_ERROR); if (ctxt == NULL) return(XML_ERR_NO_MEMORY); /* * Use input doc's dict if present, else assure XML_PARSE_NODICT is set. * We need a dictionary for xmlDetectSAX2, so if there's no doc dict * we must wait until the last moment to free the original one. */ if (doc->dict != NULL) { if (ctxt->dict != NULL) xmlDictFree(ctxt->dict); ctxt->dict = doc->dict; } else options |= XML_PARSE_NODICT; if (doc->encoding != NULL) { xmlCharEncodingHandlerPtr hdlr; if (ctxt->encoding != NULL) xmlFree((xmlChar *) ctxt->encoding); ctxt->encoding = xmlStrdup((const xmlChar *) doc->encoding); hdlr = xmlFindCharEncodingHandler((const char *) doc->encoding); if (hdlr != NULL) { xmlSwitchToEncoding(ctxt, hdlr); } else { return(XML_ERR_UNSUPPORTED_ENCODING); } } xmlCtxtUseOptionsInternal(ctxt, options, NULL); xmlDetectSAX2(ctxt); ctxt->myDoc = doc; /* parsing in context, i.e. as within existing content */ ctxt->instate = XML_PARSER_CONTENT; fake = xmlNewComment(NULL); if (fake == NULL) { xmlFreeParserCtxt(ctxt); return(XML_ERR_NO_MEMORY); } xmlAddChild(node, fake); if (node->type == XML_ELEMENT_NODE) { nodePush(ctxt, node); /* * initialize the SAX2 namespaces stack */ cur = node; while ((cur != NULL) && (cur->type == XML_ELEMENT_NODE)) { xmlNsPtr ns = cur->nsDef; const xmlChar *iprefix, *ihref; while (ns != NULL) { if (ctxt->dict) { iprefix = xmlDictLookup(ctxt->dict, ns->prefix, -1); ihref = xmlDictLookup(ctxt->dict, ns->href, -1); } else { iprefix = ns->prefix; ihref = ns->href; } if (xmlGetNamespace(ctxt, iprefix) == NULL) { nsPush(ctxt, iprefix, ihref); nsnr++; } ns = ns->next; } cur = cur->parent; } } if ((ctxt->validate) || (ctxt->replaceEntities != 0)) { /* * ID/IDREF registration will be done in xmlValidateElement below */ ctxt->loadsubset |= XML_SKIP_IDS; } #ifdef LIBXML_HTML_ENABLED if (doc->type == XML_HTML_DOCUMENT_NODE) __htmlParseContent(ctxt); else #endif xmlParseContent(ctxt); nsPop(ctxt, nsnr); if ((RAW == '<') && (NXT(1) == '/')) { xmlFatalErr(ctxt, XML_ERR_NOT_WELL_BALANCED, NULL); } else if (RAW != 0) { xmlFatalErr(ctxt, XML_ERR_EXTRA_CONTENT, NULL); } if ((ctxt->node != NULL) && (ctxt->node != node)) { xmlFatalErr(ctxt, XML_ERR_NOT_WELL_BALANCED, NULL); ctxt->wellFormed = 0; } if (!ctxt->wellFormed) { if (ctxt->errNo == 0) ret = XML_ERR_INTERNAL_ERROR; else ret = (xmlParserErrors)ctxt->errNo; } else { ret = XML_ERR_OK; } /* * Return the newly created nodeset after unlinking it from * the pseudo sibling. */ cur = fake->next; fake->next = NULL; node->last = fake; if (cur != NULL) { cur->prev = NULL; } *lst = cur; while (cur != NULL) { cur->parent = NULL; cur = cur->next; } xmlUnlinkNode(fake); xmlFreeNode(fake); if (ret != XML_ERR_OK) { xmlFreeNodeList(*lst); *lst = NULL; } if (doc->dict != NULL) ctxt->dict = NULL; xmlFreeParserCtxt(ctxt); return(ret); #else /* !SAX2 */ return(XML_ERR_INTERNAL_ERROR); #endif } #ifdef LIBXML_SAX1_ENABLED /** * xmlParseBalancedChunkMemoryRecover: * @doc: the document the chunk pertains to * @sax: the SAX handler bloc (possibly NULL) * @user_data: The user data returned on SAX callbacks (possibly NULL) * @depth: Used for loop detection, use 0 * @string: the input string in UTF8 or ISO-Latin (zero terminated) * @lst: the return value for the set of parsed nodes * @recover: return nodes even if the data is broken (use 0) * * * Parse a well-balanced chunk of an XML document * called by the parser * The allowed sequence for the Well Balanced Chunk is the one defined by * the content production in the XML grammar: * * [43] content ::= (element | CharData | Reference | CDSect | PI | Comment)* * * Returns 0 if the chunk is well balanced, -1 in case of args problem and * the parser error code otherwise * * In case recover is set to 1, the nodelist will not be empty even if * the parsed chunk is not well balanced, assuming the parsing succeeded to * some extent. */ int xmlParseBalancedChunkMemoryRecover(xmlDocPtr doc, xmlSAXHandlerPtr sax, void *user_data, int depth, const xmlChar *string, xmlNodePtr *lst, int recover) { xmlParserCtxtPtr ctxt; xmlDocPtr newDoc; xmlSAXHandlerPtr oldsax = NULL; xmlNodePtr content, newRoot; int size; int ret = 0; if (depth > 40) { return(XML_ERR_ENTITY_LOOP); } if (lst != NULL) *lst = NULL; if (string == NULL) return(-1); size = xmlStrlen(string); ctxt = xmlCreateMemoryParserCtxt((char *) string, size); if (ctxt == NULL) return(-1); ctxt->userData = ctxt; if (sax != NULL) { oldsax = ctxt->sax; ctxt->sax = sax; if (user_data != NULL) ctxt->userData = user_data; } newDoc = xmlNewDoc(BAD_CAST "1.0"); if (newDoc == NULL) { xmlFreeParserCtxt(ctxt); return(-1); } newDoc->properties = XML_DOC_INTERNAL; if ((doc != NULL) && (doc->dict != NULL)) { xmlDictFree(ctxt->dict); ctxt->dict = doc->dict; xmlDictReference(ctxt->dict); ctxt->str_xml = xmlDictLookup(ctxt->dict, BAD_CAST "xml", 3); ctxt->str_xmlns = xmlDictLookup(ctxt->dict, BAD_CAST "xmlns", 5); ctxt->str_xml_ns = xmlDictLookup(ctxt->dict, XML_XML_NAMESPACE, 36); ctxt->dictNames = 1; } else { xmlCtxtUseOptionsInternal(ctxt, XML_PARSE_NODICT, NULL); } if (doc != NULL) { newDoc->intSubset = doc->intSubset; newDoc->extSubset = doc->extSubset; } newRoot = xmlNewDocNode(newDoc, NULL, BAD_CAST "pseudoroot", NULL); if (newRoot == NULL) { if (sax != NULL) ctxt->sax = oldsax; xmlFreeParserCtxt(ctxt); newDoc->intSubset = NULL; newDoc->extSubset = NULL; xmlFreeDoc(newDoc); return(-1); } xmlAddChild((xmlNodePtr) newDoc, newRoot); nodePush(ctxt, newRoot); if (doc == NULL) { ctxt->myDoc = newDoc; } else { ctxt->myDoc = newDoc; newDoc->children->doc = doc; /* Ensure that doc has XML spec namespace */ xmlSearchNsByHref(doc, (xmlNodePtr)doc, XML_XML_NAMESPACE); newDoc->oldNs = doc->oldNs; } ctxt->instate = XML_PARSER_CONTENT; ctxt->depth = depth; /* * Doing validity checking on chunk doesn't make sense */ ctxt->validate = 0; ctxt->loadsubset = 0; xmlDetectSAX2(ctxt); if ( doc != NULL ){ content = doc->children; doc->children = NULL; xmlParseContent(ctxt); doc->children = content; } else { xmlParseContent(ctxt); } if ((RAW == '<') && (NXT(1) == '/')) { xmlFatalErr(ctxt, XML_ERR_NOT_WELL_BALANCED, NULL); } else if (RAW != 0) { xmlFatalErr(ctxt, XML_ERR_EXTRA_CONTENT, NULL); } if (ctxt->node != newDoc->children) { xmlFatalErr(ctxt, XML_ERR_NOT_WELL_BALANCED, NULL); } if (!ctxt->wellFormed) { if (ctxt->errNo == 0) ret = 1; else ret = ctxt->errNo; } else { ret = 0; } if ((lst != NULL) && ((ret == 0) || (recover == 1))) { xmlNodePtr cur; /* * Return the newly created nodeset after unlinking it from * they pseudo parent. */ cur = newDoc->children->children; *lst = cur; while (cur != NULL) { xmlSetTreeDoc(cur, doc); cur->parent = NULL; cur = cur->next; } newDoc->children->children = NULL; } if (sax != NULL) ctxt->sax = oldsax; xmlFreeParserCtxt(ctxt); newDoc->intSubset = NULL; newDoc->extSubset = NULL; newDoc->oldNs = NULL; xmlFreeDoc(newDoc); return(ret); } /** * xmlSAXParseEntity: * @sax: the SAX handler block * @filename: the filename * * parse an XML external entity out of context and build a tree. * It use the given SAX function block to handle the parsing callback. * If sax is NULL, fallback to the default DOM tree building routines. * * [78] extParsedEnt ::= TextDecl? content * * This correspond to a "Well Balanced" chunk * * Returns the resulting document tree */ xmlDocPtr xmlSAXParseEntity(xmlSAXHandlerPtr sax, const char *filename) { xmlDocPtr ret; xmlParserCtxtPtr ctxt; ctxt = xmlCreateFileParserCtxt(filename); if (ctxt == NULL) { return(NULL); } if (sax != NULL) { if (ctxt->sax != NULL) xmlFree(ctxt->sax); ctxt->sax = sax; ctxt->userData = NULL; } xmlParseExtParsedEnt(ctxt); if (ctxt->wellFormed) ret = ctxt->myDoc; else { ret = NULL; xmlFreeDoc(ctxt->myDoc); ctxt->myDoc = NULL; } if (sax != NULL) ctxt->sax = NULL; xmlFreeParserCtxt(ctxt); return(ret); } /** * xmlParseEntity: * @filename: the filename * * parse an XML external entity out of context and build a tree. * * [78] extParsedEnt ::= TextDecl? content * * This correspond to a "Well Balanced" chunk * * Returns the resulting document tree */ xmlDocPtr xmlParseEntity(const char *filename) { return(xmlSAXParseEntity(NULL, filename)); } #endif /* LIBXML_SAX1_ENABLED */ /** * xmlCreateEntityParserCtxtInternal: * @URL: the entity URL * @ID: the entity PUBLIC ID * @base: a possible base for the target URI * @pctx: parser context used to set options on new context * * Create a parser context for an external entity * Automatic support for ZLIB/Compress compressed document is provided * by default if found at compile-time. * * Returns the new parser context or NULL */ static xmlParserCtxtPtr xmlCreateEntityParserCtxtInternal(const xmlChar *URL, const xmlChar *ID, const xmlChar *base, xmlParserCtxtPtr pctx) { xmlParserCtxtPtr ctxt; xmlParserInputPtr inputStream; char *directory = NULL; xmlChar *uri; ctxt = xmlNewParserCtxt(); if (ctxt == NULL) { return(NULL); } if (pctx != NULL) { ctxt->options = pctx->options; ctxt->_private = pctx->_private; } uri = xmlBuildURI(URL, base); if (uri == NULL) { inputStream = xmlLoadExternalEntity((char *)URL, (char *)ID, ctxt); if (inputStream == NULL) { xmlFreeParserCtxt(ctxt); return(NULL); } inputPush(ctxt, inputStream); if ((ctxt->directory == NULL) && (directory == NULL)) directory = xmlParserGetDirectory((char *)URL); if ((ctxt->directory == NULL) && (directory != NULL)) ctxt->directory = directory; } else { inputStream = xmlLoadExternalEntity((char *)uri, (char *)ID, ctxt); if (inputStream == NULL) { xmlFree(uri); xmlFreeParserCtxt(ctxt); return(NULL); } inputPush(ctxt, inputStream); if ((ctxt->directory == NULL) && (directory == NULL)) directory = xmlParserGetDirectory((char *)uri); if ((ctxt->directory == NULL) && (directory != NULL)) ctxt->directory = directory; xmlFree(uri); } return(ctxt); } /** * xmlCreateEntityParserCtxt: * @URL: the entity URL * @ID: the entity PUBLIC ID * @base: a possible base for the target URI * * Create a parser context for an external entity * Automatic support for ZLIB/Compress compressed document is provided * by default if found at compile-time. * * Returns the new parser context or NULL */ xmlParserCtxtPtr xmlCreateEntityParserCtxt(const xmlChar *URL, const xmlChar *ID, const xmlChar *base) { return xmlCreateEntityParserCtxtInternal(URL, ID, base, NULL); } /************************************************************************ * * * Front ends when parsing from a file * * * ************************************************************************/ /** * xmlCreateURLParserCtxt: * @filename: the filename or URL * @options: a combination of xmlParserOption * * Create a parser context for a file or URL content. * Automatic support for ZLIB/Compress compressed document is provided * by default if found at compile-time and for file accesses * * Returns the new parser context or NULL */ xmlParserCtxtPtr xmlCreateURLParserCtxt(const char *filename, int options) { xmlParserCtxtPtr ctxt; xmlParserInputPtr inputStream; char *directory = NULL; ctxt = xmlNewParserCtxt(); if (ctxt == NULL) { xmlErrMemory(NULL, "cannot allocate parser context"); return(NULL); } if (options) xmlCtxtUseOptionsInternal(ctxt, options, NULL); ctxt->linenumbers = 1; inputStream = xmlLoadExternalEntity(filename, NULL, ctxt); if (inputStream == NULL) { xmlFreeParserCtxt(ctxt); return(NULL); } inputPush(ctxt, inputStream); if ((ctxt->directory == NULL) && (directory == NULL)) directory = xmlParserGetDirectory(filename); if ((ctxt->directory == NULL) && (directory != NULL)) ctxt->directory = directory; return(ctxt); } /** * xmlCreateFileParserCtxt: * @filename: the filename * * Create a parser context for a file content. * Automatic support for ZLIB/Compress compressed document is provided * by default if found at compile-time. * * Returns the new parser context or NULL */ xmlParserCtxtPtr xmlCreateFileParserCtxt(const char *filename) { return(xmlCreateURLParserCtxt(filename, 0)); } #ifdef LIBXML_SAX1_ENABLED /** * xmlSAXParseFileWithData: * @sax: the SAX handler block * @filename: the filename * @recovery: work in recovery mode, i.e. tries to read no Well Formed * documents * @data: the userdata * * parse an XML file and build a tree. Automatic support for ZLIB/Compress * compressed document is provided by default if found at compile-time. * It use the given SAX function block to handle the parsing callback. * If sax is NULL, fallback to the default DOM tree building routines. * * User data (void *) is stored within the parser context in the * context's _private member, so it is available nearly everywhere in libxml * * Returns the resulting document tree */ xmlDocPtr xmlSAXParseFileWithData(xmlSAXHandlerPtr sax, const char *filename, int recovery, void *data) { xmlDocPtr ret; xmlParserCtxtPtr ctxt; xmlInitParser(); ctxt = xmlCreateFileParserCtxt(filename); if (ctxt == NULL) { return(NULL); } if (sax != NULL) { if (ctxt->sax != NULL) xmlFree(ctxt->sax); ctxt->sax = sax; } xmlDetectSAX2(ctxt); if (data!=NULL) { ctxt->_private = data; } if (ctxt->directory == NULL) ctxt->directory = xmlParserGetDirectory(filename); ctxt->recovery = recovery; xmlParseDocument(ctxt); if ((ctxt->wellFormed) || recovery) { ret = ctxt->myDoc; if (ret != NULL) { if (ctxt->input->buf->compressed > 0) ret->compression = 9; else ret->compression = ctxt->input->buf->compressed; } } else { ret = NULL; xmlFreeDoc(ctxt->myDoc); ctxt->myDoc = NULL; } if (sax != NULL) ctxt->sax = NULL; xmlFreeParserCtxt(ctxt); return(ret); } /** * xmlSAXParseFile: * @sax: the SAX handler block * @filename: the filename * @recovery: work in recovery mode, i.e. tries to read no Well Formed * documents * * parse an XML file and build a tree. Automatic support for ZLIB/Compress * compressed document is provided by default if found at compile-time. * It use the given SAX function block to handle the parsing callback. * If sax is NULL, fallback to the default DOM tree building routines. * * Returns the resulting document tree */ xmlDocPtr xmlSAXParseFile(xmlSAXHandlerPtr sax, const char *filename, int recovery) { return(xmlSAXParseFileWithData(sax,filename,recovery,NULL)); } /** * xmlRecoverDoc: * @cur: a pointer to an array of xmlChar * * parse an XML in-memory document and build a tree. * In the case the document is not Well Formed, a attempt to build a * tree is tried anyway * * Returns the resulting document tree or NULL in case of failure */ xmlDocPtr xmlRecoverDoc(const xmlChar *cur) { return(xmlSAXParseDoc(NULL, cur, 1)); } /** * xmlParseFile: * @filename: the filename * * parse an XML file and build a tree. Automatic support for ZLIB/Compress * compressed document is provided by default if found at compile-time. * * Returns the resulting document tree if the file was wellformed, * NULL otherwise. */ xmlDocPtr xmlParseFile(const char *filename) { return(xmlSAXParseFile(NULL, filename, 0)); } /** * xmlRecoverFile: * @filename: the filename * * parse an XML file and build a tree. Automatic support for ZLIB/Compress * compressed document is provided by default if found at compile-time. * In the case the document is not Well Formed, it attempts to build * a tree anyway * * Returns the resulting document tree or NULL in case of failure */ xmlDocPtr xmlRecoverFile(const char *filename) { return(xmlSAXParseFile(NULL, filename, 1)); } /** * xmlSetupParserForBuffer: * @ctxt: an XML parser context * @buffer: a xmlChar * buffer * @filename: a file name * * Setup the parser context to parse a new buffer; Clears any prior * contents from the parser context. The buffer parameter must not be * NULL, but the filename parameter can be */ void xmlSetupParserForBuffer(xmlParserCtxtPtr ctxt, const xmlChar* buffer, const char* filename) { xmlParserInputPtr input; if ((ctxt == NULL) || (buffer == NULL)) return; input = xmlNewInputStream(ctxt); if (input == NULL) { xmlErrMemory(NULL, "parsing new buffer: out of memory\n"); xmlClearParserCtxt(ctxt); return; } xmlClearParserCtxt(ctxt); if (filename != NULL) input->filename = (char *) xmlCanonicPath((const xmlChar *)filename); input->base = buffer; input->cur = buffer; input->end = &buffer[xmlStrlen(buffer)]; inputPush(ctxt, input); } /** * xmlSAXUserParseFile: * @sax: a SAX handler * @user_data: The user data returned on SAX callbacks * @filename: a file name * * parse an XML file and call the given SAX handler routines. * Automatic support for ZLIB/Compress compressed document is provided * * Returns 0 in case of success or a error number otherwise */ int xmlSAXUserParseFile(xmlSAXHandlerPtr sax, void *user_data, const char *filename) { int ret = 0; xmlParserCtxtPtr ctxt; ctxt = xmlCreateFileParserCtxt(filename); if (ctxt == NULL) return -1; if (ctxt->sax != (xmlSAXHandlerPtr) &xmlDefaultSAXHandler) xmlFree(ctxt->sax); ctxt->sax = sax; xmlDetectSAX2(ctxt); if (user_data != NULL) ctxt->userData = user_data; xmlParseDocument(ctxt); if (ctxt->wellFormed) ret = 0; else { if (ctxt->errNo != 0) ret = ctxt->errNo; else ret = -1; } if (sax != NULL) ctxt->sax = NULL; if (ctxt->myDoc != NULL) { xmlFreeDoc(ctxt->myDoc); ctxt->myDoc = NULL; } xmlFreeParserCtxt(ctxt); return ret; } #endif /* LIBXML_SAX1_ENABLED */ /************************************************************************ * * * Front ends when parsing from memory * * * ************************************************************************/ /** * xmlCreateMemoryParserCtxt: * @buffer: a pointer to a char array * @size: the size of the array * * Create a parser context for an XML in-memory document. * * Returns the new parser context or NULL */ xmlParserCtxtPtr xmlCreateMemoryParserCtxt(const char *buffer, int size) { xmlParserCtxtPtr ctxt; xmlParserInputPtr input; xmlParserInputBufferPtr buf; if (buffer == NULL) return(NULL); if (size <= 0) return(NULL); ctxt = xmlNewParserCtxt(); if (ctxt == NULL) return(NULL); /* TODO: xmlParserInputBufferCreateStatic, requires some serious changes */ buf = xmlParserInputBufferCreateMem(buffer, size, XML_CHAR_ENCODING_NONE); if (buf == NULL) { xmlFreeParserCtxt(ctxt); return(NULL); } input = xmlNewInputStream(ctxt); if (input == NULL) { xmlFreeParserInputBuffer(buf); xmlFreeParserCtxt(ctxt); return(NULL); } input->filename = NULL; input->buf = buf; xmlBufResetInput(input->buf->buffer, input); inputPush(ctxt, input); return(ctxt); } #ifdef LIBXML_SAX1_ENABLED /** * xmlSAXParseMemoryWithData: * @sax: the SAX handler block * @buffer: an pointer to a char array * @size: the size of the array * @recovery: work in recovery mode, i.e. tries to read no Well Formed * documents * @data: the userdata * * parse an XML in-memory block and use the given SAX function block * to handle the parsing callback. If sax is NULL, fallback to the default * DOM tree building routines. * * User data (void *) is stored within the parser context in the * context's _private member, so it is available nearly everywhere in libxml * * Returns the resulting document tree */ xmlDocPtr xmlSAXParseMemoryWithData(xmlSAXHandlerPtr sax, const char *buffer, int size, int recovery, void *data) { xmlDocPtr ret; xmlParserCtxtPtr ctxt; xmlInitParser(); ctxt = xmlCreateMemoryParserCtxt(buffer, size); if (ctxt == NULL) return(NULL); if (sax != NULL) { if (ctxt->sax != NULL) xmlFree(ctxt->sax); ctxt->sax = sax; } xmlDetectSAX2(ctxt); if (data!=NULL) { ctxt->_private=data; } ctxt->recovery = recovery; xmlParseDocument(ctxt); if ((ctxt->wellFormed) || recovery) ret = ctxt->myDoc; else { ret = NULL; xmlFreeDoc(ctxt->myDoc); ctxt->myDoc = NULL; } if (sax != NULL) ctxt->sax = NULL; xmlFreeParserCtxt(ctxt); return(ret); } /** * xmlSAXParseMemory: * @sax: the SAX handler block * @buffer: an pointer to a char array * @size: the size of the array * @recovery: work in recovery mode, i.e. tries to read not Well Formed * documents * * parse an XML in-memory block and use the given SAX function block * to handle the parsing callback. If sax is NULL, fallback to the default * DOM tree building routines. * * Returns the resulting document tree */ xmlDocPtr xmlSAXParseMemory(xmlSAXHandlerPtr sax, const char *buffer, int size, int recovery) { return xmlSAXParseMemoryWithData(sax, buffer, size, recovery, NULL); } /** * xmlParseMemory: * @buffer: an pointer to a char array * @size: the size of the array * * parse an XML in-memory block and build a tree. * * Returns the resulting document tree */ xmlDocPtr xmlParseMemory(const char *buffer, int size) { return(xmlSAXParseMemory(NULL, buffer, size, 0)); } /** * xmlRecoverMemory: * @buffer: an pointer to a char array * @size: the size of the array * * parse an XML in-memory block and build a tree. * In the case the document is not Well Formed, an attempt to * build a tree is tried anyway * * Returns the resulting document tree or NULL in case of error */ xmlDocPtr xmlRecoverMemory(const char *buffer, int size) { return(xmlSAXParseMemory(NULL, buffer, size, 1)); } /** * xmlSAXUserParseMemory: * @sax: a SAX handler * @user_data: The user data returned on SAX callbacks * @buffer: an in-memory XML document input * @size: the length of the XML document in bytes * * A better SAX parsing routine. * parse an XML in-memory buffer and call the given SAX handler routines. * * Returns 0 in case of success or a error number otherwise */ int xmlSAXUserParseMemory(xmlSAXHandlerPtr sax, void *user_data, const char *buffer, int size) { int ret = 0; xmlParserCtxtPtr ctxt; xmlInitParser(); ctxt = xmlCreateMemoryParserCtxt(buffer, size); if (ctxt == NULL) return -1; if (ctxt->sax != (xmlSAXHandlerPtr) &xmlDefaultSAXHandler) xmlFree(ctxt->sax); ctxt->sax = sax; xmlDetectSAX2(ctxt); if (user_data != NULL) ctxt->userData = user_data; xmlParseDocument(ctxt); if (ctxt->wellFormed) ret = 0; else { if (ctxt->errNo != 0) ret = ctxt->errNo; else ret = -1; } if (sax != NULL) ctxt->sax = NULL; if (ctxt->myDoc != NULL) { xmlFreeDoc(ctxt->myDoc); ctxt->myDoc = NULL; } xmlFreeParserCtxt(ctxt); return ret; } #endif /* LIBXML_SAX1_ENABLED */ /** * xmlCreateDocParserCtxt: * @cur: a pointer to an array of xmlChar * * Creates a parser context for an XML in-memory document. * * Returns the new parser context or NULL */ xmlParserCtxtPtr xmlCreateDocParserCtxt(const xmlChar *cur) { int len; if (cur == NULL) return(NULL); len = xmlStrlen(cur); return(xmlCreateMemoryParserCtxt((const char *)cur, len)); } #ifdef LIBXML_SAX1_ENABLED /** * xmlSAXParseDoc: * @sax: the SAX handler block * @cur: a pointer to an array of xmlChar * @recovery: work in recovery mode, i.e. tries to read no Well Formed * documents * * parse an XML in-memory document and build a tree. * It use the given SAX function block to handle the parsing callback. * If sax is NULL, fallback to the default DOM tree building routines. * * Returns the resulting document tree */ xmlDocPtr xmlSAXParseDoc(xmlSAXHandlerPtr sax, const xmlChar *cur, int recovery) { xmlDocPtr ret; xmlParserCtxtPtr ctxt; xmlSAXHandlerPtr oldsax = NULL; if (cur == NULL) return(NULL); ctxt = xmlCreateDocParserCtxt(cur); if (ctxt == NULL) return(NULL); if (sax != NULL) { oldsax = ctxt->sax; ctxt->sax = sax; ctxt->userData = NULL; } xmlDetectSAX2(ctxt); xmlParseDocument(ctxt); if ((ctxt->wellFormed) || recovery) ret = ctxt->myDoc; else { ret = NULL; xmlFreeDoc(ctxt->myDoc); ctxt->myDoc = NULL; } if (sax != NULL) ctxt->sax = oldsax; xmlFreeParserCtxt(ctxt); return(ret); } /** * xmlParseDoc: * @cur: a pointer to an array of xmlChar * * parse an XML in-memory document and build a tree. * * Returns the resulting document tree */ xmlDocPtr xmlParseDoc(const xmlChar *cur) { return(xmlSAXParseDoc(NULL, cur, 0)); } #endif /* LIBXML_SAX1_ENABLED */ #ifdef LIBXML_LEGACY_ENABLED /************************************************************************ * * * Specific function to keep track of entities references * * and used by the XSLT debugger * * * ************************************************************************/ static xmlEntityReferenceFunc xmlEntityRefFunc = NULL; /** * xmlAddEntityReference: * @ent : A valid entity * @firstNode : A valid first node for children of entity * @lastNode : A valid last node of children entity * * Notify of a reference to an entity of type XML_EXTERNAL_GENERAL_PARSED_ENTITY */ static void xmlAddEntityReference(xmlEntityPtr ent, xmlNodePtr firstNode, xmlNodePtr lastNode) { if (xmlEntityRefFunc != NULL) { (*xmlEntityRefFunc) (ent, firstNode, lastNode); } } /** * xmlSetEntityReferenceFunc: * @func: A valid function * * Set the function to call call back when a xml reference has been made */ void xmlSetEntityReferenceFunc(xmlEntityReferenceFunc func) { xmlEntityRefFunc = func; } #endif /* LIBXML_LEGACY_ENABLED */ /************************************************************************ * * * Miscellaneous * * * ************************************************************************/ #ifdef LIBXML_XPATH_ENABLED #include <libxml/xpath.h> #endif extern void XMLCDECL xmlGenericErrorDefaultFunc(void *ctx, const char *msg, ...); static int xmlParserInitialized = 0; /** * xmlInitParser: * * Initialization function for the XML parser. * This is not reentrant. Call once before processing in case of * use in multithreaded programs. */ void xmlInitParser(void) { if (xmlParserInitialized != 0) return; #ifdef LIBXML_THREAD_ENABLED __xmlGlobalInitMutexLock(); if (xmlParserInitialized == 0) { #endif xmlInitThreads(); xmlInitGlobals(); if ((xmlGenericError == xmlGenericErrorDefaultFunc) || (xmlGenericError == NULL)) initGenericErrorDefaultFunc(NULL); xmlInitMemory(); xmlInitializeDict(); xmlInitCharEncodingHandlers(); xmlDefaultSAXHandlerInit(); xmlRegisterDefaultInputCallbacks(); #ifdef LIBXML_OUTPUT_ENABLED xmlRegisterDefaultOutputCallbacks(); #endif /* LIBXML_OUTPUT_ENABLED */ #ifdef LIBXML_HTML_ENABLED htmlInitAutoClose(); htmlDefaultSAXHandlerInit(); #endif #ifdef LIBXML_XPATH_ENABLED xmlXPathInit(); #endif xmlParserInitialized = 1; #ifdef LIBXML_THREAD_ENABLED } __xmlGlobalInitMutexUnlock(); #endif } /** * xmlCleanupParser: * * This function name is somewhat misleading. It does not clean up * parser state, it cleans up memory allocated by the library itself. * It is a cleanup function for the XML library. It tries to reclaim all * related global memory allocated for the library processing. * It doesn't deallocate any document related memory. One should * call xmlCleanupParser() only when the process has finished using * the library and all XML/HTML documents built with it. * See also xmlInitParser() which has the opposite function of preparing * the library for operations. * * WARNING: if your application is multithreaded or has plugin support * calling this may crash the application if another thread or * a plugin is still using libxml2. It's sometimes very hard to * guess if libxml2 is in use in the application, some libraries * or plugins may use it without notice. In case of doubt abstain * from calling this function or do it just before calling exit() * to avoid leak reports from valgrind ! */ void xmlCleanupParser(void) { if (!xmlParserInitialized) return; xmlCleanupCharEncodingHandlers(); #ifdef LIBXML_CATALOG_ENABLED xmlCatalogCleanup(); #endif xmlDictCleanup(); xmlCleanupInputCallbacks(); #ifdef LIBXML_OUTPUT_ENABLED xmlCleanupOutputCallbacks(); #endif #ifdef LIBXML_SCHEMAS_ENABLED xmlSchemaCleanupTypes(); xmlRelaxNGCleanupTypes(); #endif xmlResetLastError(); xmlCleanupGlobals(); xmlCleanupThreads(); /* must be last if called not from the main thread */ xmlCleanupMemory(); xmlParserInitialized = 0; } /************************************************************************ * * * New set (2.6.0) of simpler and more flexible APIs * * * ************************************************************************/ /** * DICT_FREE: * @str: a string * * Free a string if it is not owned by the "dict" dictionary in the * current scope */ #define DICT_FREE(str) \ if ((str) && ((!dict) || \ (xmlDictOwns(dict, (const xmlChar *)(str)) == 0))) \ xmlFree((char *)(str)); /** * xmlCtxtReset: * @ctxt: an XML parser context * * Reset a parser context */ void xmlCtxtReset(xmlParserCtxtPtr ctxt) { xmlParserInputPtr input; xmlDictPtr dict; if (ctxt == NULL) return; dict = ctxt->dict; while ((input = inputPop(ctxt)) != NULL) { /* Non consuming */ xmlFreeInputStream(input); } ctxt->inputNr = 0; ctxt->input = NULL; ctxt->spaceNr = 0; if (ctxt->spaceTab != NULL) { ctxt->spaceTab[0] = -1; ctxt->space = &ctxt->spaceTab[0]; } else { ctxt->space = NULL; } ctxt->nodeNr = 0; ctxt->node = NULL; ctxt->nameNr = 0; ctxt->name = NULL; DICT_FREE(ctxt->version); ctxt->version = NULL; DICT_FREE(ctxt->encoding); ctxt->encoding = NULL; DICT_FREE(ctxt->directory); ctxt->directory = NULL; DICT_FREE(ctxt->extSubURI); ctxt->extSubURI = NULL; DICT_FREE(ctxt->extSubSystem); ctxt->extSubSystem = NULL; if (ctxt->myDoc != NULL) xmlFreeDoc(ctxt->myDoc); ctxt->myDoc = NULL; ctxt->standalone = -1; ctxt->hasExternalSubset = 0; ctxt->hasPErefs = 0; ctxt->html = 0; ctxt->external = 0; ctxt->instate = XML_PARSER_START; ctxt->token = 0; ctxt->wellFormed = 1; ctxt->nsWellFormed = 1; ctxt->disableSAX = 0; ctxt->valid = 1; #if 0 ctxt->vctxt.userData = ctxt; ctxt->vctxt.error = xmlParserValidityError; ctxt->vctxt.warning = xmlParserValidityWarning; #endif ctxt->record_info = 0; ctxt->nbChars = 0; ctxt->checkIndex = 0; ctxt->inSubset = 0; ctxt->errNo = XML_ERR_OK; ctxt->depth = 0; ctxt->charset = XML_CHAR_ENCODING_UTF8; ctxt->catalogs = NULL; ctxt->nbentities = 0; ctxt->sizeentities = 0; ctxt->sizeentcopy = 0; xmlInitNodeInfoSeq(&ctxt->node_seq); if (ctxt->attsDefault != NULL) { xmlHashFree(ctxt->attsDefault, (xmlHashDeallocator) xmlFree); ctxt->attsDefault = NULL; } if (ctxt->attsSpecial != NULL) { xmlHashFree(ctxt->attsSpecial, NULL); ctxt->attsSpecial = NULL; } #ifdef LIBXML_CATALOG_ENABLED if (ctxt->catalogs != NULL) xmlCatalogFreeLocal(ctxt->catalogs); #endif if (ctxt->lastError.code != XML_ERR_OK) xmlResetError(&ctxt->lastError); } /** * xmlCtxtResetPush: * @ctxt: an XML parser context * @chunk: a pointer to an array of chars * @size: number of chars in the array * @filename: an optional file name or URI * @encoding: the document encoding, or NULL * * Reset a push parser context * * Returns 0 in case of success and 1 in case of error */ int xmlCtxtResetPush(xmlParserCtxtPtr ctxt, const char *chunk, int size, const char *filename, const char *encoding) { xmlParserInputPtr inputStream; xmlParserInputBufferPtr buf; xmlCharEncoding enc = XML_CHAR_ENCODING_NONE; if (ctxt == NULL) return(1); if ((encoding == NULL) && (chunk != NULL) && (size >= 4)) enc = xmlDetectCharEncoding((const xmlChar *) chunk, size); buf = xmlAllocParserInputBuffer(enc); if (buf == NULL) return(1); if (ctxt == NULL) { xmlFreeParserInputBuffer(buf); return(1); } xmlCtxtReset(ctxt); if (ctxt->pushTab == NULL) { ctxt->pushTab = (void **) xmlMalloc(ctxt->nameMax * 3 * sizeof(xmlChar *)); if (ctxt->pushTab == NULL) { xmlErrMemory(ctxt, NULL); xmlFreeParserInputBuffer(buf); return(1); } } if (filename == NULL) { ctxt->directory = NULL; } else { ctxt->directory = xmlParserGetDirectory(filename); } inputStream = xmlNewInputStream(ctxt); if (inputStream == NULL) { xmlFreeParserInputBuffer(buf); return(1); } if (filename == NULL) inputStream->filename = NULL; else inputStream->filename = (char *) xmlCanonicPath((const xmlChar *) filename); inputStream->buf = buf; xmlBufResetInput(buf->buffer, inputStream); inputPush(ctxt, inputStream); if ((size > 0) && (chunk != NULL) && (ctxt->input != NULL) && (ctxt->input->buf != NULL)) { size_t base = xmlBufGetInputBase(ctxt->input->buf->buffer, ctxt->input); size_t cur = ctxt->input->cur - ctxt->input->base; xmlParserInputBufferPush(ctxt->input->buf, size, chunk); xmlBufSetInputBaseCur(ctxt->input->buf->buffer, ctxt->input, base, cur); #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: pushed %d\n", size); #endif } if (encoding != NULL) { xmlCharEncodingHandlerPtr hdlr; if (ctxt->encoding != NULL) xmlFree((xmlChar *) ctxt->encoding); ctxt->encoding = xmlStrdup((const xmlChar *) encoding); hdlr = xmlFindCharEncodingHandler(encoding); if (hdlr != NULL) { xmlSwitchToEncoding(ctxt, hdlr); } else { xmlFatalErrMsgStr(ctxt, XML_ERR_UNSUPPORTED_ENCODING, "Unsupported encoding %s\n", BAD_CAST encoding); } } else if (enc != XML_CHAR_ENCODING_NONE) { xmlSwitchEncoding(ctxt, enc); } return(0); } /** * xmlCtxtUseOptionsInternal: * @ctxt: an XML parser context * @options: a combination of xmlParserOption * @encoding: the user provided encoding to use * * Applies the options to the parser context * * Returns 0 in case of success, the set of unknown or unimplemented options * in case of error. */ static int xmlCtxtUseOptionsInternal(xmlParserCtxtPtr ctxt, int options, const char *encoding) { if (ctxt == NULL) return(-1); if (encoding != NULL) { if (ctxt->encoding != NULL) xmlFree((xmlChar *) ctxt->encoding); ctxt->encoding = xmlStrdup((const xmlChar *) encoding); } if (options & XML_PARSE_RECOVER) { ctxt->recovery = 1; options -= XML_PARSE_RECOVER; ctxt->options |= XML_PARSE_RECOVER; } else ctxt->recovery = 0; if (options & XML_PARSE_DTDLOAD) { ctxt->loadsubset = XML_DETECT_IDS; options -= XML_PARSE_DTDLOAD; ctxt->options |= XML_PARSE_DTDLOAD; } else ctxt->loadsubset = 0; if (options & XML_PARSE_DTDATTR) { ctxt->loadsubset |= XML_COMPLETE_ATTRS; options -= XML_PARSE_DTDATTR; ctxt->options |= XML_PARSE_DTDATTR; } if (options & XML_PARSE_NOENT) { ctxt->replaceEntities = 1; /* ctxt->loadsubset |= XML_DETECT_IDS; */ options -= XML_PARSE_NOENT; ctxt->options |= XML_PARSE_NOENT; } else ctxt->replaceEntities = 0; if (options & XML_PARSE_PEDANTIC) { ctxt->pedantic = 1; options -= XML_PARSE_PEDANTIC; ctxt->options |= XML_PARSE_PEDANTIC; } else ctxt->pedantic = 0; if (options & XML_PARSE_NOBLANKS) { ctxt->keepBlanks = 0; ctxt->sax->ignorableWhitespace = xmlSAX2IgnorableWhitespace; options -= XML_PARSE_NOBLANKS; ctxt->options |= XML_PARSE_NOBLANKS; } else ctxt->keepBlanks = 1; if (options & XML_PARSE_DTDVALID) { ctxt->validate = 1; if (options & XML_PARSE_NOWARNING) ctxt->vctxt.warning = NULL; if (options & XML_PARSE_NOERROR) ctxt->vctxt.error = NULL; options -= XML_PARSE_DTDVALID; ctxt->options |= XML_PARSE_DTDVALID; } else ctxt->validate = 0; if (options & XML_PARSE_NOWARNING) { ctxt->sax->warning = NULL; options -= XML_PARSE_NOWARNING; } if (options & XML_PARSE_NOERROR) { ctxt->sax->error = NULL; ctxt->sax->fatalError = NULL; options -= XML_PARSE_NOERROR; } #ifdef LIBXML_SAX1_ENABLED if (options & XML_PARSE_SAX1) { ctxt->sax->startElement = xmlSAX2StartElement; ctxt->sax->endElement = xmlSAX2EndElement; ctxt->sax->startElementNs = NULL; ctxt->sax->endElementNs = NULL; ctxt->sax->initialized = 1; options -= XML_PARSE_SAX1; ctxt->options |= XML_PARSE_SAX1; } #endif /* LIBXML_SAX1_ENABLED */ if (options & XML_PARSE_NODICT) { ctxt->dictNames = 0; options -= XML_PARSE_NODICT; ctxt->options |= XML_PARSE_NODICT; } else { ctxt->dictNames = 1; } if (options & XML_PARSE_NOCDATA) { ctxt->sax->cdataBlock = NULL; options -= XML_PARSE_NOCDATA; ctxt->options |= XML_PARSE_NOCDATA; } if (options & XML_PARSE_NSCLEAN) { ctxt->options |= XML_PARSE_NSCLEAN; options -= XML_PARSE_NSCLEAN; } if (options & XML_PARSE_NONET) { ctxt->options |= XML_PARSE_NONET; options -= XML_PARSE_NONET; } if (options & XML_PARSE_NOXXE) { ctxt->options |= XML_PARSE_NOXXE; options -= XML_PARSE_NOXXE; } if (options & XML_PARSE_COMPACT) { ctxt->options |= XML_PARSE_COMPACT; options -= XML_PARSE_COMPACT; } if (options & XML_PARSE_OLD10) { ctxt->options |= XML_PARSE_OLD10; options -= XML_PARSE_OLD10; } if (options & XML_PARSE_NOBASEFIX) { ctxt->options |= XML_PARSE_NOBASEFIX; options -= XML_PARSE_NOBASEFIX; } if (options & XML_PARSE_HUGE) { ctxt->options |= XML_PARSE_HUGE; options -= XML_PARSE_HUGE; if (ctxt->dict != NULL) xmlDictSetLimit(ctxt->dict, 0); } if (options & XML_PARSE_OLDSAX) { ctxt->options |= XML_PARSE_OLDSAX; options -= XML_PARSE_OLDSAX; } if (options & XML_PARSE_IGNORE_ENC) { ctxt->options |= XML_PARSE_IGNORE_ENC; options -= XML_PARSE_IGNORE_ENC; } if (options & XML_PARSE_BIG_LINES) { ctxt->options |= XML_PARSE_BIG_LINES; options -= XML_PARSE_BIG_LINES; } ctxt->linenumbers = 1; return (options); } /** * xmlCtxtUseOptions: * @ctxt: an XML parser context * @options: a combination of xmlParserOption * * Applies the options to the parser context * * Returns 0 in case of success, the set of unknown or unimplemented options * in case of error. */ int xmlCtxtUseOptions(xmlParserCtxtPtr ctxt, int options) { return(xmlCtxtUseOptionsInternal(ctxt, options, NULL)); } /** * xmlDoRead: * @ctxt: an XML parser context * @URL: the base URL to use for the document * @encoding: the document encoding, or NULL * @options: a combination of xmlParserOption * @reuse: keep the context for reuse * * Common front-end for the xmlRead functions * * Returns the resulting document tree or NULL */ static xmlDocPtr xmlDoRead(xmlParserCtxtPtr ctxt, const char *URL, const char *encoding, int options, int reuse) { xmlDocPtr ret; xmlCtxtUseOptionsInternal(ctxt, options, encoding); if (encoding != NULL) { xmlCharEncodingHandlerPtr hdlr; hdlr = xmlFindCharEncodingHandler(encoding); if (hdlr != NULL) xmlSwitchToEncoding(ctxt, hdlr); } if ((URL != NULL) && (ctxt->input != NULL) && (ctxt->input->filename == NULL)) ctxt->input->filename = (char *) xmlStrdup((const xmlChar *) URL); xmlParseDocument(ctxt); if ((ctxt->wellFormed) || ctxt->recovery) ret = ctxt->myDoc; else { ret = NULL; if (ctxt->myDoc != NULL) { xmlFreeDoc(ctxt->myDoc); } } ctxt->myDoc = NULL; if (!reuse) { xmlFreeParserCtxt(ctxt); } return (ret); } /** * xmlReadDoc: * @cur: a pointer to a zero terminated string * @URL: the base URL to use for the document * @encoding: the document encoding, or NULL * @options: a combination of xmlParserOption * * parse an XML in-memory document and build a tree. * * Returns the resulting document tree */ xmlDocPtr xmlReadDoc(const xmlChar * cur, const char *URL, const char *encoding, int options) { xmlParserCtxtPtr ctxt; if (cur == NULL) return (NULL); xmlInitParser(); ctxt = xmlCreateDocParserCtxt(cur); if (ctxt == NULL) return (NULL); return (xmlDoRead(ctxt, URL, encoding, options, 0)); } /** * xmlReadFile: * @filename: a file or URL * @encoding: the document encoding, or NULL * @options: a combination of xmlParserOption * * parse an XML file from the filesystem or the network. * * Returns the resulting document tree */ xmlDocPtr xmlReadFile(const char *filename, const char *encoding, int options) { xmlParserCtxtPtr ctxt; xmlInitParser(); ctxt = xmlCreateURLParserCtxt(filename, options); if (ctxt == NULL) return (NULL); return (xmlDoRead(ctxt, NULL, encoding, options, 0)); } /** * xmlReadMemory: * @buffer: a pointer to a char array * @size: the size of the array * @URL: the base URL to use for the document * @encoding: the document encoding, or NULL * @options: a combination of xmlParserOption * * parse an XML in-memory document and build a tree. * * Returns the resulting document tree */ xmlDocPtr xmlReadMemory(const char *buffer, int size, const char *URL, const char *encoding, int options) { xmlParserCtxtPtr ctxt; xmlInitParser(); ctxt = xmlCreateMemoryParserCtxt(buffer, size); if (ctxt == NULL) return (NULL); return (xmlDoRead(ctxt, URL, encoding, options, 0)); } /** * xmlReadFd: * @fd: an open file descriptor * @URL: the base URL to use for the document * @encoding: the document encoding, or NULL * @options: a combination of xmlParserOption * * parse an XML from a file descriptor and build a tree. * NOTE that the file descriptor will not be closed when the * reader is closed or reset. * * Returns the resulting document tree */ xmlDocPtr xmlReadFd(int fd, const char *URL, const char *encoding, int options) { xmlParserCtxtPtr ctxt; xmlParserInputBufferPtr input; xmlParserInputPtr stream; if (fd < 0) return (NULL); xmlInitParser(); input = xmlParserInputBufferCreateFd(fd, XML_CHAR_ENCODING_NONE); if (input == NULL) return (NULL); input->closecallback = NULL; ctxt = xmlNewParserCtxt(); if (ctxt == NULL) { xmlFreeParserInputBuffer(input); return (NULL); } stream = xmlNewIOInputStream(ctxt, input, XML_CHAR_ENCODING_NONE); if (stream == NULL) { xmlFreeParserInputBuffer(input); xmlFreeParserCtxt(ctxt); return (NULL); } inputPush(ctxt, stream); return (xmlDoRead(ctxt, URL, encoding, options, 0)); } /** * xmlReadIO: * @ioread: an I/O read function * @ioclose: an I/O close function * @ioctx: an I/O handler * @URL: the base URL to use for the document * @encoding: the document encoding, or NULL * @options: a combination of xmlParserOption * * parse an XML document from I/O functions and source and build a tree. * * Returns the resulting document tree */ xmlDocPtr xmlReadIO(xmlInputReadCallback ioread, xmlInputCloseCallback ioclose, void *ioctx, const char *URL, const char *encoding, int options) { xmlParserCtxtPtr ctxt; xmlParserInputBufferPtr input; xmlParserInputPtr stream; if (ioread == NULL) return (NULL); xmlInitParser(); input = xmlParserInputBufferCreateIO(ioread, ioclose, ioctx, XML_CHAR_ENCODING_NONE); if (input == NULL) { if (ioclose != NULL) ioclose(ioctx); return (NULL); } ctxt = xmlNewParserCtxt(); if (ctxt == NULL) { xmlFreeParserInputBuffer(input); return (NULL); } stream = xmlNewIOInputStream(ctxt, input, XML_CHAR_ENCODING_NONE); if (stream == NULL) { xmlFreeParserInputBuffer(input); xmlFreeParserCtxt(ctxt); return (NULL); } inputPush(ctxt, stream); return (xmlDoRead(ctxt, URL, encoding, options, 0)); } /** * xmlCtxtReadDoc: * @ctxt: an XML parser context * @cur: a pointer to a zero terminated string * @URL: the base URL to use for the document * @encoding: the document encoding, or NULL * @options: a combination of xmlParserOption * * parse an XML in-memory document and build a tree. * This reuses the existing @ctxt parser context * * Returns the resulting document tree */ xmlDocPtr xmlCtxtReadDoc(xmlParserCtxtPtr ctxt, const xmlChar * cur, const char *URL, const char *encoding, int options) { xmlParserInputPtr stream; if (cur == NULL) return (NULL); if (ctxt == NULL) return (NULL); xmlInitParser(); xmlCtxtReset(ctxt); stream = xmlNewStringInputStream(ctxt, cur); if (stream == NULL) { return (NULL); } inputPush(ctxt, stream); return (xmlDoRead(ctxt, URL, encoding, options, 1)); } /** * xmlCtxtReadFile: * @ctxt: an XML parser context * @filename: a file or URL * @encoding: the document encoding, or NULL * @options: a combination of xmlParserOption * * parse an XML file from the filesystem or the network. * This reuses the existing @ctxt parser context * * Returns the resulting document tree */ xmlDocPtr xmlCtxtReadFile(xmlParserCtxtPtr ctxt, const char *filename, const char *encoding, int options) { xmlParserInputPtr stream; if (filename == NULL) return (NULL); if (ctxt == NULL) return (NULL); xmlInitParser(); xmlCtxtReset(ctxt); stream = xmlLoadExternalEntity(filename, NULL, ctxt); if (stream == NULL) { return (NULL); } inputPush(ctxt, stream); return (xmlDoRead(ctxt, NULL, encoding, options, 1)); } /** * xmlCtxtReadMemory: * @ctxt: an XML parser context * @buffer: a pointer to a char array * @size: the size of the array * @URL: the base URL to use for the document * @encoding: the document encoding, or NULL * @options: a combination of xmlParserOption * * parse an XML in-memory document and build a tree. * This reuses the existing @ctxt parser context * * Returns the resulting document tree */ xmlDocPtr xmlCtxtReadMemory(xmlParserCtxtPtr ctxt, const char *buffer, int size, const char *URL, const char *encoding, int options) { xmlParserInputBufferPtr input; xmlParserInputPtr stream; if (ctxt == NULL) return (NULL); if (buffer == NULL) return (NULL); xmlInitParser(); xmlCtxtReset(ctxt); input = xmlParserInputBufferCreateMem(buffer, size, XML_CHAR_ENCODING_NONE); if (input == NULL) { return(NULL); } stream = xmlNewIOInputStream(ctxt, input, XML_CHAR_ENCODING_NONE); if (stream == NULL) { xmlFreeParserInputBuffer(input); return(NULL); } inputPush(ctxt, stream); return (xmlDoRead(ctxt, URL, encoding, options, 1)); } /** * xmlCtxtReadFd: * @ctxt: an XML parser context * @fd: an open file descriptor * @URL: the base URL to use for the document * @encoding: the document encoding, or NULL * @options: a combination of xmlParserOption * * parse an XML from a file descriptor and build a tree. * This reuses the existing @ctxt parser context * NOTE that the file descriptor will not be closed when the * reader is closed or reset. * * Returns the resulting document tree */ xmlDocPtr xmlCtxtReadFd(xmlParserCtxtPtr ctxt, int fd, const char *URL, const char *encoding, int options) { xmlParserInputBufferPtr input; xmlParserInputPtr stream; if (fd < 0) return (NULL); if (ctxt == NULL) return (NULL); xmlInitParser(); xmlCtxtReset(ctxt); input = xmlParserInputBufferCreateFd(fd, XML_CHAR_ENCODING_NONE); if (input == NULL) return (NULL); input->closecallback = NULL; stream = xmlNewIOInputStream(ctxt, input, XML_CHAR_ENCODING_NONE); if (stream == NULL) { xmlFreeParserInputBuffer(input); return (NULL); } inputPush(ctxt, stream); return (xmlDoRead(ctxt, URL, encoding, options, 1)); } /** * xmlCtxtReadIO: * @ctxt: an XML parser context * @ioread: an I/O read function * @ioclose: an I/O close function * @ioctx: an I/O handler * @URL: the base URL to use for the document * @encoding: the document encoding, or NULL * @options: a combination of xmlParserOption * * parse an XML document from I/O functions and source and build a tree. * This reuses the existing @ctxt parser context * * Returns the resulting document tree */ xmlDocPtr xmlCtxtReadIO(xmlParserCtxtPtr ctxt, xmlInputReadCallback ioread, xmlInputCloseCallback ioclose, void *ioctx, const char *URL, const char *encoding, int options) { xmlParserInputBufferPtr input; xmlParserInputPtr stream; if (ioread == NULL) return (NULL); if (ctxt == NULL) return (NULL); xmlInitParser(); xmlCtxtReset(ctxt); input = xmlParserInputBufferCreateIO(ioread, ioclose, ioctx, XML_CHAR_ENCODING_NONE); if (input == NULL) { if (ioclose != NULL) ioclose(ioctx); return (NULL); } stream = xmlNewIOInputStream(ctxt, input, XML_CHAR_ENCODING_NONE); if (stream == NULL) { xmlFreeParserInputBuffer(input); return (NULL); } inputPush(ctxt, stream); return (xmlDoRead(ctxt, URL, encoding, options, 1)); } #define bottom_parser #include "elfgcchack.h"
./CrossVul/dataset_final_sorted/CWE-119/c/bad_2947_1
crossvul-cpp_data_good_5813_0
/* * Quicktime Video (RPZA) Video Decoder * Copyright (C) 2003 the ffmpeg project * * 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 * QT RPZA Video Decoder by Roberto Togni * For more information about the RPZA format, visit: * http://www.pcisys.net/~melanson/codecs/ * * The RPZA decoder outputs RGB555 colorspace data. * * Note that this decoder reads big endian RGB555 pixel values from the * bytestream, arranges them in the host's endian order, and outputs * them to the final rendered map in the same host endian order. This is * intended behavior as the libavcodec documentation states that RGB555 * pixels shall be stored in native CPU endianness. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "libavutil/internal.h" #include "libavutil/intreadwrite.h" #include "avcodec.h" #include "internal.h" typedef struct RpzaContext { AVCodecContext *avctx; AVFrame frame; const unsigned char *buf; int size; } RpzaContext; #define ADVANCE_BLOCK() \ { \ pixel_ptr += 4; \ if (pixel_ptr >= width) \ { \ pixel_ptr = 0; \ row_ptr += stride * 4; \ } \ total_blocks--; \ if (total_blocks < 0) \ { \ av_log(s->avctx, AV_LOG_ERROR, "warning: block counter just went negative (this should not happen)\n"); \ return; \ } \ } static void rpza_decode_stream(RpzaContext *s) { int width = s->avctx->width; int stride = s->frame.linesize[0] / 2; int row_inc = stride - 4; int stream_ptr = 0; int chunk_size; unsigned char opcode; int n_blocks; unsigned short colorA = 0, colorB; unsigned short color4[4]; unsigned char index, idx; unsigned short ta, tb; unsigned short *pixels = (unsigned short *)s->frame.data[0]; int row_ptr = 0; int pixel_ptr = -4; int block_ptr; int pixel_x, pixel_y; int total_blocks; /* First byte is always 0xe1. Warn if it's different */ if (s->buf[stream_ptr] != 0xe1) av_log(s->avctx, AV_LOG_ERROR, "First chunk byte is 0x%02x instead of 0xe1\n", s->buf[stream_ptr]); /* Get chunk size, ingnoring first byte */ chunk_size = AV_RB32(&s->buf[stream_ptr]) & 0x00FFFFFF; stream_ptr += 4; /* If length mismatch use size from MOV file and try to decode anyway */ if (chunk_size != s->size) av_log(s->avctx, AV_LOG_ERROR, "MOV chunk size != encoded chunk size; using MOV chunk size\n"); chunk_size = s->size; /* Number of 4x4 blocks in frame. */ total_blocks = ((s->avctx->width + 3) / 4) * ((s->avctx->height + 3) / 4); /* Process chunk data */ while (stream_ptr < chunk_size) { opcode = s->buf[stream_ptr++]; /* Get opcode */ n_blocks = (opcode & 0x1f) + 1; /* Extract block counter from opcode */ /* If opcode MSbit is 0, we need more data to decide what to do */ if ((opcode & 0x80) == 0) { colorA = (opcode << 8) | (s->buf[stream_ptr++]); opcode = 0; if ((s->buf[stream_ptr] & 0x80) != 0) { /* Must behave as opcode 110xxxxx, using colorA computed * above. Use fake opcode 0x20 to enter switch block at * the right place */ opcode = 0x20; n_blocks = 1; } } switch (opcode & 0xe0) { /* Skip blocks */ case 0x80: while (n_blocks--) { ADVANCE_BLOCK(); } break; /* Fill blocks with one color */ case 0xa0: colorA = AV_RB16 (&s->buf[stream_ptr]); stream_ptr += 2; while (n_blocks--) { ADVANCE_BLOCK() block_ptr = row_ptr + pixel_ptr; for (pixel_y = 0; pixel_y < 4; pixel_y++) { for (pixel_x = 0; pixel_x < 4; pixel_x++){ pixels[block_ptr] = colorA; block_ptr++; } block_ptr += row_inc; } } break; /* Fill blocks with 4 colors */ case 0xc0: colorA = AV_RB16 (&s->buf[stream_ptr]); stream_ptr += 2; case 0x20: colorB = AV_RB16 (&s->buf[stream_ptr]); stream_ptr += 2; /* sort out the colors */ color4[0] = colorB; color4[1] = 0; color4[2] = 0; color4[3] = colorA; /* red components */ ta = (colorA >> 10) & 0x1F; tb = (colorB >> 10) & 0x1F; color4[1] |= ((11 * ta + 21 * tb) >> 5) << 10; color4[2] |= ((21 * ta + 11 * tb) >> 5) << 10; /* green components */ ta = (colorA >> 5) & 0x1F; tb = (colorB >> 5) & 0x1F; color4[1] |= ((11 * ta + 21 * tb) >> 5) << 5; color4[2] |= ((21 * ta + 11 * tb) >> 5) << 5; /* blue components */ ta = colorA & 0x1F; tb = colorB & 0x1F; color4[1] |= ((11 * ta + 21 * tb) >> 5); color4[2] |= ((21 * ta + 11 * tb) >> 5); if (s->size - stream_ptr < n_blocks * 4) return; while (n_blocks--) { ADVANCE_BLOCK(); block_ptr = row_ptr + pixel_ptr; for (pixel_y = 0; pixel_y < 4; pixel_y++) { index = s->buf[stream_ptr++]; for (pixel_x = 0; pixel_x < 4; pixel_x++){ idx = (index >> (2 * (3 - pixel_x))) & 0x03; pixels[block_ptr] = color4[idx]; block_ptr++; } block_ptr += row_inc; } } break; /* Fill block with 16 colors */ case 0x00: if (s->size - stream_ptr < 16) return; ADVANCE_BLOCK(); block_ptr = row_ptr + pixel_ptr; for (pixel_y = 0; pixel_y < 4; pixel_y++) { for (pixel_x = 0; pixel_x < 4; pixel_x++){ /* We already have color of upper left pixel */ if ((pixel_y != 0) || (pixel_x !=0)) { colorA = AV_RB16 (&s->buf[stream_ptr]); stream_ptr += 2; } pixels[block_ptr] = colorA; block_ptr++; } block_ptr += row_inc; } break; /* Unknown opcode */ default: av_log(s->avctx, AV_LOG_ERROR, "Unknown opcode %d in rpza chunk." " Skip remaining %d bytes of chunk data.\n", opcode, chunk_size - stream_ptr); return; } /* Opcode switch */ } } static av_cold int rpza_decode_init(AVCodecContext *avctx) { RpzaContext *s = avctx->priv_data; s->avctx = avctx; avctx->pix_fmt = AV_PIX_FMT_RGB555; avcodec_get_frame_defaults(&s->frame); return 0; } static int rpza_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { const uint8_t *buf = avpkt->data; int buf_size = avpkt->size; RpzaContext *s = avctx->priv_data; int ret; s->buf = buf; s->size = buf_size; if ((ret = ff_reget_buffer(avctx, &s->frame)) < 0) return ret; rpza_decode_stream(s); if ((ret = av_frame_ref(data, &s->frame)) < 0) return ret; *got_frame = 1; /* always report that the buffer was completely consumed */ return buf_size; } static av_cold int rpza_decode_end(AVCodecContext *avctx) { RpzaContext *s = avctx->priv_data; av_frame_unref(&s->frame); return 0; } AVCodec ff_rpza_decoder = { .name = "rpza", .type = AVMEDIA_TYPE_VIDEO, .id = AV_CODEC_ID_RPZA, .priv_data_size = sizeof(RpzaContext), .init = rpza_decode_init, .close = rpza_decode_end, .decode = rpza_decode_frame, .capabilities = CODEC_CAP_DR1, .long_name = NULL_IF_CONFIG_SMALL("QuickTime video (RPZA)"), };
./CrossVul/dataset_final_sorted/CWE-119/c/good_5813_0
crossvul-cpp_data_good_4787_13
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % DDDD J V V U U % % D D J V V U U % % D D J V V U U % % D D J J V V U U % % DDDD JJJ V UUU % % % % % % Read DjVu Images. % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2015 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/colormap.h" #include "magick/constitute.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/list.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/pixel-accessor.h" #include "magick/quantum-private.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/module.h" #if defined(MAGICKCORE_DJVU_DELEGATE) #include <libdjvu/ddjvuapi.h> #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s D J V U % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsDJVU() returns MagickTrue if the image format type, identified by the % magick string, is DJVU. % % The format of the IsDJVU method is: % % MagickBooleanType IsDJVU(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 IsDJVU(const unsigned char *magick,const size_t length) { if (length < 8) return(MagickFalse); if (memcmp(magick,"AT&TFORM",8) == 0) return(MagickTrue); return(MagickFalse); } #if defined(MAGICKCORE_DJVU_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d D J V U I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadDJVUImage() reads DJVU image and returns it. It allocates the memory % necessary for the new Image structure and returns a pointer to the new % image or set of images. % % The format of the ReadDJVUImage method is: % % Image *ReadDJVUImage(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. % */ #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif typedef struct _LoadContext LoadContext; struct _LoadContext { ddjvu_context_t* context; ddjvu_document_t *document; ddjvu_page_t *page; int streamid; int pages; Image *image; }; #define BLOCKSIZE 65536 #if 0 static void pump_data(Image *image, LoadContext* lc) { int blocksize = BLOCKSIZE; char data[BLOCKSIZE]; int size; /* i might check for a condition! */ while ((size = (size_t) ReadBlob(image,(size_t) blocksize,data)) == blocksize) { ddjvu_stream_write(lc->document, lc->streamid, data, size); } if (size) ddjvu_stream_write(lc->document, lc->streamid, data, size); ddjvu_stream_close(lc->document, lc->streamid, 0); } #endif /* returns NULL only after all is delivered! */ static ddjvu_message_t* pump_data_until_message(LoadContext *lc,Image *image) /* ddjvu_context_t *context, type ddjvu_document_type_t */ { size_t blocksize = BLOCKSIZE; unsigned char data[BLOCKSIZE]; size_t size; ddjvu_message_t *message; /* i might check for a condition! */ size=0; while (!(message = ddjvu_message_peek(lc->context)) && (size = (size_t) ReadBlob(image,(size_t) blocksize,data)) == blocksize) { ddjvu_stream_write(lc->document, lc->streamid, (char *) data, size); } if (message) return message; if (size) ddjvu_stream_write(lc->document, lc->streamid, (char *) data, size); ddjvu_stream_close(lc->document, lc->streamid, 0); return NULL; } #define DEBUG 0 #if DEBUG static const char* message_tag_name(ddjvu_message_tag_t tag) { static char* names[] = { "ERROR", "INFO", "NEWSTREAM", "DOCINFO", "PAGEINFO", "RELAYOUT", "REDISPLAY", "CHUNK", "THUMBNAIL", "PROGRESS", }; if (tag <= DDJVU_PROGRESS) return names[tag]; else { /* bark! */ return 0; } } #endif /* write out nice info on the message, * and store in *user* data the info on progress. * */ int process_message(ddjvu_message_t *message) { #if 0 ddjvu_context_t* context= message->m_any.context; #endif if (! message) return(-1); #if DEBUG printf("*** %s: %s.\n",__FUNCTION__, message_tag_name(message->m_any.tag)); #endif switch (message->m_any.tag){ case DDJVU_DOCINFO: { ddjvu_document_t* document= message->m_any.document; /* ddjvu_document_decoding_status is set by libdjvu! */ /* we have some info on the document */ LoadContext *lc = (LoadContext *) ddjvu_document_get_user_data(document); lc->pages = ddjvu_document_get_pagenum(document); #if DEBUG printf("the doc has %d pages\n", ddjvu_document_get_pagenum(document)); #endif break; } case DDJVU_CHUNK: #if DEBUG printf("the name of the chunk is: %s\n", message->m_chunk.chunkid); #endif break; case DDJVU_RELAYOUT: case DDJVU_PAGEINFO: { #if 0 ddjvu_page_t* page = message->m_any.page; page_info* info = ddjvu_page_get_user_data(page); printf("page decoding status: %d %s%s%s\n", ddjvu_page_decoding_status(page), status_color, status_name(ddjvu_page_decoding_status(page)), color_reset); printf("the page LAYOUT changed: width x height: %d x %d @ %d dpi. Version %d, type %d\n", // printf("page info:\n width x height: %d x %d @ %d dpi, version %d, type %d\n", ddjvu_page_get_width(page), ddjvu_page_get_height(page), ddjvu_page_get_resolution(page), ddjvu_page_get_version(page), /* DDJVU_PAGETYPE_BITONAL */ ddjvu_page_get_type(page)); info->info = 1; #endif break; } case DDJVU_REDISPLAY: { #if 0 ddjvu_page_t* page = message->m_any.page; page_info* info = ddjvu_page_get_user_data(page); printf("the page can/should be REDISPLAYED\n"); info->display = 1; #endif break; } case DDJVU_PROGRESS: #if DEBUG printf("PROGRESS:\n"); #endif break; case DDJVU_ERROR: printf("simply ERROR!\n message:\t%s\nfunction:\t%s(file %s)\nlineno:\t%d\n", message->m_error.message, message->m_error.function, message->m_error.filename, message->m_error.lineno); break; case DDJVU_INFO: #if DEBUG printf("INFO: %s!\n", message->m_info.message); #endif break; default: printf("unexpected\n"); }; return(message->m_any.tag); } #if defined(__cplusplus) || defined(c_plusplus) } #endif #define RGB 1 /* * DjVu advertised readiness to provide bitmap: So get it! * we use the RGB format! */ static void get_page_image(LoadContext *lc, ddjvu_page_t *page, int x, int y, int w, int h, const ImageInfo *image_info ) { ddjvu_format_t *format; ddjvu_page_type_t type; Image *image; int ret, stride; unsigned char *q; ddjvu_rect_t rect; rect.x = x; rect.y = y; rect.w = (unsigned int) w; /* /10 */ rect.h = (unsigned int) h; /* /10 */ image = lc->image; type = ddjvu_page_get_type(lc->page); /* stride of this temporary buffer: */ stride = (type == DDJVU_PAGETYPE_BITONAL)? (image->columns + 7)/8 : image->columns *3; q = (unsigned char *) AcquireQuantumMemory(image->rows,stride); if (q == (unsigned char *) NULL) return; format = ddjvu_format_create( (type == DDJVU_PAGETYPE_BITONAL)?DDJVU_FORMAT_LSBTOMSB : DDJVU_FORMAT_RGB24, /* DDJVU_FORMAT_RGB24 * DDJVU_FORMAT_RGBMASK32*/ /* DDJVU_FORMAT_RGBMASK32 */ 0, NULL); #if 0 /* fixme: ThrowReaderException is a macro, which uses `exception' variable */ if (format == NULL) { abort(); /* ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); */ } #endif ddjvu_format_set_row_order(format, 1); ddjvu_format_set_y_direction(format, 1); ret = ddjvu_page_render(page, DDJVU_RENDER_COLOR, /* ddjvu_render_mode_t */ &rect, &rect, /* mmc: ?? */ format, stride, /* ?? */ (char*)q); (void) ret; ddjvu_format_release(format); if (type == DDJVU_PAGETYPE_BITONAL) { /* */ #if DEBUG printf("%s: expanding BITONAL page/image\n", __FUNCTION__); #endif register IndexPacket *indexes; size_t bit, byte; for (y=0; y < (ssize_t) image->rows; y++) { PixelPacket * o = QueueAuthenticPixels(image,0,y,image->columns,1,&image->exception); if (o == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); bit=0; byte=0; /* fixme: the non-aligned, last =<7 bits ! that's ok!!!*/ for (x= 0; x < (ssize_t) image->columns; x++) { if (bit == 0) byte= (size_t) q[(y * stride) + (x / 8)]; if (indexes != (IndexPacket *) NULL) SetPixelIndex(indexes+x,(IndexPacket) (((byte & 0x01) != 0) ? 0x00 : 0x01)); bit++; if (bit == 8) bit=0; byte>>=1; } if (SyncAuthenticPixels(image,&image->exception) == MagickFalse) break; } if (image->ping == MagickFalse) SyncImage(image); } else { #if DEBUG printf("%s: expanding PHOTO page/image\n", __FUNCTION__); #endif /* now transfer line-wise: */ ssize_t i; #if 0 /* old: */ char* r; #else register PixelPacket *r; unsigned char *s; #endif s=q; for (i = 0;i< (ssize_t) image->rows; i++) { #if DEBUG if (i % 1000 == 0) printf("%d\n",i); #endif r = QueueAuthenticPixels(image,0,i,image->columns,1,&image->exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(r,ScaleCharToQuantum(*s++)); SetPixelGreen(r,ScaleCharToQuantum(*s++)); SetPixelBlue(r,ScaleCharToQuantum(*s++)); r++; } (void) SyncAuthenticPixels(image,&image->exception); } } q=(unsigned char *) RelinquishMagickMemory(q); } #if defined(MAGICKCORE_DJVU_DELEGATE) #if 0 static int get_page_line(LoadContext *lc, int row, QuantumInfo* quantum_info) { ddjvu_format_t *format; int ret; size_t stride; unsigned char *q; ddjvu_rect_t rect, pagerect; rect.x = 0; rect.y = row; rect.w = lc->image->columns; /* /10 */ rect.h = 1; /* /10 */ pagerect.x = 0; pagerect.y = 0; pagerect.w = lc->image->columns; pagerect.h = lc->image->rows; format = ddjvu_format_create( #if RGB DDJVU_FORMAT_RGB24 #else DDJVU_FORMAT_GREY8 #endif , 0, NULL); ddjvu_format_set_row_order(format, 1); ddjvu_format_set_y_direction(format, 1); stride=1; #if RGB stride=3; #endif q = (unsigned char *) AcquireQuantumMemory(lc->image->columns,stride); ret = ddjvu_page_render(lc->page, DDJVU_RENDER_COLOR, /* ddjvu_render_mode_t */ &pagerect, &rect, /* mmc: ?? */ format, pagerect.w * 3, /* ?? */ (char*)q); ImportQuantumPixels(lc->image, (CacheView *) NULL, quantum_info, #if RGB RGBQuantum #else GrayQuantum #endif ,q,&lc->image->exception); q=(unsigned char *) RelinquishMagickMemory(q); ddjvu_format_release(format); return ret; } #endif #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d O n e D J V U I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadOneDJVUImage() reads a Portable Network Graphics (DJVU) image file % (minus the 8-byte signature) and returns it. It allocates the memory % necessary for the new Image structure and returns a pointer to the new % image. % % The format of the ReadOneDJVUImage method is: % % Image *ReadOneDJVUImage(MngInfo *mng_info, const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o mng_info: Specifies a pointer to a MngInfo structure. % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static inline double MagickMax(const double x,const double y) { if (x > y) return(x); return(y); } static Image *ReadOneDJVUImage(LoadContext* lc,const int pagenum, const ImageInfo *image_info,ExceptionInfo *exception) { ddjvu_page_type_t type; ddjvu_pageinfo_t info; ddjvu_message_t *message; Image *image; int logging; int tag; MagickBooleanType status; /* so, we know that the page is there! Get its dimension, and */ /* Read one DJVU image */ image = lc->image; /* register PixelPacket *q; */ logging=LogMagickEvent(CoderEvent,GetMagickModule(), " enter ReadOneDJVUImage()"); (void) logging; #if DEBUG printf("==== Loading the page %d\n", pagenum); #endif lc->page = ddjvu_page_create_by_pageno(lc->document, pagenum); /* 0? */ /* pump data untill the page is ready for rendering. */ tag=(-1); do { while ((message = ddjvu_message_peek(lc->context))) { tag=process_message(message); if (tag == 0) break; ddjvu_message_pop(lc->context); } /* fixme: maybe exit? */ /* if (lc->error) break; */ message = pump_data_until_message(lc,image); if (message) do { tag=process_message(message); if (tag == 0) break; ddjvu_message_pop(lc->context); } while ((message = ddjvu_message_peek(lc->context))); } while (!ddjvu_page_decoding_done(lc->page)); ddjvu_document_get_pageinfo(lc->document, pagenum, &info); image->x_resolution = (float) info.dpi; image->y_resolution =(float) info.dpi; if (image_info->density != (char *) NULL) { int flags; GeometryInfo geometry_info; /* Set rendering resolution. */ flags=ParseGeometry(image_info->density,&geometry_info); image->x_resolution=geometry_info.rho; image->y_resolution=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->y_resolution=image->x_resolution; info.width=(int) (info.width*image->x_resolution/info.dpi); info.height=(int) (info.height*image->y_resolution/info.dpi); info.dpi=(int) MagickMax(image->x_resolution,image->y_resolution); } type = ddjvu_page_get_type(lc->page); /* double -> float! */ /* image->gamma = (float)ddjvu_page_get_gamma(lc->page); */ /* mmc: set image->depth */ /* mmc: This from the type */ image->columns=(size_t) info.width; image->rows=(size_t) info.height; /* mmc: bitonal should be palettized, and compressed! */ if (type == DDJVU_PAGETYPE_BITONAL){ image->colorspace = GRAYColorspace; image->storage_class = PseudoClass; image->depth = 8UL; /* i only support that? */ image->colors= 2; if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } else { image->colorspace = RGBColorspace; image->storage_class = DirectClass; /* fixme: MAGICKCORE_QUANTUM_DEPTH ?*/ image->depth = 8UL; /* i only support that? */ image->matte = MagickTrue; /* is this useful? */ } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } #if DEBUG printf("now filling %.20g x %.20g\n",(double) image->columns,(double) image->rows); #endif #if 1 /* per_line */ /* q = QueueAuthenticPixels(image,0,0,image->columns,image->rows); */ get_page_image(lc, lc->page, 0, 0, info.width, info.height, image_info); #else int i; for (i = 0;i< image->rows; i++) { printf("%d\n",i); q = QueueAuthenticPixels(image,0,i,image->columns,1); get_page_line(lc, i, quantum_info); SyncAuthenticPixels(image); } #endif /* per_line */ #if DEBUG printf("END: finished filling %.20g x %.20g\n",(double) image->columns, (double) image->rows); #endif if (!image->ping) SyncImage(image); /* indexes=GetAuthenticIndexQueue(image); */ /* mmc: ??? Convert PNM pixels to runlength-encoded MIFF packets. */ /* image->colors = */ /* how is the line padding / stride? */ if (lc->page) { ddjvu_page_release(lc->page); lc->page = NULL; } /* image->page.y=mng_info->y_off[mng_info->object_id]; */ if (tag == 0) image=DestroyImage(image); return image; /* end of reading one DJVU page/image */ } #if 0 /* palette */ if (AcquireImageColormap(image,2) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Monochrome colormap. mmc: this the default! */ image->colormap[0].red=QuantumRange; image->colormap[0].green=QuantumRange; image->colormap[0].blue=QuantumRange; image->colormap[1].red=0; image->colormap[1].green=0; image->colormap[1].blue=0; #endif static void djvu_close_lc(LoadContext* lc) { if (lc->document) ddjvu_document_release(lc->document); if (lc->context) ddjvu_context_release(lc->context); if (lc->page) ddjvu_page_release(lc->page); RelinquishMagickMemory(lc); } static Image *ReadDJVUImage(const ImageInfo *image_info, ExceptionInfo *exception) { const char *url; ddjvu_message_t *message; Image *image, *images; int logging, use_cache; LoadContext *lc; MagickBooleanType status; register ssize_t i; /* * Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter ReadDJVUImage()"); (void) logging; image = AcquireImage(image_info); /* mmc: ?? */ lc = (LoadContext *) NULL; status = OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) ThrowReaderException(FileOpenError,"UnableToOpenFile"); /* Verify DJVU signature. */ #if 0 count = ReadBlob(image,8,(unsigned char *) magic_number); /* IsDJVU(const unsigned char *magick,const size_t length) */ if (memcmp(magic_number,"AT&TFORM",8) != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); #endif /* * Allocate a LoadContext structure. */ lc = (LoadContext *) AcquireMagickMemory(sizeof(*lc)); if (lc == NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* * Initialize members of the MngInfo structure. */ (void) ResetMagickMemory(lc,0,sizeof(LoadContext)); lc->image = image; lc->pages = 0; lc->context = ddjvu_context_create("ImageMagick djvu loader"); /* g_program_name */ ddjvu_cache_set_size(lc->context, 1); /* right? */ use_cache = 0; /* document: here we don't have a filename, but, for the sake of generality, a FILE* ! */ url="http://www.imagemagick.org/fake.djvu"; lc->document = ddjvu_document_create(lc->context, url, use_cache); /* don't cache */ ddjvu_document_set_user_data(lc->document, lc); /* now we wait the message-request for data: */ message = ddjvu_message_wait(lc->context); if (message->m_any.tag != DDJVU_NEWSTREAM) { /* fixme: the djvu context, document! */ ddjvu_document_release(lc->document); ddjvu_context_release(lc->context); RelinquishMagickMemory(lc); ThrowReaderException(ResourceLimitError,"Djvu initial message: unexpected type"); return NULL; /* error! */ }; lc->streamid = message->m_newstream.streamid; ddjvu_message_pop(lc->context); message = pump_data_until_message(lc,image); /* now process the messages: */ if (message) do { process_message(message); ddjvu_message_pop(lc->context); } while ((message = ddjvu_message_peek(lc->context))); /* fixme: i hope we have not read any messages pertinent(?) related to the page itself! */ while (lc->pages == 0) { message = ddjvu_message_wait(lc->context); process_message(message); ddjvu_message_pop(lc->context); } images=NewImageList(); i=0; if (image_info->number_scenes != 0) i=image_info->scene; for ( ; i < (ssize_t) lc->pages; i++) { image=ReadOneDJVUImage(lc,i,image_info,exception); if (image == (Image *) NULL) break; image->scene=i; AppendImageToList(&images,CloneImageList(image,exception)); images->extent=GetBlobSize(image); if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; } djvu_close_lc(lc); (void) CloseBlob(images); if (image != (Image *) NULL) image=DestroyImageList(image); #if 0 if ((image->page.width == 0) && (image->page.height == 0)) { image->page.width = image->columns+image->page.x; image->page.height = image->rows+image->page.y; } if (image->columns == 0 || image->rows == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadDJVUImage() with error."); ThrowReaderException(CorruptImageError,"CorruptImage"); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadDJVUImage()"); #endif return(GetFirstImageInList(images)); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r D J V U I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterDJVUImage() adds attributes for the DJVU 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 RegisterDJVUImage method is: % % size_t RegisterDJVUImage(void) % */ ModuleExport size_t RegisterDJVUImage(void) { char version[MaxTextExtent]; MagickInfo *entry; static const char *DJVUNote = { "See http://www.djvuzone.org/ for details about the DJVU format. The\n" "DJVU 1.2 specification is available there and at\n" "ftp://swrinde.nde.swri.edu/pub/djvu/documents/." }; *version='\0'; #if defined(DJVU_LIBDJVU_VER_STRING) (void) ConcatenateMagickString(version,"libdjvu ",MaxTextExtent); (void) ConcatenateMagickString(version,DJVU_LIBDJVU_VER_STRING,MaxTextExtent); #endif entry=SetMagickInfo("DJVU"); #if defined(MAGICKCORE_DJVU_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadDJVUImage; #endif entry->raw=MagickTrue; entry->magick=(IsImageFormatHandler *) IsDJVU; entry->adjoin=MagickFalse; entry->thread_support=MagickTrue; entry->description=AcquireString("D�j� vu"); entry->module=AcquireString("DJVU"); if (*version != '\0') entry->version=AcquireString(version); entry->note=AcquireString(DJVUNote); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r D J V U I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterDJVUImage() removes format registrations made by the % DJVU module from the list of supported formats. % % The format of the UnregisterDJVUImage method is: % % UnregisterDJVUImage(void) % */ ModuleExport void UnregisterDJVUImage(void) { (void) UnregisterMagickInfo("DJVU"); }
./CrossVul/dataset_final_sorted/CWE-119/c/good_4787_13
crossvul-cpp_data_good_4787_12
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % DDDD IIIII BBBB % % D D I B B % % D D I BBBB % % D D I B B % % DDDD IIIII BBBB % % % % % % Read/Write Windows DIB Image Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2015 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colormap.h" #include "magick/colormap-private.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/draw.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/geometry.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/log.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/pixel-accessor.h" #include "magick/quantum-private.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/module.h" #include "magick/transform.h" /* Typedef declarations. */ typedef struct _DIBInfo { size_t size; ssize_t width, height; unsigned short planes, bits_per_pixel; size_t compression, image_size, x_pixels, y_pixels, number_colors, red_mask, green_mask, blue_mask, alpha_mask, colors_important; ssize_t colorspace; PointInfo red_primary, green_primary, blue_primary, gamma_scale; } DIBInfo; /* Forward declarations. */ static MagickBooleanType WriteDIBImage(const ImageInfo *,Image *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e c o d e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DecodeImage unpacks the packed image pixels into runlength-encoded % pixel packets. % % The format of the DecodeImage method is: % % MagickBooleanType DecodeImage(Image *image, % const MagickBooleanType compression,unsigned char *pixels) % % A description of each parameter follows: % % o image: the address of a structure of type Image. % % o compression: A value of 1 means the compressed pixels are runlength % encoded for a 256-color bitmap. A value of 2 means a 16-color bitmap. % % o pixels: The address of a byte (8 bits) array of pixel data created by % the decoding process. % */ static inline size_t MagickMin(const size_t x,const size_t y) { if (x < y) return(x); return(y); } static MagickBooleanType DecodeImage(Image *image, const MagickBooleanType compression,unsigned char *pixels) { #if !defined(MAGICKCORE_WINDOWS_SUPPORT) || defined(__MINGW32__) || defined(__MINGW64__) #define BI_RGB 0 #define BI_RLE8 1 #define BI_RLE4 2 #define BI_BITFIELDS 3 #endif int count; ssize_t y; register ssize_t i, x; register unsigned char *p, *q; unsigned char byte; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(pixels != (unsigned char *) NULL); (void) ResetMagickMemory(pixels,0,(size_t) image->columns*image->rows* sizeof(*pixels)); byte=0; x=0; p=pixels; q=pixels+(size_t) image->columns*image->rows; for (y=0; y < (ssize_t) image->rows; ) { if ((p < pixels) || (p >= q)) break; count=ReadBlobByte(image); if (count == EOF) break; if (count != 0) { count=(int) MagickMin((size_t) count,(size_t) (q-p)); /* Encoded mode. */ byte=(unsigned char) ReadBlobByte(image); if (compression == BI_RLE8) { for (i=0; i < count; i++) *p++=(unsigned char) byte; } else { for (i=0; i < count; i++) *p++=(unsigned char) ((i & 0x01) != 0 ? (byte & 0x0f) : ((byte >> 4) & 0x0f)); } x+=count; } else { /* Escape mode. */ count=ReadBlobByte(image); if (count == 0x01) return(MagickTrue); switch (count) { case 0x00: { /* End of line. */ x=0; y++; p=pixels+y*image->columns; break; } case 0x02: { /* Delta mode. */ x+=ReadBlobByte(image); y+=ReadBlobByte(image); p=pixels+y*image->columns+x; break; } default: { /* Absolute mode. */ count=(int) MagickMin((size_t) count,(size_t) (q-p)); if (compression == BI_RLE8) for (i=0; i < count; i++) *p++=(unsigned char) ReadBlobByte(image); else for (i=0; i < count; i++) { if ((i & 0x01) == 0) byte=(unsigned char) ReadBlobByte(image); *p++=(unsigned char) ((i & 0x01) != 0 ? (byte & 0x0f) : ((byte >> 4) & 0x0f)); } x+=count; /* Read pad byte. */ if (compression == BI_RLE8) { if ((count & 0x01) != 0) (void) ReadBlobByte(image); } else if (((count & 0x03) == 1) || ((count & 0x03) == 2)) (void) ReadBlobByte(image); break; } } } if (SetImageProgress(image,LoadImageTag,y,image->rows) == MagickFalse) break; } (void) ReadBlobByte(image); /* end of line */ (void) ReadBlobByte(image); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E n c o d e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % EncodeImage compresses pixels using a runlength encoded format. % % The format of the EncodeImage method is: % % static MagickBooleanType EncodeImage(Image *image, % const size_t bytes_per_line,const unsigned char *pixels, % unsigned char *compressed_pixels) % % A description of each parameter follows: % % o image: The image. % % o bytes_per_line: the number of bytes in a scanline of compressed pixels % % o pixels: The address of a byte (8 bits) array of pixel data created by % the compression process. % % o compressed_pixels: The address of a byte (8 bits) array of compressed % pixel data. % */ static size_t EncodeImage(Image *image,const size_t bytes_per_line, const unsigned char *pixels,unsigned char *compressed_pixels) { ssize_t y; register const unsigned char *p; register ssize_t i, x; register unsigned char *q; /* Runlength encode pixels. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(pixels != (const unsigned char *) NULL); assert(compressed_pixels != (unsigned char *) NULL); p=pixels; q=compressed_pixels; i=0; for (y=0; y < (ssize_t) image->rows; y++) { for (x=0; x < (ssize_t) bytes_per_line; x+=i) { /* Determine runlength. */ for (i=1; ((x+i) < (ssize_t) bytes_per_line); i++) if ((*(p+i) != *p) || (i == 255)) break; *q++=(unsigned char) i; *q++=(*p); p+=i; } /* End of line. */ *q++=0x00; *q++=0x00; if (SetImageProgress(image,LoadImageTag,y,image->rows) == MagickFalse) break; } /* End of bitmap. */ *q++=0; *q++=0x01; return((size_t) (q-compressed_pixels)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s D I B % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsDIB() returns MagickTrue if the image format type, identified by the % magick string, is DIB. % % The format of the IsDIB method is: % % MagickBooleanType IsDIB(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 IsDIB(const unsigned char *magick,const size_t length) { if (length < 2) return(MagickFalse); if (memcmp(magick,"\050\000",2) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d D I B I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadDIBImage() reads a Microsoft Windows bitmap 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 ReadDIBImage method is: % % image=ReadDIBImage(image_info) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static inline ssize_t MagickAbsoluteValue(const ssize_t x) { if (x < 0) return(-x); return(x); } static inline size_t MagickMax(const size_t x,const size_t y) { if (x > y) return(x); return(y); } static Image *ReadDIBImage(const ImageInfo *image_info,ExceptionInfo *exception) { DIBInfo dib_info; Image *image; IndexPacket index; ssize_t bit, y; MagickBooleanType status; MemoryInfo *pixel_info; register IndexPacket *indexes; register ssize_t x; register PixelPacket *q; register ssize_t i; register unsigned char *p; size_t bytes_per_line, length; ssize_t count; unsigned char *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Determine if this a DIB file. */ (void) ResetMagickMemory(&dib_info,0,sizeof(dib_info)); dib_info.size=ReadBlobLSBLong(image); if (dib_info.size != 40) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Microsoft Windows 3.X DIB image file. */ dib_info.width=(short) ReadBlobLSBLong(image); dib_info.height=(short) ReadBlobLSBLong(image); dib_info.planes=ReadBlobLSBShort(image); dib_info.bits_per_pixel=ReadBlobLSBShort(image); dib_info.compression=ReadBlobLSBLong(image); dib_info.image_size=ReadBlobLSBLong(image); dib_info.x_pixels=ReadBlobLSBLong(image); dib_info.y_pixels=ReadBlobLSBLong(image); dib_info.number_colors=ReadBlobLSBLong(image); dib_info.colors_important=ReadBlobLSBLong(image); if ((dib_info.compression == BI_BITFIELDS) && ((dib_info.bits_per_pixel == 16) || (dib_info.bits_per_pixel == 32))) { dib_info.red_mask=ReadBlobLSBLong(image); dib_info.green_mask=ReadBlobLSBLong(image); dib_info.blue_mask=ReadBlobLSBLong(image); } image->matte=dib_info.bits_per_pixel == 32 ? MagickTrue : MagickFalse; image->columns=(size_t) MagickAbsoluteValue(dib_info.width); image->rows=(size_t) MagickAbsoluteValue(dib_info.height); image->depth=8; if ((dib_info.number_colors != 0) || (dib_info.bits_per_pixel < 16)) { size_t one; image->storage_class=PseudoClass; image->colors=dib_info.number_colors; one=1; if (image->colors == 0) image->colors=one << dib_info.bits_per_pixel; } if (image_info->size) { RectangleInfo geometry; MagickStatusType flags; flags=ParseAbsoluteGeometry(image_info->size,&geometry); if (flags & WidthValue) if ((geometry.width != 0) && (geometry.width < image->columns)) image->columns=geometry.width; if (flags & HeightValue) if ((geometry.height != 0) && (geometry.height < image->rows)) image->rows=geometry.height; } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } if (image->storage_class == PseudoClass) { size_t length, packet_size; unsigned char *dib_colormap; /* Read DIB raster colormap. */ if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); length=(size_t) image->colors; dib_colormap=(unsigned char *) AcquireQuantumMemory(length, 4*sizeof(*dib_colormap)); if (dib_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); packet_size=4; count=ReadBlob(image,packet_size*image->colors,dib_colormap); if (count != (ssize_t) (packet_size*image->colors)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); p=dib_colormap; for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].blue=ScaleCharToQuantum(*p++); image->colormap[i].green=ScaleCharToQuantum(*p++); image->colormap[i].red=ScaleCharToQuantum(*p++); if (packet_size == 4) p++; } dib_colormap=(unsigned char *) RelinquishMagickMemory(dib_colormap); } /* Read image data. */ if (dib_info.compression == BI_RLE4) dib_info.bits_per_pixel<<=1; bytes_per_line=4*((image->columns*dib_info.bits_per_pixel+31)/32); length=bytes_per_line*image->rows; pixel_info=AcquireVirtualMemory((size_t) image->rows,MagickMax( bytes_per_line,image->columns+256UL)*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); if ((dib_info.compression == BI_RGB) || (dib_info.compression == BI_BITFIELDS)) { count=ReadBlob(image,length,pixels); if (count != (ssize_t) (length)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); } else { /* Convert run-length encoded raster pixels. */ status=DecodeImage(image,dib_info.compression ? MagickTrue : MagickFalse, pixels); if (status == MagickFalse) ThrowReaderException(CorruptImageError,"UnableToRunlengthDecodeImage"); } /* Initialize image structure. */ image->units=PixelsPerCentimeterResolution; image->x_resolution=(double) dib_info.x_pixels/100.0; image->y_resolution=(double) dib_info.y_pixels/100.0; /* Convert DIB raster image to pixel packets. */ switch (dib_info.bits_per_pixel) { case 1: { /* Convert bitmap scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < ((ssize_t) image->columns-7); x+=8) { for (bit=0; bit < 8; bit++) { index=(IndexPacket) ((*p) & (0x80 >> bit) ? 0x01 : 0x00); SetPixelIndex(indexes+x+bit,index); } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (ssize_t) (image->columns % 8); bit++) { index=(IndexPacket) ((*p) & (0x80 >> bit) ? 0x01 : 0x00); SetPixelIndex(indexes+x+bit,index); } p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,image->rows-y-1, image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image); break; } case 4: { /* Convert PseudoColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < ((ssize_t) image->columns-1); x+=2) { index=ConstrainColormapIndex(image,(*p >> 4) & 0xf); SetPixelIndex(indexes+x,index); index=ConstrainColormapIndex(image,*p & 0xf); SetPixelIndex(indexes+x+1,index); p++; } if ((image->columns % 2) != 0) { index=ConstrainColormapIndex(image,(*p >> 4) & 0xf); SetPixelIndex(indexes+x,index); p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,image->rows-y-1, image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image); break; } case 8: { /* Convert PseudoColor scanline. */ if ((dib_info.compression == BI_RLE8) || (dib_info.compression == BI_RLE4)) bytes_per_line=image->columns; for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { index=ConstrainColormapIndex(image,*p); SetPixelIndex(indexes+x,index); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,image->rows-y-1, image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image); break; } case 16: { unsigned short word; /* Convert PseudoColor scanline. */ image->storage_class=DirectClass; if (dib_info.compression == BI_RLE8) bytes_per_line=2*image->columns; for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { word=(*p++); word|=(*p++ << 8); if (dib_info.red_mask == 0) { SetPixelRed(q,ScaleCharToQuantum(ScaleColor5to8( (unsigned char) ((word >> 10) & 0x1f)))); SetPixelGreen(q,ScaleCharToQuantum(ScaleColor5to8( (unsigned char) ((word >> 5) & 0x1f)))); SetPixelBlue(q,ScaleCharToQuantum(ScaleColor5to8( (unsigned char) (word & 0x1f)))); } else { SetPixelRed(q,ScaleCharToQuantum(ScaleColor5to8( (unsigned char) ((word >> 11) & 0x1f)))); SetPixelGreen(q,ScaleCharToQuantum(ScaleColor6to8( (unsigned char) ((word >> 5) & 0x3f)))); SetPixelBlue(q,ScaleCharToQuantum(ScaleColor5to8( (unsigned char) (word & 0x1f)))); } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,image->rows-y-1, image->rows); if (status == MagickFalse) break; } } break; } case 24: case 32: { /* Convert DirectColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelRed(q,ScaleCharToQuantum(*p++)); if (image->matte != MagickFalse) SetPixelOpacity(q,ScaleCharToQuantum(*p++)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,image->rows-y-1, image->rows); if (status == MagickFalse) break; } } break; } default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } pixel_info=RelinquishVirtualMemory(pixel_info); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); if (dib_info.height < 0) { Image *flipped_image; /* Correct image orientation. */ flipped_image=FlipImage(image,exception); if (flipped_image != (Image *) NULL) { DuplicateBlob(flipped_image,image); image=DestroyImage(image); image=flipped_image; } } (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r D I B I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterDIBImage() adds attributes for the DIB 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 RegisterDIBImage method is: % % size_t RegisterDIBImage(void) % */ ModuleExport size_t RegisterDIBImage(void) { MagickInfo *entry; entry=SetMagickInfo("DIB"); entry->decoder=(DecodeImageHandler *) ReadDIBImage; entry->encoder=(EncodeImageHandler *) WriteDIBImage; entry->magick=(IsImageFormatHandler *) IsDIB; entry->adjoin=MagickFalse; entry->stealth=MagickTrue; entry->description=ConstantString( "Microsoft Windows 3.X Packed Device-Independent Bitmap"); entry->module=ConstantString("DIB"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r D I B I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterDIBImage() removes format registrations made by the % DIB module from the list of supported formats. % % The format of the UnregisterDIBImage method is: % % UnregisterDIBImage(void) % */ ModuleExport void UnregisterDIBImage(void) { (void) UnregisterMagickInfo("DIB"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e D I B I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteDIBImage() writes an image in Microsoft Windows bitmap encoded % image format. % % The format of the WriteDIBImage method is: % % MagickBooleanType WriteDIBImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % */ static MagickBooleanType WriteDIBImage(const ImageInfo *image_info,Image *image) { DIBInfo dib_info; MagickBooleanType status; register const IndexPacket *indexes; register const PixelPacket *p; register ssize_t i, x; register unsigned char *q; size_t bytes_per_line; ssize_t y; unsigned char *dib_data, *pixels; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); /* Initialize DIB raster file header. */ (void) TransformImageColorspace(image,sRGBColorspace); if (image->storage_class == DirectClass) { /* Full color DIB raster. */ dib_info.number_colors=0; dib_info.bits_per_pixel=(unsigned short) (image->matte ? 32 : 24); } else { /* Colormapped DIB raster. */ dib_info.bits_per_pixel=8; if (image_info->depth > 8) dib_info.bits_per_pixel=16; if (IsMonochromeImage(image,&image->exception) != MagickFalse) dib_info.bits_per_pixel=1; dib_info.number_colors=(dib_info.bits_per_pixel == 16) ? 0 : (1UL << dib_info.bits_per_pixel); } bytes_per_line=4*((image->columns*dib_info.bits_per_pixel+31)/32); dib_info.size=40; dib_info.width=(ssize_t) image->columns; dib_info.height=(ssize_t) image->rows; dib_info.planes=1; dib_info.compression=(size_t) (dib_info.bits_per_pixel == 16 ? BI_BITFIELDS : BI_RGB); dib_info.image_size=bytes_per_line*image->rows; dib_info.x_pixels=75*39; dib_info.y_pixels=75*39; switch (image->units) { case UndefinedResolution: case PixelsPerInchResolution: { dib_info.x_pixels=(size_t) (100.0*image->x_resolution/2.54); dib_info.y_pixels=(size_t) (100.0*image->y_resolution/2.54); break; } case PixelsPerCentimeterResolution: { dib_info.x_pixels=(size_t) (100.0*image->x_resolution); dib_info.y_pixels=(size_t) (100.0*image->y_resolution); break; } } dib_info.colors_important=dib_info.number_colors; /* Convert MIFF to DIB raster pixels. */ pixels=(unsigned char *) AcquireQuantumMemory(dib_info.image_size, sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) ResetMagickMemory(pixels,0,dib_info.image_size); switch (dib_info.bits_per_pixel) { case 1: { register unsigned char bit, byte; /* Convert PseudoClass image to a DIB monochrome image. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); q=pixels+(image->rows-y-1)*bytes_per_line; bit=0; byte=0; for (x=0; x < (ssize_t) image->columns; x++) { byte<<=1; byte|=GetPixelIndex(indexes+x) != 0 ? 0x01 : 0x00; bit++; if (bit == 8) { *q++=byte; bit=0; byte=0; } p++; } if (bit != 0) { *q++=(unsigned char) (byte << (8-bit)); x++; } for (x=(ssize_t) (image->columns+7)/8; x < (ssize_t) bytes_per_line; x++) *q++=0x00; status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } break; } case 8: { /* Convert PseudoClass packet to DIB pixel. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); q=pixels+(image->rows-y-1)*bytes_per_line; for (x=0; x < (ssize_t) image->columns; x++) *q++=(unsigned char) GetPixelIndex(indexes+x); for ( ; x < (ssize_t) bytes_per_line; x++) *q++=0x00; status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } break; } case 16: { unsigned short word; /* Convert PseudoClass packet to DIB pixel. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; q=pixels+(image->rows-y-1)*bytes_per_line; for (x=0; x < (ssize_t) image->columns; x++) { word=(unsigned short) ((ScaleColor8to5((unsigned char) ScaleQuantumToChar(GetPixelRed(p))) << 11) | (ScaleColor8to6((unsigned char) ScaleQuantumToChar( GetPixelGreen(p))) << 5) | (ScaleColor8to5((unsigned char) ScaleQuantumToChar((unsigned char) GetPixelBlue(p)) << 0))); *q++=(unsigned char)(word & 0xff); *q++=(unsigned char)(word >> 8); p++; } for (x=(ssize_t) (2*image->columns); x < (ssize_t) bytes_per_line; x++) *q++=0x00; status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } break; } case 24: case 32: { /* Convert DirectClass packet to DIB RGB pixel. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; q=pixels+(image->rows-y-1)*bytes_per_line; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelBlue(p)); *q++=ScaleQuantumToChar(GetPixelGreen(p)); *q++=ScaleQuantumToChar(GetPixelRed(p)); if (image->matte != MagickFalse) *q++=ScaleQuantumToChar(GetPixelOpacity(p)); p++; } if (dib_info.bits_per_pixel == 24) for (x=(ssize_t) (3*image->columns); x < (ssize_t) bytes_per_line; x++) *q++=0x00; status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } break; } } if (dib_info.bits_per_pixel == 8) if (image_info->compression != NoCompression) { size_t length; /* Convert run-length encoded raster pixels. */ length=2UL*(bytes_per_line+2UL)+2UL; dib_data=(unsigned char *) AcquireQuantumMemory(length, (image->rows+2UL)*sizeof(*dib_data)); if (dib_data == (unsigned char *) NULL) { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } dib_info.image_size=(size_t) EncodeImage(image,bytes_per_line, pixels,dib_data); pixels=(unsigned char *) RelinquishMagickMemory(pixels); pixels=dib_data; dib_info.compression = BI_RLE8; } /* Write DIB header. */ (void) WriteBlobLSBLong(image,(unsigned int) dib_info.size); (void) WriteBlobLSBLong(image,dib_info.width); (void) WriteBlobLSBLong(image,(unsigned short) dib_info.height); (void) WriteBlobLSBShort(image,(unsigned short) dib_info.planes); (void) WriteBlobLSBShort(image,dib_info.bits_per_pixel); (void) WriteBlobLSBLong(image,(unsigned int) dib_info.compression); (void) WriteBlobLSBLong(image,(unsigned int) dib_info.image_size); (void) WriteBlobLSBLong(image,(unsigned int) dib_info.x_pixels); (void) WriteBlobLSBLong(image,(unsigned int) dib_info.y_pixels); (void) WriteBlobLSBLong(image,(unsigned int) dib_info.number_colors); (void) WriteBlobLSBLong(image,(unsigned int) dib_info.colors_important); if (image->storage_class == PseudoClass) { if (dib_info.bits_per_pixel <= 8) { unsigned char *dib_colormap; /* Dump colormap to file. */ dib_colormap=(unsigned char *) AcquireQuantumMemory((size_t) (1UL << dib_info.bits_per_pixel),4*sizeof(*dib_colormap)); if (dib_colormap == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); q=dib_colormap; for (i=0; i < (ssize_t) MagickMin(image->colors,dib_info.number_colors); i++) { *q++=ScaleQuantumToChar(image->colormap[i].blue); *q++=ScaleQuantumToChar(image->colormap[i].green); *q++=ScaleQuantumToChar(image->colormap[i].red); *q++=(Quantum) 0x0; } for ( ; i < (ssize_t) (1L << dib_info.bits_per_pixel); i++) { *q++=(Quantum) 0x0; *q++=(Quantum) 0x0; *q++=(Quantum) 0x0; *q++=(Quantum) 0x0; } (void) WriteBlob(image,(size_t) (4*(1 << dib_info.bits_per_pixel)), dib_colormap); dib_colormap=(unsigned char *) RelinquishMagickMemory(dib_colormap); } else if ((dib_info.bits_per_pixel == 16) && (dib_info.compression == BI_BITFIELDS)) { (void) WriteBlobLSBLong(image,0xf800); (void) WriteBlobLSBLong(image,0x07e0); (void) WriteBlobLSBLong(image,0x001f); } } (void) WriteBlob(image,dib_info.image_size,pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); (void) CloseBlob(image); return(MagickTrue); }
./CrossVul/dataset_final_sorted/CWE-119/c/good_4787_12
crossvul-cpp_data_good_339_7
/* * sc.c: General functions * * Copyright (C) 2001, 2002 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 <stdio.h> #include <ctype.h> #include <stdlib.h> #include <string.h> #include <assert.h> #ifdef HAVE_SYS_MMAN_H #include <sys/mman.h> #endif #ifdef ENABLE_OPENSSL #include <openssl/crypto.h> /* for OPENSSL_cleanse */ #endif #include "internal.h" #ifdef PACKAGE_VERSION static const char *sc_version = PACKAGE_VERSION; #else static const char *sc_version = "(undef)"; #endif const char *sc_get_version(void) { return sc_version; } int sc_hex_to_bin(const char *in, u8 *out, size_t *outlen) { int err = SC_SUCCESS; size_t left, count = 0, in_len; if (in == NULL || out == NULL || outlen == NULL) { return SC_ERROR_INVALID_ARGUMENTS; } left = *outlen; in_len = strlen(in); while (*in != '\0') { int byte = 0, nybbles = 2; while (nybbles-- && *in && *in != ':' && *in != ' ') { char c; byte <<= 4; c = *in++; if ('0' <= c && c <= '9') c -= '0'; else if ('a' <= c && c <= 'f') c = c - 'a' + 10; else if ('A' <= c && c <= 'F') c = c - 'A' + 10; else { err = SC_ERROR_INVALID_ARGUMENTS; goto out; } byte |= c; } /* Detect premature end of string before byte is complete */ if (in_len > 1 && *in == '\0' && nybbles >= 0) { err = SC_ERROR_INVALID_ARGUMENTS; break; } if (*in == ':' || *in == ' ') in++; if (left <= 0) { err = SC_ERROR_BUFFER_TOO_SMALL; break; } out[count++] = (u8) byte; left--; } out: *outlen = count; return err; } int sc_bin_to_hex(const u8 *in, size_t in_len, char *out, size_t out_len, int in_sep) { unsigned int n, sep_len; char *pos, *end, sep; sep = (char)in_sep; sep_len = sep > 0 ? 1 : 0; pos = out; end = out + out_len; for (n = 0; n < in_len; n++) { if (pos + 3 + sep_len >= end) return SC_ERROR_BUFFER_TOO_SMALL; if (n && sep_len) *pos++ = sep; sprintf(pos, "%02x", in[n]); pos += 2; } *pos = '\0'; return SC_SUCCESS; } /* * Right trim all non-printable characters */ size_t sc_right_trim(u8 *buf, size_t len) { size_t i; if (!buf) return 0; if (len > 0) { for(i = len-1; i > 0; i--) { if(!isprint(buf[i])) { buf[i] = '\0'; len--; continue; } break; } } return len; } u8 *ulong2bebytes(u8 *buf, unsigned long x) { if (buf != NULL) { buf[3] = (u8) (x & 0xff); buf[2] = (u8) ((x >> 8) & 0xff); buf[1] = (u8) ((x >> 16) & 0xff); buf[0] = (u8) ((x >> 24) & 0xff); } return buf; } u8 *ushort2bebytes(u8 *buf, unsigned short x) { if (buf != NULL) { buf[1] = (u8) (x & 0xff); buf[0] = (u8) ((x >> 8) & 0xff); } return buf; } unsigned long bebytes2ulong(const u8 *buf) { if (buf == NULL) return 0UL; return (unsigned long) (buf[0] << 24 | buf[1] << 16 | buf[2] << 8 | buf[3]); } unsigned short bebytes2ushort(const u8 *buf) { if (buf == NULL) return 0U; return (unsigned short) (buf[0] << 8 | buf[1]); } unsigned short lebytes2ushort(const u8 *buf) { if (buf == NULL) return 0U; return (unsigned short)buf[1] << 8 | (unsigned short)buf[0]; } void sc_init_oid(struct sc_object_id *oid) { int ii; if (!oid) return; for (ii=0; ii<SC_MAX_OBJECT_ID_OCTETS; ii++) oid->value[ii] = -1; } int sc_format_oid(struct sc_object_id *oid, const char *in) { int ii, ret = SC_ERROR_INVALID_ARGUMENTS; const char *p; char *q; if (oid == NULL || in == NULL) return SC_ERROR_INVALID_ARGUMENTS; sc_init_oid(oid); p = in; for (ii=0; ii < SC_MAX_OBJECT_ID_OCTETS; ii++) { oid->value[ii] = strtol(p, &q, 10); if (!*q) break; if (!(q[0] == '.' && isdigit(q[1]))) goto out; p = q + 1; } if (!sc_valid_oid(oid)) goto out; ret = SC_SUCCESS; out: if (ret) sc_init_oid(oid); return ret; } int sc_compare_oid(const struct sc_object_id *oid1, const struct sc_object_id *oid2) { int i; if (oid1 == NULL || oid2 == NULL) { return SC_ERROR_INVALID_ARGUMENTS; } for (i = 0; i < SC_MAX_OBJECT_ID_OCTETS; i++) { if (oid1->value[i] != oid2->value[i]) return 0; if (oid1->value[i] == -1) break; } return 1; } int sc_valid_oid(const struct sc_object_id *oid) { int ii; if (!oid) return 0; if (oid->value[0] == -1 || oid->value[1] == -1) return 0; if (oid->value[0] > 2 || oid->value[1] > 39) return 0; for (ii=0;ii<SC_MAX_OBJECT_ID_OCTETS;ii++) if (oid->value[ii]) break; if (ii==SC_MAX_OBJECT_ID_OCTETS) return 0; return 1; } int sc_detect_card_presence(sc_reader_t *reader) { int r; LOG_FUNC_CALLED(reader->ctx); if (reader->ops->detect_card_presence == NULL) LOG_FUNC_RETURN(reader->ctx, SC_ERROR_NOT_SUPPORTED); r = reader->ops->detect_card_presence(reader); LOG_FUNC_RETURN(reader->ctx, r); } int sc_path_set(sc_path_t *path, int type, const u8 *id, size_t id_len, int idx, int count) { if (path == NULL || id == NULL || id_len == 0 || id_len > SC_MAX_PATH_SIZE) return SC_ERROR_INVALID_ARGUMENTS; memset(path, 0, sizeof(*path)); memcpy(path->value, id, id_len); path->len = id_len; path->type = type; path->index = idx; path->count = count; return SC_SUCCESS; } void sc_format_path(const char *str, sc_path_t *path) { int type = SC_PATH_TYPE_PATH; if (path) { memset(path, 0, sizeof(*path)); if (*str == 'i' || *str == 'I') { type = SC_PATH_TYPE_FILE_ID; str++; } path->len = sizeof(path->value); if (sc_hex_to_bin(str, path->value, &path->len) >= 0) { path->type = type; } path->count = -1; } } int sc_append_path(sc_path_t *dest, const sc_path_t *src) { return sc_concatenate_path(dest, dest, src); } int sc_append_path_id(sc_path_t *dest, const u8 *id, size_t idlen) { if (dest->len + idlen > SC_MAX_PATH_SIZE) return SC_ERROR_INVALID_ARGUMENTS; memcpy(dest->value + dest->len, id, idlen); dest->len += idlen; return SC_SUCCESS; } int sc_append_file_id(sc_path_t *dest, unsigned int fid) { u8 id[2] = { fid >> 8, fid & 0xff }; return sc_append_path_id(dest, id, 2); } int sc_concatenate_path(sc_path_t *d, const sc_path_t *p1, const sc_path_t *p2) { sc_path_t tpath; if (d == NULL || p1 == NULL || p2 == NULL) return SC_ERROR_INVALID_ARGUMENTS; if (p1->type == SC_PATH_TYPE_DF_NAME || p2->type == SC_PATH_TYPE_DF_NAME) /* we do not support concatenation of AIDs at the moment */ return SC_ERROR_NOT_SUPPORTED; if (p1->len + p2->len > SC_MAX_PATH_SIZE) return SC_ERROR_INVALID_ARGUMENTS; memset(&tpath, 0, sizeof(sc_path_t)); memcpy(tpath.value, p1->value, p1->len); memcpy(tpath.value + p1->len, p2->value, p2->len); tpath.len = p1->len + p2->len; tpath.type = SC_PATH_TYPE_PATH; /* use 'index' and 'count' entry of the second path object */ tpath.index = p2->index; tpath.count = p2->count; /* the result is currently always as path */ tpath.type = SC_PATH_TYPE_PATH; *d = tpath; return SC_SUCCESS; } const char *sc_print_path(const sc_path_t *path) { static char buffer[SC_MAX_PATH_STRING_SIZE + SC_MAX_AID_STRING_SIZE]; if (sc_path_print(buffer, sizeof(buffer), path) != SC_SUCCESS) buffer[0] = '\0'; return buffer; } int sc_path_print(char *buf, size_t buflen, const sc_path_t *path) { size_t i; if (buf == NULL || path == NULL) return SC_ERROR_INVALID_ARGUMENTS; if (buflen < path->len * 2 + path->aid.len * 2 + 1) return SC_ERROR_BUFFER_TOO_SMALL; buf[0] = '\0'; if (path->aid.len) { for (i = 0; i < path->aid.len; i++) snprintf(buf + strlen(buf), buflen - strlen(buf), "%02x", path->aid.value[i]); snprintf(buf + strlen(buf), buflen - strlen(buf), "::"); } for (i = 0; i < path->len; i++) snprintf(buf + strlen(buf), buflen - strlen(buf), "%02x", path->value[i]); if (!path->aid.len && path->type == SC_PATH_TYPE_DF_NAME) snprintf(buf + strlen(buf), buflen - strlen(buf), "::"); return SC_SUCCESS; } int sc_compare_path(const sc_path_t *path1, const sc_path_t *path2) { return path1->len == path2->len && !memcmp(path1->value, path2->value, path1->len); } int sc_compare_path_prefix(const sc_path_t *prefix, const sc_path_t *path) { sc_path_t tpath; if (prefix->len > path->len) return 0; tpath = *path; tpath.len = prefix->len; return sc_compare_path(&tpath, prefix); } const sc_path_t *sc_get_mf_path(void) { static const sc_path_t mf_path = { {0x3f, 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 2, 0, 0, SC_PATH_TYPE_PATH, {{0},0} }; return &mf_path; } int sc_file_add_acl_entry(sc_file_t *file, unsigned int operation, unsigned int method, unsigned long key_ref) { sc_acl_entry_t *p, *_new; if (file == NULL || operation >= SC_MAX_AC_OPS) { return SC_ERROR_INVALID_ARGUMENTS; } switch (method) { case SC_AC_NEVER: sc_file_clear_acl_entries(file, operation); file->acl[operation] = (sc_acl_entry_t *) 1; return SC_SUCCESS; case SC_AC_NONE: sc_file_clear_acl_entries(file, operation); file->acl[operation] = (sc_acl_entry_t *) 2; return SC_SUCCESS; case SC_AC_UNKNOWN: sc_file_clear_acl_entries(file, operation); file->acl[operation] = (sc_acl_entry_t *) 3; return SC_SUCCESS; default: /* NONE and UNKNOWN get zapped when a new AC is added. * If the ACL is NEVER, additional entries will be * dropped silently. */ if (file->acl[operation] == (sc_acl_entry_t *) 1) return SC_SUCCESS; if (file->acl[operation] == (sc_acl_entry_t *) 2 || file->acl[operation] == (sc_acl_entry_t *) 3) file->acl[operation] = NULL; } /* If the entry is already present (e.g. due to the mapping) * of the card's AC with OpenSC's), don't add it again. */ for (p = file->acl[operation]; p != NULL; p = p->next) { if ((p->method == method) && (p->key_ref == key_ref)) return SC_SUCCESS; } _new = malloc(sizeof(sc_acl_entry_t)); if (_new == NULL) return SC_ERROR_OUT_OF_MEMORY; _new->method = method; _new->key_ref = key_ref; _new->next = NULL; p = file->acl[operation]; if (p == NULL) { file->acl[operation] = _new; return SC_SUCCESS; } while (p->next != NULL) p = p->next; p->next = _new; return SC_SUCCESS; } const sc_acl_entry_t * sc_file_get_acl_entry(const sc_file_t *file, unsigned int operation) { sc_acl_entry_t *p; static const sc_acl_entry_t e_never = { SC_AC_NEVER, SC_AC_KEY_REF_NONE, {{0, 0, 0, {0}}}, NULL }; static const sc_acl_entry_t e_none = { SC_AC_NONE, SC_AC_KEY_REF_NONE, {{0, 0, 0, {0}}}, NULL }; static const sc_acl_entry_t e_unknown = { SC_AC_UNKNOWN, SC_AC_KEY_REF_NONE, {{0, 0, 0, {0}}}, NULL }; if (file == NULL || operation >= SC_MAX_AC_OPS) { return NULL; } p = file->acl[operation]; if (p == (sc_acl_entry_t *) 1) return &e_never; if (p == (sc_acl_entry_t *) 2) return &e_none; if (p == (sc_acl_entry_t *) 3) return &e_unknown; return file->acl[operation]; } void sc_file_clear_acl_entries(sc_file_t *file, unsigned int operation) { sc_acl_entry_t *e; if (file == NULL || operation >= SC_MAX_AC_OPS) { return; } e = file->acl[operation]; if (e == (sc_acl_entry_t *) 1 || e == (sc_acl_entry_t *) 2 || e == (sc_acl_entry_t *) 3) { file->acl[operation] = NULL; return; } while (e != NULL) { sc_acl_entry_t *tmp = e->next; free(e); e = tmp; } file->acl[operation] = NULL; } sc_file_t * sc_file_new(void) { sc_file_t *file = (sc_file_t *)calloc(1, sizeof(sc_file_t)); if (file == NULL) return NULL; file->magic = SC_FILE_MAGIC; return file; } void sc_file_free(sc_file_t *file) { unsigned int i; if (file == NULL || !sc_file_valid(file)) return; file->magic = 0; for (i = 0; i < SC_MAX_AC_OPS; i++) sc_file_clear_acl_entries(file, i); if (file->sec_attr) free(file->sec_attr); if (file->prop_attr) free(file->prop_attr); if (file->type_attr) free(file->type_attr); if (file->encoded_content) free(file->encoded_content); free(file); } void sc_file_dup(sc_file_t **dest, const sc_file_t *src) { sc_file_t *newf; const sc_acl_entry_t *e; unsigned int op; *dest = NULL; if (!sc_file_valid(src)) return; newf = sc_file_new(); if (newf == NULL) return; *dest = newf; memcpy(&newf->path, &src->path, sizeof(struct sc_path)); memcpy(&newf->name, &src->name, sizeof(src->name)); newf->namelen = src->namelen; newf->type = src->type; newf->shareable = src->shareable; newf->ef_structure = src->ef_structure; newf->size = src->size; newf->id = src->id; newf->status = src->status; for (op = 0; op < SC_MAX_AC_OPS; op++) { newf->acl[op] = NULL; e = sc_file_get_acl_entry(src, op); if (e != NULL) { if (sc_file_add_acl_entry(newf, op, e->method, e->key_ref) < 0) goto err; } } newf->record_length = src->record_length; newf->record_count = src->record_count; if (sc_file_set_sec_attr(newf, src->sec_attr, src->sec_attr_len) < 0) goto err; if (sc_file_set_prop_attr(newf, src->prop_attr, src->prop_attr_len) < 0) goto err; if (sc_file_set_type_attr(newf, src->type_attr, src->type_attr_len) < 0) goto err; if (sc_file_set_content(newf, src->encoded_content, src->encoded_content_len) < 0) goto err; return; err: sc_file_free(newf); *dest = NULL; } int sc_file_set_sec_attr(sc_file_t *file, const u8 *sec_attr, size_t sec_attr_len) { u8 *tmp; if (!sc_file_valid(file)) { return SC_ERROR_INVALID_ARGUMENTS; } if (sec_attr == NULL || sec_attr_len) { if (file->sec_attr != NULL) free(file->sec_attr); file->sec_attr = NULL; file->sec_attr_len = 0; return 0; } tmp = (u8 *) realloc(file->sec_attr, sec_attr_len); if (!tmp) { if (file->sec_attr) free(file->sec_attr); file->sec_attr = NULL; file->sec_attr_len = 0; return SC_ERROR_OUT_OF_MEMORY; } file->sec_attr = tmp; memcpy(file->sec_attr, sec_attr, sec_attr_len); file->sec_attr_len = sec_attr_len; return 0; } int sc_file_set_prop_attr(sc_file_t *file, const u8 *prop_attr, size_t prop_attr_len) { u8 *tmp; if (!sc_file_valid(file)) { return SC_ERROR_INVALID_ARGUMENTS; } if (prop_attr == NULL) { if (file->prop_attr != NULL) free(file->prop_attr); file->prop_attr = NULL; file->prop_attr_len = 0; return SC_SUCCESS; } tmp = (u8 *) realloc(file->prop_attr, prop_attr_len); if (!tmp) { if (file->prop_attr) free(file->prop_attr); file->prop_attr = NULL; file->prop_attr_len = 0; return SC_ERROR_OUT_OF_MEMORY; } file->prop_attr = tmp; memcpy(file->prop_attr, prop_attr, prop_attr_len); file->prop_attr_len = prop_attr_len; return SC_SUCCESS; } int sc_file_set_type_attr(sc_file_t *file, const u8 *type_attr, size_t type_attr_len) { u8 *tmp; if (!sc_file_valid(file)) { return SC_ERROR_INVALID_ARGUMENTS; } if (type_attr == NULL) { if (file->type_attr != NULL) free(file->type_attr); file->type_attr = NULL; file->type_attr_len = 0; return SC_SUCCESS; } tmp = (u8 *) realloc(file->type_attr, type_attr_len); if (!tmp) { if (file->type_attr) free(file->type_attr); file->type_attr = NULL; file->type_attr_len = 0; return SC_ERROR_OUT_OF_MEMORY; } file->type_attr = tmp; memcpy(file->type_attr, type_attr, type_attr_len); file->type_attr_len = type_attr_len; return SC_SUCCESS; } int sc_file_set_content(sc_file_t *file, const u8 *content, size_t content_len) { u8 *tmp; if (!sc_file_valid(file)) { return SC_ERROR_INVALID_ARGUMENTS; } if (content == NULL) { if (file->encoded_content != NULL) free(file->encoded_content); file->encoded_content = NULL; file->encoded_content_len = 0; return SC_SUCCESS; } tmp = (u8 *) realloc(file->encoded_content, content_len); if (!tmp) { if (file->encoded_content) free(file->encoded_content); file->encoded_content = NULL; file->encoded_content_len = 0; return SC_ERROR_OUT_OF_MEMORY; } file->encoded_content = tmp; memcpy(file->encoded_content, content, content_len); file->encoded_content_len = content_len; return SC_SUCCESS; } int sc_file_valid(const sc_file_t *file) { if (file == NULL) return 0; return file->magic == SC_FILE_MAGIC; } int _sc_parse_atr(sc_reader_t *reader) { u8 *p = reader->atr.value; int atr_len = (int) reader->atr.len; int n_hist, x; int tx[4] = {-1, -1, -1, -1}; int i, FI, DI; const int Fi_table[] = { 372, 372, 558, 744, 1116, 1488, 1860, -1, -1, 512, 768, 1024, 1536, 2048, -1, -1 }; const int f_table[] = { 40, 50, 60, 80, 120, 160, 200, -1, -1, 50, 75, 100, 150, 200, -1, -1 }; const int Di_table[] = { -1, 1, 2, 4, 8, 16, 32, -1, 12, 20, -1, -1, -1, -1, -1, -1 }; reader->atr_info.hist_bytes_len = 0; reader->atr_info.hist_bytes = NULL; if (atr_len == 0) { sc_log(reader->ctx, "empty ATR - card not present?\n"); return SC_ERROR_INTERNAL; } if (p[0] != 0x3B && p[0] != 0x3F) { sc_log(reader->ctx, "invalid sync byte in ATR: 0x%02X\n", p[0]); return SC_ERROR_INTERNAL; } n_hist = p[1] & 0x0F; x = p[1] >> 4; p += 2; atr_len -= 2; for (i = 0; i < 4 && atr_len > 0; i++) { if (x & (1 << i)) { tx[i] = *p; p++; atr_len--; } else tx[i] = -1; } if (tx[0] >= 0) { reader->atr_info.FI = FI = tx[0] >> 4; reader->atr_info.DI = DI = tx[0] & 0x0F; reader->atr_info.Fi = Fi_table[FI]; reader->atr_info.f = f_table[FI]; reader->atr_info.Di = Di_table[DI]; } else { reader->atr_info.Fi = -1; reader->atr_info.f = -1; reader->atr_info.Di = -1; } if (tx[2] >= 0) reader->atr_info.N = tx[3]; else reader->atr_info.N = -1; while (tx[3] > 0 && tx[3] & 0xF0 && atr_len > 0) { x = tx[3] >> 4; for (i = 0; i < 4 && atr_len > 0; i++) { if (x & (1 << i)) { tx[i] = *p; p++; atr_len--; } else tx[i] = -1; } } if (atr_len <= 0) return SC_SUCCESS; if (n_hist > atr_len) n_hist = atr_len; reader->atr_info.hist_bytes_len = n_hist; reader->atr_info.hist_bytes = p; return SC_SUCCESS; } void sc_mem_clear(void *ptr, size_t len) { if (len > 0) { #ifdef ENABLE_OPENSSL OPENSSL_cleanse(ptr, len); #else memset(ptr, 0, len); #endif } } int sc_mem_reverse(unsigned char *buf, size_t len) { unsigned char ch; size_t ii; if (!buf || !len) return SC_ERROR_INVALID_ARGUMENTS; for (ii = 0; ii < len / 2; ii++) { ch = *(buf + ii); *(buf + ii) = *(buf + len - 1 - ii); *(buf + len - 1 - ii) = ch; } return SC_SUCCESS; } static int sc_remote_apdu_allocate(struct sc_remote_data *rdata, struct sc_remote_apdu **new_rapdu) { struct sc_remote_apdu *rapdu = NULL, *rr; if (!rdata) return SC_ERROR_INVALID_ARGUMENTS; rapdu = calloc(1, sizeof(struct sc_remote_apdu)); if (rapdu == NULL) return SC_ERROR_OUT_OF_MEMORY; rapdu->apdu.data = &rapdu->sbuf[0]; rapdu->apdu.resp = &rapdu->rbuf[0]; rapdu->apdu.resplen = sizeof(rapdu->rbuf); if (new_rapdu) *new_rapdu = rapdu; if (rdata->data == NULL) { rdata->data = rapdu; rdata->length = 1; return SC_SUCCESS; } for (rr = rdata->data; rr->next; rr = rr->next) ; rr->next = rapdu; rdata->length++; return SC_SUCCESS; } static void sc_remote_apdu_free (struct sc_remote_data *rdata) { struct sc_remote_apdu *rapdu = NULL; if (!rdata) return; rapdu = rdata->data; while(rapdu) { struct sc_remote_apdu *rr = rapdu->next; free(rapdu); rapdu = rr; } } void sc_remote_data_init(struct sc_remote_data *rdata) { if (!rdata) return; memset(rdata, 0, sizeof(struct sc_remote_data)); rdata->alloc = sc_remote_apdu_allocate; rdata->free = sc_remote_apdu_free; } static unsigned long sc_CRC_tab32[256]; static int sc_CRC_tab32_initialized = 0; unsigned sc_crc32(const unsigned char *value, size_t len) { size_t ii, jj; unsigned long crc; unsigned long index, long_c; if (!sc_CRC_tab32_initialized) { for (ii=0; ii<256; ii++) { crc = (unsigned long) ii; for (jj=0; jj<8; jj++) { if ( crc & 0x00000001L ) crc = ( crc >> 1 ) ^ 0xEDB88320l; else crc = crc >> 1; } sc_CRC_tab32[ii] = crc; } sc_CRC_tab32_initialized = 1; } crc = 0xffffffffL; for (ii=0; ii<len; ii++) { long_c = 0x000000ffL & (unsigned long) (*(value + ii)); index = crc ^ long_c; crc = (crc >> 8) ^ sc_CRC_tab32[ index & 0xff ]; } crc ^= 0xffffffff; return crc%0xffff; } const u8 *sc_compacttlv_find_tag(const u8 *buf, size_t len, u8 tag, size_t *outlen) { if (buf != NULL) { size_t idx; u8 plain_tag = tag & 0xF0; size_t expected_len = tag & 0x0F; for (idx = 0; idx < len; idx++) { if ((buf[idx] & 0xF0) == plain_tag && idx + expected_len < len && (expected_len == 0 || expected_len == (buf[idx] & 0x0F))) { if (outlen != NULL) *outlen = buf[idx] & 0x0F; return buf + (idx + 1); } idx += (buf[idx] & 0x0F); } } return NULL; } /**************************** mutex functions ************************/ int sc_mutex_create(const sc_context_t *ctx, void **mutex) { if (ctx == NULL) return SC_ERROR_INVALID_ARGUMENTS; if (ctx->thread_ctx != NULL && ctx->thread_ctx->create_mutex != NULL) return ctx->thread_ctx->create_mutex(mutex); else return SC_SUCCESS; } int sc_mutex_lock(const sc_context_t *ctx, void *mutex) { if (ctx == NULL) return SC_ERROR_INVALID_ARGUMENTS; if (ctx->thread_ctx != NULL && ctx->thread_ctx->lock_mutex != NULL) return ctx->thread_ctx->lock_mutex(mutex); else return SC_SUCCESS; } int sc_mutex_unlock(const sc_context_t *ctx, void *mutex) { if (ctx == NULL) return SC_ERROR_INVALID_ARGUMENTS; if (ctx->thread_ctx != NULL && ctx->thread_ctx->unlock_mutex != NULL) return ctx->thread_ctx->unlock_mutex(mutex); else return SC_SUCCESS; } int sc_mutex_destroy(const sc_context_t *ctx, void *mutex) { if (ctx == NULL) return SC_ERROR_INVALID_ARGUMENTS; if (ctx->thread_ctx != NULL && ctx->thread_ctx->destroy_mutex != NULL) return ctx->thread_ctx->destroy_mutex(mutex); else return SC_SUCCESS; } unsigned long sc_thread_id(const sc_context_t *ctx) { if (ctx == NULL || ctx->thread_ctx == NULL || ctx->thread_ctx->thread_id == NULL) return 0UL; else return ctx->thread_ctx->thread_id(); }
./CrossVul/dataset_final_sorted/CWE-119/c/good_339_7
crossvul-cpp_data_good_1028_0
/* * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code * distributions retain the above copyright notice and this paragraph * in its entirety, and (2) distributions including binary code include * the above copyright notice and this paragraph in its entirety in * the documentation or other materials provided with the distribution. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND * WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT * LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE. * * Original code by Hannes Gredler (hannes@gredler.at) * Support for LMP service discovery extensions (defined by OIF UNI 1.0) * added by Manu Pathak (mapathak@cisco.com), May 2005 */ /* \summary: Link Management Protocol (LMP) printer */ /* specification: RFC 4204 */ /* OIF UNI 1.0: http://www.oiforum.com/public/documents/OIF-UNI-01.0.pdf */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include "netdissect.h" #include "extract.h" #include "addrtoname.h" #include "gmpls.h" static const char tstr[] = " [|LMP]"; /* * LMP common header * * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Vers | (Reserved) | Flags | Msg Type | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | LMP Length | (Reserved) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct lmp_common_header { uint8_t version_res[2]; uint8_t flags; uint8_t msg_type; uint8_t length[2]; uint8_t reserved[2]; }; #define LMP_VERSION 1 #define LMP_EXTRACT_VERSION(x) (((x)&0xf0)>>4) static const struct tok lmp_header_flag_values[] = { { 0x01, "Control Channel Down"}, { 0x02, "LMP restart"}, { 0, NULL} }; static const struct tok lmp_obj_te_link_flag_values[] = { { 0x01, "Fault Management Supported"}, { 0x02, "Link Verification Supported"}, { 0, NULL} }; static const struct tok lmp_obj_data_link_flag_values[] = { { 0x01, "Data Link Port"}, { 0x02, "Allocated for user traffic"}, { 0x04, "Failed link"}, { 0, NULL} }; static const struct tok lmp_obj_channel_status_values[] = { { 1, "Signal Okay"}, { 2, "Signal Degraded"}, { 3, "Signal Fail"}, { 0, NULL} }; static const struct tok lmp_obj_begin_verify_flag_values[] = { { 0x0001, "Verify all links"}, { 0x0002, "Data link type"}, { 0, NULL} }; static const struct tok lmp_obj_begin_verify_error_values[] = { { 0x01, "Link Verification Procedure Not supported"}, { 0x02, "Unwilling to verify"}, { 0x04, "Unsupported verification transport mechanism"}, { 0x08, "Link-Id configuration error"}, { 0x10, "Unknown object c-type"}, { 0, NULL} }; static const struct tok lmp_obj_link_summary_error_values[] = { { 0x01, "Unacceptable non-negotiable LINK-SUMMARY parameters"}, { 0x02, "Renegotiate LINK-SUMMARY parameters"}, { 0x04, "Invalid TE-LINK Object"}, { 0x08, "Invalid DATA-LINK Object"}, { 0x10, "Unknown TE-LINK Object c-type"}, { 0x20, "Unknown DATA-LINK Object c-type"}, { 0, NULL} }; /* Service Config Supported Protocols Flags */ static const struct tok lmp_obj_service_config_sp_flag_values[] = { { 0x01, "RSVP Supported"}, { 0x02, "LDP Supported"}, { 0, NULL} }; /* Service Config Client Port Service Attribute Transparency Flags */ static const struct tok lmp_obj_service_config_cpsa_tp_flag_values[] = { { 0x01, "Path/VC Overhead Transparency Supported"}, { 0x02, "Line/MS Overhead Transparency Supported"}, { 0x04, "Section/RS Overhead Transparency Supported"}, { 0, NULL} }; /* Service Config Client Port Service Attribute Contiguous Concatenation Types Flags */ static const struct tok lmp_obj_service_config_cpsa_cct_flag_values[] = { { 0x01, "Contiguous Concatenation Types Supported"}, { 0, NULL} }; /* Service Config Network Service Attributes Transparency Flags */ static const struct tok lmp_obj_service_config_nsa_transparency_flag_values[] = { { 0x01, "Standard SOH/RSOH Transparency Supported"}, { 0x02, "Standard LOH/MSOH Transparency Supported"}, { 0, NULL} }; /* Service Config Network Service Attributes TCM Monitoring Flags */ static const struct tok lmp_obj_service_config_nsa_tcm_flag_values[] = { { 0x01, "Transparent Tandem Connection Monitoring Supported"}, { 0, NULL} }; /* Network Service Attributes Network Diversity Flags */ static const struct tok lmp_obj_service_config_nsa_network_diversity_flag_values[] = { { 0x01, "Node Diversity Supported"}, { 0x02, "Link Diversity Supported"}, { 0x04, "SRLG Diversity Supported"}, { 0, NULL} }; #define LMP_MSGTYPE_CONFIG 1 #define LMP_MSGTYPE_CONFIG_ACK 2 #define LMP_MSGTYPE_CONFIG_NACK 3 #define LMP_MSGTYPE_HELLO 4 #define LMP_MSGTYPE_VERIFY_BEGIN 5 #define LMP_MSGTYPE_VERIFY_BEGIN_ACK 6 #define LMP_MSGTYPE_VERIFY_BEGIN_NACK 7 #define LMP_MSGTYPE_VERIFY_END 8 #define LMP_MSGTYPE_VERIFY_END_ACK 9 #define LMP_MSGTYPE_TEST 10 #define LMP_MSGTYPE_TEST_STATUS_SUCCESS 11 #define LMP_MSGTYPE_TEST_STATUS_FAILURE 12 #define LMP_MSGTYPE_TEST_STATUS_ACK 13 #define LMP_MSGTYPE_LINK_SUMMARY 14 #define LMP_MSGTYPE_LINK_SUMMARY_ACK 15 #define LMP_MSGTYPE_LINK_SUMMARY_NACK 16 #define LMP_MSGTYPE_CHANNEL_STATUS 17 #define LMP_MSGTYPE_CHANNEL_STATUS_ACK 18 #define LMP_MSGTYPE_CHANNEL_STATUS_REQ 19 #define LMP_MSGTYPE_CHANNEL_STATUS_RESP 20 /* LMP Service Discovery message types defined by UNI 1.0 */ #define LMP_MSGTYPE_SERVICE_CONFIG 50 #define LMP_MSGTYPE_SERVICE_CONFIG_ACK 51 #define LMP_MSGTYPE_SERVICE_CONFIG_NACK 52 static const struct tok lmp_msg_type_values[] = { { LMP_MSGTYPE_CONFIG, "Config"}, { LMP_MSGTYPE_CONFIG_ACK, "Config ACK"}, { LMP_MSGTYPE_CONFIG_NACK, "Config NACK"}, { LMP_MSGTYPE_HELLO, "Hello"}, { LMP_MSGTYPE_VERIFY_BEGIN, "Begin Verify"}, { LMP_MSGTYPE_VERIFY_BEGIN_ACK, "Begin Verify ACK"}, { LMP_MSGTYPE_VERIFY_BEGIN_NACK, "Begin Verify NACK"}, { LMP_MSGTYPE_VERIFY_END, "End Verify"}, { LMP_MSGTYPE_VERIFY_END_ACK, "End Verify ACK"}, { LMP_MSGTYPE_TEST, "Test"}, { LMP_MSGTYPE_TEST_STATUS_SUCCESS, "Test Status Success"}, { LMP_MSGTYPE_TEST_STATUS_FAILURE, "Test Status Failure"}, { LMP_MSGTYPE_TEST_STATUS_ACK, "Test Status ACK"}, { LMP_MSGTYPE_LINK_SUMMARY, "Link Summary"}, { LMP_MSGTYPE_LINK_SUMMARY_ACK, "Link Summary ACK"}, { LMP_MSGTYPE_LINK_SUMMARY_NACK, "Link Summary NACK"}, { LMP_MSGTYPE_CHANNEL_STATUS, "Channel Status"}, { LMP_MSGTYPE_CHANNEL_STATUS_ACK, "Channel Status ACK"}, { LMP_MSGTYPE_CHANNEL_STATUS_REQ, "Channel Status Request"}, { LMP_MSGTYPE_CHANNEL_STATUS_RESP, "Channel Status Response"}, { LMP_MSGTYPE_SERVICE_CONFIG, "Service Config"}, { LMP_MSGTYPE_SERVICE_CONFIG_ACK, "Service Config ACK"}, { LMP_MSGTYPE_SERVICE_CONFIG_NACK, "Service Config NACK"}, { 0, NULL} }; /* * LMP object header * * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * |N| C-Type | Class | Length | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | | * // (object contents) // * | | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct lmp_object_header { uint8_t ctype; uint8_t class_num; uint8_t length[2]; }; #define LMP_OBJ_CC_ID 1 #define LMP_OBJ_NODE_ID 2 #define LMP_OBJ_LINK_ID 3 #define LMP_OBJ_INTERFACE_ID 4 #define LMP_OBJ_MESSAGE_ID 5 #define LMP_OBJ_CONFIG 6 #define LMP_OBJ_HELLO 7 #define LMP_OBJ_VERIFY_BEGIN 8 #define LMP_OBJ_VERIFY_BEGIN_ACK 9 #define LMP_OBJ_VERIFY_ID 10 #define LMP_OBJ_TE_LINK 11 #define LMP_OBJ_DATA_LINK 12 #define LMP_OBJ_CHANNEL_STATUS 13 #define LMP_OBJ_CHANNEL_STATUS_REQ 14 #define LMP_OBJ_ERROR_CODE 20 #define LMP_OBJ_SERVICE_CONFIG 51 /* defined in UNI 1.0 */ static const struct tok lmp_obj_values[] = { { LMP_OBJ_CC_ID, "Control Channel ID" }, { LMP_OBJ_NODE_ID, "Node ID" }, { LMP_OBJ_LINK_ID, "Link ID" }, { LMP_OBJ_INTERFACE_ID, "Interface ID" }, { LMP_OBJ_MESSAGE_ID, "Message ID" }, { LMP_OBJ_CONFIG, "Configuration" }, { LMP_OBJ_HELLO, "Hello" }, { LMP_OBJ_VERIFY_BEGIN, "Verify Begin" }, { LMP_OBJ_VERIFY_BEGIN_ACK, "Verify Begin ACK" }, { LMP_OBJ_VERIFY_ID, "Verify ID" }, { LMP_OBJ_TE_LINK, "TE Link" }, { LMP_OBJ_DATA_LINK, "Data Link" }, { LMP_OBJ_CHANNEL_STATUS, "Channel Status" }, { LMP_OBJ_CHANNEL_STATUS_REQ, "Channel Status Request" }, { LMP_OBJ_ERROR_CODE, "Error Code" }, { LMP_OBJ_SERVICE_CONFIG, "Service Config" }, { 0, NULL} }; #define INT_SWITCHING_TYPE_SUBOBJ 1 #define WAVELENGTH_SUBOBJ 2 static const struct tok lmp_data_link_subobj[] = { { INT_SWITCHING_TYPE_SUBOBJ, "Interface Switching Type" }, { WAVELENGTH_SUBOBJ , "Wavelength" }, { 0, NULL} }; #define LMP_CTYPE_IPV4 1 #define LMP_CTYPE_IPV6 2 #define LMP_CTYPE_LOC 1 #define LMP_CTYPE_RMT 2 #define LMP_CTYPE_UNMD 3 #define LMP_CTYPE_IPV4_LOC 1 #define LMP_CTYPE_IPV4_RMT 2 #define LMP_CTYPE_IPV6_LOC 3 #define LMP_CTYPE_IPV6_RMT 4 #define LMP_CTYPE_UNMD_LOC 5 #define LMP_CTYPE_UNMD_RMT 6 #define LMP_CTYPE_1 1 #define LMP_CTYPE_2 2 #define LMP_CTYPE_HELLO_CONFIG 1 #define LMP_CTYPE_HELLO 1 #define LMP_CTYPE_BEGIN_VERIFY_ERROR 1 #define LMP_CTYPE_LINK_SUMMARY_ERROR 2 /* C-Types for Service Config Object */ #define LMP_CTYPE_SERVICE_CONFIG_SP 1 #define LMP_CTYPE_SERVICE_CONFIG_CPSA 2 #define LMP_CTYPE_SERVICE_CONFIG_TRANSPARENCY_TCM 3 #define LMP_CTYPE_SERVICE_CONFIG_NETWORK_DIVERSITY 4 /* * Different link types allowed in the Client Port Service Attributes * subobject defined for LMP Service Discovery in the UNI 1.0 spec */ #define LMP_SD_SERVICE_CONFIG_CPSA_LINK_TYPE_SDH 5 /* UNI 1.0 Sec 9.4.2 */ #define LMP_SD_SERVICE_CONFIG_CPSA_LINK_TYPE_SONET 6 /* UNI 1.0 Sec 9.4.2 */ /* * the ctypes are not globally unique so for * translating it to strings we build a table based * on objects offsetted by the ctype */ static const struct tok lmp_ctype_values[] = { { 256*LMP_OBJ_CC_ID+LMP_CTYPE_LOC, "Local" }, { 256*LMP_OBJ_CC_ID+LMP_CTYPE_RMT, "Remote" }, { 256*LMP_OBJ_NODE_ID+LMP_CTYPE_LOC, "Local" }, { 256*LMP_OBJ_NODE_ID+LMP_CTYPE_RMT, "Remote" }, { 256*LMP_OBJ_LINK_ID+LMP_CTYPE_IPV4_LOC, "IPv4 Local" }, { 256*LMP_OBJ_LINK_ID+LMP_CTYPE_IPV4_RMT, "IPv4 Remote" }, { 256*LMP_OBJ_LINK_ID+LMP_CTYPE_IPV6_LOC, "IPv6 Local" }, { 256*LMP_OBJ_LINK_ID+LMP_CTYPE_IPV6_RMT, "IPv6 Remote" }, { 256*LMP_OBJ_LINK_ID+LMP_CTYPE_UNMD_LOC, "Unnumbered Local" }, { 256*LMP_OBJ_LINK_ID+LMP_CTYPE_UNMD_RMT, "Unnumbered Remote" }, { 256*LMP_OBJ_INTERFACE_ID+LMP_CTYPE_IPV4_LOC, "IPv4 Local" }, { 256*LMP_OBJ_INTERFACE_ID+LMP_CTYPE_IPV4_RMT, "IPv4 Remote" }, { 256*LMP_OBJ_INTERFACE_ID+LMP_CTYPE_IPV6_LOC, "IPv6 Local" }, { 256*LMP_OBJ_INTERFACE_ID+LMP_CTYPE_IPV6_RMT, "IPv6 Remote" }, { 256*LMP_OBJ_INTERFACE_ID+LMP_CTYPE_UNMD_LOC, "Unnumbered Local" }, { 256*LMP_OBJ_INTERFACE_ID+LMP_CTYPE_UNMD_RMT, "Unnumbered Remote" }, { 256*LMP_OBJ_MESSAGE_ID+LMP_CTYPE_1, "1" }, { 256*LMP_OBJ_MESSAGE_ID+LMP_CTYPE_2, "2" }, { 256*LMP_OBJ_CONFIG+LMP_CTYPE_1, "1" }, { 256*LMP_OBJ_HELLO+LMP_CTYPE_1, "1" }, { 256*LMP_OBJ_VERIFY_BEGIN+LMP_CTYPE_1, "1" }, { 256*LMP_OBJ_VERIFY_BEGIN_ACK+LMP_CTYPE_1, "1" }, { 256*LMP_OBJ_VERIFY_ID+LMP_CTYPE_1, "1" }, { 256*LMP_OBJ_TE_LINK+LMP_CTYPE_IPV4, "IPv4" }, { 256*LMP_OBJ_TE_LINK+LMP_CTYPE_IPV6, "IPv6" }, { 256*LMP_OBJ_TE_LINK+LMP_CTYPE_UNMD, "Unnumbered" }, { 256*LMP_OBJ_DATA_LINK+LMP_CTYPE_IPV4, "IPv4" }, { 256*LMP_OBJ_DATA_LINK+LMP_CTYPE_IPV6, "IPv6" }, { 256*LMP_OBJ_DATA_LINK+LMP_CTYPE_UNMD, "Unnumbered" }, { 256*LMP_OBJ_CHANNEL_STATUS+LMP_CTYPE_IPV4, "IPv4" }, { 256*LMP_OBJ_CHANNEL_STATUS+LMP_CTYPE_IPV6, "IPv6" }, { 256*LMP_OBJ_CHANNEL_STATUS+LMP_CTYPE_UNMD, "Unnumbered" }, { 256*LMP_OBJ_CHANNEL_STATUS_REQ+LMP_CTYPE_IPV4, "IPv4" }, { 256*LMP_OBJ_CHANNEL_STATUS_REQ+LMP_CTYPE_IPV6, "IPv6" }, { 256*LMP_OBJ_CHANNEL_STATUS_REQ+LMP_CTYPE_UNMD, "Unnumbered" }, { 256*LMP_OBJ_ERROR_CODE+LMP_CTYPE_1, "1" }, { 256*LMP_OBJ_ERROR_CODE+LMP_CTYPE_2, "2" }, { 256*LMP_OBJ_SERVICE_CONFIG+LMP_CTYPE_SERVICE_CONFIG_SP, "1" }, { 256*LMP_OBJ_SERVICE_CONFIG+LMP_CTYPE_SERVICE_CONFIG_CPSA, "2" }, { 256*LMP_OBJ_SERVICE_CONFIG+LMP_CTYPE_SERVICE_CONFIG_TRANSPARENCY_TCM, "3" }, { 256*LMP_OBJ_SERVICE_CONFIG+LMP_CTYPE_SERVICE_CONFIG_NETWORK_DIVERSITY, "4" }, { 0, NULL} }; static int lmp_print_data_link_subobjs(netdissect_options *ndo, const u_char *obj_tptr, int total_subobj_len, int offset) { int hexdump = FALSE; int subobj_type, subobj_len; union { /* int to float conversion buffer */ float f; uint32_t i; } bw; while (total_subobj_len > 0 && hexdump == FALSE ) { ND_TCHECK_16BITS(obj_tptr + offset); subobj_type = EXTRACT_8BITS(obj_tptr + offset); subobj_len = EXTRACT_8BITS(obj_tptr + offset + 1); ND_PRINT((ndo, "\n\t Subobject, Type: %s (%u), Length: %u", tok2str(lmp_data_link_subobj, "Unknown", subobj_type), subobj_type, subobj_len)); if (subobj_len < 4) { ND_PRINT((ndo, " (too short)")); break; } if ((subobj_len % 4) != 0) { ND_PRINT((ndo, " (not a multiple of 4)")); break; } if (total_subobj_len < subobj_len) { ND_PRINT((ndo, " (goes past the end of the object)")); break; } switch(subobj_type) { case INT_SWITCHING_TYPE_SUBOBJ: ND_TCHECK_8BITS(obj_tptr + offset + 2); ND_PRINT((ndo, "\n\t Switching Type: %s (%u)", tok2str(gmpls_switch_cap_values, "Unknown", EXTRACT_8BITS(obj_tptr + offset + 2)), EXTRACT_8BITS(obj_tptr + offset + 2))); ND_TCHECK_8BITS(obj_tptr + offset + 3); ND_PRINT((ndo, "\n\t Encoding Type: %s (%u)", tok2str(gmpls_encoding_values, "Unknown", EXTRACT_8BITS(obj_tptr + offset + 3)), EXTRACT_8BITS(obj_tptr + offset + 3))); ND_TCHECK_32BITS(obj_tptr + offset + 4); bw.i = EXTRACT_32BITS(obj_tptr+offset+4); ND_PRINT((ndo, "\n\t Min Reservable Bandwidth: %.3f Mbps", bw.f*8/1000000)); ND_TCHECK_32BITS(obj_tptr + offset + 8); bw.i = EXTRACT_32BITS(obj_tptr+offset+8); ND_PRINT((ndo, "\n\t Max Reservable Bandwidth: %.3f Mbps", bw.f*8/1000000)); break; case WAVELENGTH_SUBOBJ: ND_TCHECK_32BITS(obj_tptr + offset + 4); ND_PRINT((ndo, "\n\t Wavelength: %u", EXTRACT_32BITS(obj_tptr+offset+4))); break; default: /* Any Unknown Subobject ==> Exit loop */ hexdump=TRUE; break; } total_subobj_len-=subobj_len; offset+=subobj_len; } return (hexdump); trunc: return -1; } void lmp_print(netdissect_options *ndo, register const u_char *pptr, register u_int len) { const struct lmp_common_header *lmp_com_header; const struct lmp_object_header *lmp_obj_header; const u_char *tptr,*obj_tptr; u_int tlen,lmp_obj_len,lmp_obj_ctype,obj_tlen; int hexdump, ret; u_int offset; u_int link_type; union { /* int to float conversion buffer */ float f; uint32_t i; } bw; tptr=pptr; lmp_com_header = (const struct lmp_common_header *)pptr; ND_TCHECK(*lmp_com_header); /* * Sanity checking of the header. */ if (LMP_EXTRACT_VERSION(lmp_com_header->version_res[0]) != LMP_VERSION) { ND_PRINT((ndo, "LMP version %u packet not supported", LMP_EXTRACT_VERSION(lmp_com_header->version_res[0]))); return; } /* in non-verbose mode just lets print the basic Message Type*/ if (ndo->ndo_vflag < 1) { ND_PRINT((ndo, "LMPv%u %s Message, length: %u", LMP_EXTRACT_VERSION(lmp_com_header->version_res[0]), tok2str(lmp_msg_type_values, "unknown (%u)",lmp_com_header->msg_type), len)); return; } /* ok they seem to want to know everything - lets fully decode it */ tlen=EXTRACT_16BITS(lmp_com_header->length); ND_PRINT((ndo, "\n\tLMPv%u, msg-type: %s, Flags: [%s], length: %u", LMP_EXTRACT_VERSION(lmp_com_header->version_res[0]), tok2str(lmp_msg_type_values, "unknown, type: %u",lmp_com_header->msg_type), bittok2str(lmp_header_flag_values,"none",lmp_com_header->flags), tlen)); if (tlen < sizeof(const struct lmp_common_header)) { ND_PRINT((ndo, " (too short)")); return; } if (tlen > len) { ND_PRINT((ndo, " (too long)")); tlen = len; } tptr+=sizeof(const struct lmp_common_header); tlen-=sizeof(const struct lmp_common_header); while(tlen>0) { /* did we capture enough for fully decoding the object header ? */ ND_TCHECK2(*tptr, sizeof(struct lmp_object_header)); lmp_obj_header = (const struct lmp_object_header *)tptr; lmp_obj_len=EXTRACT_16BITS(lmp_obj_header->length); lmp_obj_ctype=(lmp_obj_header->ctype)&0x7f; ND_PRINT((ndo, "\n\t %s Object (%u), Class-Type: %s (%u) Flags: [%snegotiable], length: %u", tok2str(lmp_obj_values, "Unknown", lmp_obj_header->class_num), lmp_obj_header->class_num, tok2str(lmp_ctype_values, "Unknown", ((lmp_obj_header->class_num)<<8)+lmp_obj_ctype), lmp_obj_ctype, (lmp_obj_header->ctype)&0x80 ? "" : "non-", lmp_obj_len)); if (lmp_obj_len < 4) { ND_PRINT((ndo, " (too short)")); return; } if ((lmp_obj_len % 4) != 0) { ND_PRINT((ndo, " (not a multiple of 4)")); return; } obj_tptr=tptr+sizeof(struct lmp_object_header); obj_tlen=lmp_obj_len-sizeof(struct lmp_object_header); /* did we capture enough for fully decoding the object ? */ ND_TCHECK2(*tptr, lmp_obj_len); hexdump=FALSE; switch(lmp_obj_header->class_num) { case LMP_OBJ_CC_ID: switch(lmp_obj_ctype) { case LMP_CTYPE_LOC: case LMP_CTYPE_RMT: if (obj_tlen != 4) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Control Channel ID: %u (0x%08x)", EXTRACT_32BITS(obj_tptr), EXTRACT_32BITS(obj_tptr))); break; default: hexdump=TRUE; } break; case LMP_OBJ_LINK_ID: case LMP_OBJ_INTERFACE_ID: switch(lmp_obj_ctype) { case LMP_CTYPE_IPV4_LOC: case LMP_CTYPE_IPV4_RMT: if (obj_tlen != 4) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t IPv4 Link ID: %s (0x%08x)", ipaddr_string(ndo, obj_tptr), EXTRACT_32BITS(obj_tptr))); break; case LMP_CTYPE_IPV6_LOC: case LMP_CTYPE_IPV6_RMT: if (obj_tlen != 16) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t IPv6 Link ID: %s (0x%08x)", ip6addr_string(ndo, obj_tptr), EXTRACT_32BITS(obj_tptr))); break; case LMP_CTYPE_UNMD_LOC: case LMP_CTYPE_UNMD_RMT: if (obj_tlen != 4) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Link ID: %u (0x%08x)", EXTRACT_32BITS(obj_tptr), EXTRACT_32BITS(obj_tptr))); break; default: hexdump=TRUE; } break; case LMP_OBJ_MESSAGE_ID: switch(lmp_obj_ctype) { case LMP_CTYPE_1: if (obj_tlen != 4) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Message ID: %u (0x%08x)", EXTRACT_32BITS(obj_tptr), EXTRACT_32BITS(obj_tptr))); break; case LMP_CTYPE_2: if (obj_tlen != 4) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Message ID Ack: %u (0x%08x)", EXTRACT_32BITS(obj_tptr), EXTRACT_32BITS(obj_tptr))); break; default: hexdump=TRUE; } break; case LMP_OBJ_NODE_ID: switch(lmp_obj_ctype) { case LMP_CTYPE_LOC: case LMP_CTYPE_RMT: if (obj_tlen != 4) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Node ID: %s (0x%08x)", ipaddr_string(ndo, obj_tptr), EXTRACT_32BITS(obj_tptr))); break; default: hexdump=TRUE; } break; case LMP_OBJ_CONFIG: switch(lmp_obj_ctype) { case LMP_CTYPE_HELLO_CONFIG: if (obj_tlen != 4) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Hello Interval: %u\n\t Hello Dead Interval: %u", EXTRACT_16BITS(obj_tptr), EXTRACT_16BITS(obj_tptr+2))); break; default: hexdump=TRUE; } break; case LMP_OBJ_HELLO: switch(lmp_obj_ctype) { case LMP_CTYPE_HELLO: if (obj_tlen != 8) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Tx Seq: %u, Rx Seq: %u", EXTRACT_32BITS(obj_tptr), EXTRACT_32BITS(obj_tptr+4))); break; default: hexdump=TRUE; } break; case LMP_OBJ_TE_LINK: switch(lmp_obj_ctype) { case LMP_CTYPE_IPV4: if (obj_tlen != 12) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Flags: [%s]", bittok2str(lmp_obj_te_link_flag_values, "none", EXTRACT_8BITS(obj_tptr)))); ND_PRINT((ndo, "\n\t Local Link-ID: %s (0x%08x)" "\n\t Remote Link-ID: %s (0x%08x)", ipaddr_string(ndo, obj_tptr+4), EXTRACT_32BITS(obj_tptr+4), ipaddr_string(ndo, obj_tptr+8), EXTRACT_32BITS(obj_tptr+8))); break; case LMP_CTYPE_IPV6: if (obj_tlen != 36) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Flags: [%s]", bittok2str(lmp_obj_te_link_flag_values, "none", EXTRACT_8BITS(obj_tptr)))); ND_PRINT((ndo, "\n\t Local Link-ID: %s (0x%08x)" "\n\t Remote Link-ID: %s (0x%08x)", ip6addr_string(ndo, obj_tptr+4), EXTRACT_32BITS(obj_tptr+4), ip6addr_string(ndo, obj_tptr+20), EXTRACT_32BITS(obj_tptr+20))); break; case LMP_CTYPE_UNMD: if (obj_tlen != 12) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Flags: [%s]", bittok2str(lmp_obj_te_link_flag_values, "none", EXTRACT_8BITS(obj_tptr)))); ND_PRINT((ndo, "\n\t Local Link-ID: %u (0x%08x)" "\n\t Remote Link-ID: %u (0x%08x)", EXTRACT_32BITS(obj_tptr+4), EXTRACT_32BITS(obj_tptr+4), EXTRACT_32BITS(obj_tptr+8), EXTRACT_32BITS(obj_tptr+8))); break; default: hexdump=TRUE; } break; case LMP_OBJ_DATA_LINK: switch(lmp_obj_ctype) { case LMP_CTYPE_IPV4: if (obj_tlen < 12) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Flags: [%s]", bittok2str(lmp_obj_data_link_flag_values, "none", EXTRACT_8BITS(obj_tptr)))); ND_PRINT((ndo, "\n\t Local Interface ID: %s (0x%08x)" "\n\t Remote Interface ID: %s (0x%08x)", ipaddr_string(ndo, obj_tptr+4), EXTRACT_32BITS(obj_tptr+4), ipaddr_string(ndo, obj_tptr+8), EXTRACT_32BITS(obj_tptr+8))); ret = lmp_print_data_link_subobjs(ndo, obj_tptr, obj_tlen - 12, 12); if (ret == -1) goto trunc; if (ret == TRUE) hexdump=TRUE; break; case LMP_CTYPE_IPV6: if (obj_tlen < 36) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Flags: [%s]", bittok2str(lmp_obj_data_link_flag_values, "none", EXTRACT_8BITS(obj_tptr)))); ND_PRINT((ndo, "\n\t Local Interface ID: %s (0x%08x)" "\n\t Remote Interface ID: %s (0x%08x)", ip6addr_string(ndo, obj_tptr+4), EXTRACT_32BITS(obj_tptr+4), ip6addr_string(ndo, obj_tptr+20), EXTRACT_32BITS(obj_tptr+20))); ret = lmp_print_data_link_subobjs(ndo, obj_tptr, obj_tlen - 36, 36); if (ret == -1) goto trunc; if (ret == TRUE) hexdump=TRUE; break; case LMP_CTYPE_UNMD: if (obj_tlen < 12) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Flags: [%s]", bittok2str(lmp_obj_data_link_flag_values, "none", EXTRACT_8BITS(obj_tptr)))); ND_PRINT((ndo, "\n\t Local Interface ID: %u (0x%08x)" "\n\t Remote Interface ID: %u (0x%08x)", EXTRACT_32BITS(obj_tptr+4), EXTRACT_32BITS(obj_tptr+4), EXTRACT_32BITS(obj_tptr+8), EXTRACT_32BITS(obj_tptr+8))); ret = lmp_print_data_link_subobjs(ndo, obj_tptr, obj_tlen - 12, 12); if (ret == -1) goto trunc; if (ret == TRUE) hexdump=TRUE; break; default: hexdump=TRUE; } break; case LMP_OBJ_VERIFY_BEGIN: switch(lmp_obj_ctype) { case LMP_CTYPE_1: if (obj_tlen != 20) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Flags: %s", bittok2str(lmp_obj_begin_verify_flag_values, "none", EXTRACT_16BITS(obj_tptr)))); ND_PRINT((ndo, "\n\t Verify Interval: %u", EXTRACT_16BITS(obj_tptr+2))); ND_PRINT((ndo, "\n\t Data links: %u", EXTRACT_32BITS(obj_tptr+4))); ND_PRINT((ndo, "\n\t Encoding type: %s", tok2str(gmpls_encoding_values, "Unknown", *(obj_tptr+8)))); ND_PRINT((ndo, "\n\t Verify Transport Mechanism: %u (0x%x)%s", EXTRACT_16BITS(obj_tptr+10), EXTRACT_16BITS(obj_tptr+10), EXTRACT_16BITS(obj_tptr+10)&8000 ? " (Payload test messages capable)" : "")); bw.i = EXTRACT_32BITS(obj_tptr+12); ND_PRINT((ndo, "\n\t Transmission Rate: %.3f Mbps",bw.f*8/1000000)); ND_PRINT((ndo, "\n\t Wavelength: %u", EXTRACT_32BITS(obj_tptr+16))); break; default: hexdump=TRUE; } break; case LMP_OBJ_VERIFY_BEGIN_ACK: switch(lmp_obj_ctype) { case LMP_CTYPE_1: if (obj_tlen != 4) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Verify Dead Interval: %u" "\n\t Verify Transport Response: %u", EXTRACT_16BITS(obj_tptr), EXTRACT_16BITS(obj_tptr+2))); break; default: hexdump=TRUE; } break; case LMP_OBJ_VERIFY_ID: switch(lmp_obj_ctype) { case LMP_CTYPE_1: if (obj_tlen != 4) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Verify ID: %u", EXTRACT_32BITS(obj_tptr))); break; default: hexdump=TRUE; } break; case LMP_OBJ_CHANNEL_STATUS: switch(lmp_obj_ctype) { case LMP_CTYPE_IPV4: offset = 0; /* Decode pairs: <Interface_ID (4 bytes), Channel_status (4 bytes)> */ while (offset+8 <= obj_tlen) { ND_PRINT((ndo, "\n\t Interface ID: %s (0x%08x)", ipaddr_string(ndo, obj_tptr+offset), EXTRACT_32BITS(obj_tptr+offset))); ND_PRINT((ndo, "\n\t\t Active: %s (%u)", (EXTRACT_32BITS(obj_tptr+offset+4)>>31) ? "Allocated" : "Non-allocated", (EXTRACT_32BITS(obj_tptr+offset+4)>>31))); ND_PRINT((ndo, "\n\t\t Direction: %s (%u)", (EXTRACT_32BITS(obj_tptr+offset+4)>>30)&0x1 ? "Transmit" : "Receive", (EXTRACT_32BITS(obj_tptr+offset+4)>>30)&0x1)); ND_PRINT((ndo, "\n\t\t Channel Status: %s (%u)", tok2str(lmp_obj_channel_status_values, "Unknown", EXTRACT_32BITS(obj_tptr+offset+4)&0x3FFFFFF), EXTRACT_32BITS(obj_tptr+offset+4)&0x3FFFFFF)); offset+=8; } break; case LMP_CTYPE_IPV6: offset = 0; /* Decode pairs: <Interface_ID (16 bytes), Channel_status (4 bytes)> */ while (offset+20 <= obj_tlen) { ND_PRINT((ndo, "\n\t Interface ID: %s (0x%08x)", ip6addr_string(ndo, obj_tptr+offset), EXTRACT_32BITS(obj_tptr+offset))); ND_PRINT((ndo, "\n\t\t Active: %s (%u)", (EXTRACT_32BITS(obj_tptr+offset+16)>>31) ? "Allocated" : "Non-allocated", (EXTRACT_32BITS(obj_tptr+offset+16)>>31))); ND_PRINT((ndo, "\n\t\t Direction: %s (%u)", (EXTRACT_32BITS(obj_tptr+offset+16)>>30)&0x1 ? "Transmit" : "Receive", (EXTRACT_32BITS(obj_tptr+offset+16)>>30)&0x1)); ND_PRINT((ndo, "\n\t\t Channel Status: %s (%u)", tok2str(lmp_obj_channel_status_values, "Unknown", EXTRACT_32BITS(obj_tptr+offset+16)&0x3FFFFFF), EXTRACT_32BITS(obj_tptr+offset+16)&0x3FFFFFF)); offset+=20; } break; case LMP_CTYPE_UNMD: offset = 0; /* Decode pairs: <Interface_ID (4 bytes), Channel_status (4 bytes)> */ while (offset+8 <= obj_tlen) { ND_PRINT((ndo, "\n\t Interface ID: %u (0x%08x)", EXTRACT_32BITS(obj_tptr+offset), EXTRACT_32BITS(obj_tptr+offset))); ND_PRINT((ndo, "\n\t\t Active: %s (%u)", (EXTRACT_32BITS(obj_tptr+offset+4)>>31) ? "Allocated" : "Non-allocated", (EXTRACT_32BITS(obj_tptr+offset+4)>>31))); ND_PRINT((ndo, "\n\t\t Direction: %s (%u)", (EXTRACT_32BITS(obj_tptr+offset+4)>>30)&0x1 ? "Transmit" : "Receive", (EXTRACT_32BITS(obj_tptr+offset+4)>>30)&0x1)); ND_PRINT((ndo, "\n\t\t Channel Status: %s (%u)", tok2str(lmp_obj_channel_status_values, "Unknown", EXTRACT_32BITS(obj_tptr+offset+4)&0x3FFFFFF), EXTRACT_32BITS(obj_tptr+offset+4)&0x3FFFFFF)); offset+=8; } break; default: hexdump=TRUE; } break; case LMP_OBJ_CHANNEL_STATUS_REQ: switch(lmp_obj_ctype) { case LMP_CTYPE_IPV4: offset = 0; while (offset+4 <= obj_tlen) { ND_PRINT((ndo, "\n\t Interface ID: %s (0x%08x)", ipaddr_string(ndo, obj_tptr+offset), EXTRACT_32BITS(obj_tptr+offset))); offset+=4; } break; case LMP_CTYPE_IPV6: offset = 0; while (offset+16 <= obj_tlen) { ND_PRINT((ndo, "\n\t Interface ID: %s (0x%08x)", ip6addr_string(ndo, obj_tptr+offset), EXTRACT_32BITS(obj_tptr+offset))); offset+=16; } break; case LMP_CTYPE_UNMD: offset = 0; while (offset+4 <= obj_tlen) { ND_PRINT((ndo, "\n\t Interface ID: %u (0x%08x)", EXTRACT_32BITS(obj_tptr+offset), EXTRACT_32BITS(obj_tptr+offset))); offset+=4; } break; default: hexdump=TRUE; } break; case LMP_OBJ_ERROR_CODE: switch(lmp_obj_ctype) { case LMP_CTYPE_BEGIN_VERIFY_ERROR: if (obj_tlen != 4) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Error Code: %s", bittok2str(lmp_obj_begin_verify_error_values, "none", EXTRACT_32BITS(obj_tptr)))); break; case LMP_CTYPE_LINK_SUMMARY_ERROR: if (obj_tlen != 4) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Error Code: %s", bittok2str(lmp_obj_link_summary_error_values, "none", EXTRACT_32BITS(obj_tptr)))); break; default: hexdump=TRUE; } break; case LMP_OBJ_SERVICE_CONFIG: switch (lmp_obj_ctype) { case LMP_CTYPE_SERVICE_CONFIG_SP: if (obj_tlen != 4) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Flags: %s", bittok2str(lmp_obj_service_config_sp_flag_values, "none", EXTRACT_8BITS(obj_tptr)))); ND_PRINT((ndo, "\n\t UNI Version: %u", EXTRACT_8BITS(obj_tptr + 1))); break; case LMP_CTYPE_SERVICE_CONFIG_CPSA: if (obj_tlen != 16) { ND_PRINT((ndo, " (not correct for object)")); break; } link_type = EXTRACT_8BITS(obj_tptr); ND_PRINT((ndo, "\n\t Link Type: %s (%u)", tok2str(lmp_sd_service_config_cpsa_link_type_values, "Unknown", link_type), link_type)); switch (link_type) { case LMP_SD_SERVICE_CONFIG_CPSA_LINK_TYPE_SDH: ND_PRINT((ndo, "\n\t Signal Type: %s (%u)", tok2str(lmp_sd_service_config_cpsa_signal_type_sdh_values, "Unknown", EXTRACT_8BITS(obj_tptr + 1)), EXTRACT_8BITS(obj_tptr + 1))); break; case LMP_SD_SERVICE_CONFIG_CPSA_LINK_TYPE_SONET: ND_PRINT((ndo, "\n\t Signal Type: %s (%u)", tok2str(lmp_sd_service_config_cpsa_signal_type_sonet_values, "Unknown", EXTRACT_8BITS(obj_tptr + 1)), EXTRACT_8BITS(obj_tptr + 1))); break; } ND_PRINT((ndo, "\n\t Transparency: %s", bittok2str(lmp_obj_service_config_cpsa_tp_flag_values, "none", EXTRACT_8BITS(obj_tptr + 2)))); ND_PRINT((ndo, "\n\t Contiguous Concatenation Types: %s", bittok2str(lmp_obj_service_config_cpsa_cct_flag_values, "none", EXTRACT_8BITS(obj_tptr + 3)))); ND_PRINT((ndo, "\n\t Minimum NCC: %u", EXTRACT_16BITS(obj_tptr+4))); ND_PRINT((ndo, "\n\t Maximum NCC: %u", EXTRACT_16BITS(obj_tptr+6))); ND_PRINT((ndo, "\n\t Minimum NVC:%u", EXTRACT_16BITS(obj_tptr+8))); ND_PRINT((ndo, "\n\t Maximum NVC:%u", EXTRACT_16BITS(obj_tptr+10))); ND_PRINT((ndo, "\n\t Local Interface ID: %s (0x%08x)", ipaddr_string(ndo, obj_tptr+12), EXTRACT_32BITS(obj_tptr+12))); break; case LMP_CTYPE_SERVICE_CONFIG_TRANSPARENCY_TCM: if (obj_tlen != 8) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Transparency Flags: %s", bittok2str( lmp_obj_service_config_nsa_transparency_flag_values, "none", EXTRACT_32BITS(obj_tptr)))); ND_PRINT((ndo, "\n\t TCM Monitoring Flags: %s", bittok2str( lmp_obj_service_config_nsa_tcm_flag_values, "none", EXTRACT_8BITS(obj_tptr + 7)))); break; case LMP_CTYPE_SERVICE_CONFIG_NETWORK_DIVERSITY: if (obj_tlen != 4) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Diversity: Flags: %s", bittok2str( lmp_obj_service_config_nsa_network_diversity_flag_values, "none", EXTRACT_8BITS(obj_tptr + 3)))); break; default: hexdump = TRUE; } break; default: if (ndo->ndo_vflag <= 1) print_unknown_data(ndo,obj_tptr,"\n\t ",obj_tlen); break; } /* do we want to see an additionally hexdump ? */ if (ndo->ndo_vflag > 1 || hexdump==TRUE) print_unknown_data(ndo,tptr+sizeof(struct lmp_object_header),"\n\t ", lmp_obj_len-sizeof(struct lmp_object_header)); tptr+=lmp_obj_len; tlen-=lmp_obj_len; } return; trunc: ND_PRINT((ndo, "%s", tstr)); } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 8 * End: */
./CrossVul/dataset_final_sorted/CWE-119/c/good_1028_0
crossvul-cpp_data_bad_578_1
#ifndef IGNOREALL /* dcraw.c -- Dave Coffin's raw photo decoder Copyright 1997-2015 by Dave Coffin, dcoffin a cybercom o net This is a command-line ANSI C program to convert raw photos from any digital camera on any computer running any operating system. No license is required to download and use dcraw.c. However, to lawfully redistribute dcraw, you must either (a) offer, at no extra charge, full source code* for all executable files containing RESTRICTED functions, (b) distribute this code under the GPL Version 2 or later, (c) remove all RESTRICTED functions, re-implement them, or copy them from an earlier, unrestricted Revision of dcraw.c, or (d) purchase a license from the author. The functions that process Foveon images have been RESTRICTED since Revision 1.237. All other code remains free for all uses. *If you have not modified dcraw.c in any way, a link to my homepage qualifies as "full source code". $Revision: 1.476 $ $Date: 2015/05/25 02:29:14 $ */ /*@out DEFINES #ifndef USE_JPEG #define NO_JPEG #endif #ifndef USE_JASPER #define NO_JASPER #endif @end DEFINES */ #define NO_LCMS #define DCRAW_VERBOSE //@out DEFINES #define DCRAW_VERSION "9.26" #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #define _USE_MATH_DEFINES #include <ctype.h> #include <errno.h> #include <fcntl.h> #include <float.h> #include <limits.h> #include <math.h> #include <setjmp.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <sys/types.h> //@end DEFINES #if defined(DJGPP) || defined(__MINGW32__) #define fseeko fseek #define ftello ftell #else #define fgetc getc_unlocked #endif //@out DEFINES #ifdef __CYGWIN__ #include <io.h> #endif #if defined WIN32 || defined(__MINGW32__) #include <sys/utime.h> #include <winsock2.h> #pragma comment(lib, "ws2_32.lib") #define snprintf _snprintf #define strcasecmp stricmp #define strncasecmp strnicmp //@end DEFINES typedef __int64 INT64; typedef unsigned __int64 UINT64; //@out DEFINES #else #include <unistd.h> #include <utime.h> #include <netinet/in.h> typedef long long INT64; typedef unsigned long long UINT64; #endif #ifdef NODEPS #define NO_JASPER #define NO_JPEG #define NO_LCMS #endif #ifndef NO_JASPER #include <jasper/jasper.h> /* Decode Red camera movies */ #endif #ifndef NO_JPEG #include <jpeglib.h> /* Decode compressed Kodak DC120 photos */ #endif /* and Adobe Lossy DNGs */ #ifndef NO_LCMS #ifdef USE_LCMS #include <lcms.h> /* Support color profiles */ #else #include <lcms2.h> /* Support color profiles */ #endif #endif #ifdef LOCALEDIR #include <libintl.h> #define _(String) gettext(String) #else #define _(String) (String) #endif #ifdef LJPEG_DECODE #error Please compile dcraw.c by itself. #error Do not link it with ljpeg_decode. #endif #ifndef LONG_BIT #define LONG_BIT (8 * sizeof(long)) #endif //@end DEFINES #if !defined(uchar) #define uchar unsigned char #endif #if !defined(ushort) #define ushort unsigned short #endif /* All global variables are defined here, and all functions that access them are prefixed with "CLASS". Note that a thread-safe C++ class cannot have non-const static local variables. */ FILE *ifp, *ofp; short order; const char *ifname; char *meta_data, xtrans[6][6], xtrans_abs[6][6]; char cdesc[5], desc[512], make[64], model[64], model2[64], artist[64], software[64]; float flash_used, canon_ev, iso_speed, shutter, aperture, focal_len; time_t timestamp; off_t strip_offset, data_offset; off_t thumb_offset, meta_offset, profile_offset; unsigned shot_order, kodak_cbpp, exif_cfa, unique_id; unsigned thumb_length, meta_length, profile_length; unsigned thumb_misc, *oprof, fuji_layout, shot_select = 0, multi_out = 0; unsigned tiff_nifds, tiff_samples, tiff_bps, tiff_compress; unsigned black, maximum, mix_green, raw_color, zero_is_bad; unsigned zero_after_ff, is_raw, dng_version, is_foveon, data_error; unsigned tile_width, tile_length, gpsdata[32], load_flags; unsigned flip, tiff_flip, filters, colors; ushort raw_height, raw_width, height, width, top_margin, left_margin; ushort shrink, iheight, iwidth, fuji_width, thumb_width, thumb_height; ushort *raw_image, (*image)[4], cblack[4102]; ushort white[8][8], curve[0x10000], cr2_slice[3], sraw_mul[4]; double pixel_aspect, aber[4] = {1, 1, 1, 1}, gamm[6] = {0.45, 4.5, 0, 0, 0, 0}; float bright = 1, user_mul[4] = {0, 0, 0, 0}, threshold = 0; int mask[8][4]; int half_size = 0, four_color_rgb = 0, document_mode = 0, highlight = 0; int verbose = 0, use_auto_wb = 0, use_camera_wb = 0, use_camera_matrix = 1; int output_color = 1, output_bps = 8, output_tiff = 0, med_passes = 0; int no_auto_bright = 0; unsigned greybox[4] = {0, 0, UINT_MAX, UINT_MAX}; float cam_mul[4], pre_mul[4], cmatrix[3][4], rgb_cam[3][4]; const double xyz_rgb[3][3] = {/* XYZ from RGB */ {0.412453, 0.357580, 0.180423}, {0.212671, 0.715160, 0.072169}, {0.019334, 0.119193, 0.950227}}; const float d65_white[3] = {0.950456, 1, 1.088754}; int histogram[4][0x2000]; void (*write_thumb)(), (*write_fun)(); void (*load_raw)(), (*thumb_load_raw)(); jmp_buf failure; struct decode { struct decode *branch[2]; int leaf; } first_decode[2048], *second_decode, *free_decode; struct tiff_ifd { int t_width, t_height, bps, comp, phint, offset, t_flip, samples, bytes; int t_tile_width, t_tile_length, sample_format, predictor; float t_shutter; } tiff_ifd[10]; struct ph1 { int format, key_off, tag_21a; int t_black, split_col, black_col, split_row, black_row; float tag_210; } ph1; #define CLASS //@out DEFINES #define FORC(cnt) for (c = 0; c < cnt; c++) #define FORC3 FORC(3) #define FORC4 FORC(4) #define FORCC for (c = 0; c < colors && c < 4; c++) #define SQR(x) ((x) * (x)) #define ABS(x) (((int)(x) ^ ((int)(x) >> 31)) - ((int)(x) >> 31)) #define MIN(a, b) ((a) < (b) ? (a) : (b)) #define MAX(a, b) ((a) > (b) ? (a) : (b)) #define LIM(x, min, max) MAX(min, MIN(x, max)) #define ULIM(x, y, z) ((y) < (z) ? LIM(x, y, z) : LIM(x, z, y)) #define CLIP(x) LIM((int)(x), 0, 65535) #define SWAP(a, b) \ { \ a = a + b; \ b = a - b; \ a = a - b; \ } #define my_swap(type, i, j) \ { \ type t = i; \ i = j; \ j = t; \ } static float fMAX(float a, float b) { return MAX(a, b); } /* In order to inline this calculation, I make the risky assumption that all filter patterns can be described by a repeating pattern of eight rows and two columns Do not use the FC or BAYER macros with the Leaf CatchLight, because its pattern is 16x16, not 2x8. Return values are either 0/1/2/3 = G/M/C/Y or 0/1/2/3 = R/G1/B/G2 PowerShot 600 PowerShot A50 PowerShot Pro70 Pro90 & G1 0xe1e4e1e4: 0x1b4e4b1e: 0x1e4b4e1b: 0xb4b4b4b4: 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 0 G M G M G M 0 C Y C Y C Y 0 Y C Y C Y C 0 G M G M G M 1 C Y C Y C Y 1 M G M G M G 1 M G M G M G 1 Y C Y C Y C 2 M G M G M G 2 Y C Y C Y C 2 C Y C Y C Y 3 C Y C Y C Y 3 G M G M G M 3 G M G M G M 4 C Y C Y C Y 4 Y C Y C Y C PowerShot A5 5 G M G M G M 5 G M G M G M 0x1e4e1e4e: 6 Y C Y C Y C 6 C Y C Y C Y 7 M G M G M G 7 M G M G M G 0 1 2 3 4 5 0 C Y C Y C Y 1 G M G M G M 2 C Y C Y C Y 3 M G M G M G All RGB cameras use one of these Bayer grids: 0x16161616: 0x61616161: 0x49494949: 0x94949494: 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 0 B G B G B G 0 G R G R G R 0 G B G B G B 0 R G R G R G 1 G R G R G R 1 B G B G B G 1 R G R G R G 1 G B G B G B 2 B G B G B G 2 G R G R G R 2 G B G B G B 2 R G R G R G 3 G R G R G R 3 B G B G B G 3 R G R G R G 3 G B G B G B */ #define RAW(row, col) raw_image[(row)*raw_width + (col)] //@end DEFINES #define FC(row, col) (filters >> ((((row) << 1 & 14) + ((col)&1)) << 1) & 3) //@out DEFINES #define BAYER(row, col) image[((row) >> shrink) * iwidth + ((col) >> shrink)][FC(row, col)] #define BAYER2(row, col) image[((row) >> shrink) * iwidth + ((col) >> shrink)][fcol(row, col)] //@end DEFINES /* @out COMMON #include <math.h> #define CLASS LibRaw:: #include "libraw/libraw_types.h" #define LIBRAW_LIBRARY_BUILD #define LIBRAW_IO_REDEFINED #include "libraw/libraw.h" #include "internal/defines.h" #include "internal/var_defines.h" @end COMMON */ //@out COMMON int CLASS fcol(int row, int col) { static const char filter[16][16] = { {2, 1, 1, 3, 2, 3, 2, 0, 3, 2, 3, 0, 1, 2, 1, 0}, {0, 3, 0, 2, 0, 1, 3, 1, 0, 1, 1, 2, 0, 3, 3, 2}, {2, 3, 3, 2, 3, 1, 1, 3, 3, 1, 2, 1, 2, 0, 0, 3}, {0, 1, 0, 1, 0, 2, 0, 2, 2, 0, 3, 0, 1, 3, 2, 1}, {3, 1, 1, 2, 0, 1, 0, 2, 1, 3, 1, 3, 0, 1, 3, 0}, {2, 0, 0, 3, 3, 2, 3, 1, 2, 0, 2, 0, 3, 2, 2, 1}, {2, 3, 3, 1, 2, 1, 2, 1, 2, 1, 1, 2, 3, 0, 0, 1}, {1, 0, 0, 2, 3, 0, 0, 3, 0, 3, 0, 3, 2, 1, 2, 3}, {2, 3, 3, 1, 1, 2, 1, 0, 3, 2, 3, 0, 2, 3, 1, 3}, {1, 0, 2, 0, 3, 0, 3, 2, 0, 1, 1, 2, 0, 1, 0, 2}, {0, 1, 1, 3, 3, 2, 2, 1, 1, 3, 3, 0, 2, 1, 3, 2}, {2, 3, 2, 0, 0, 1, 3, 0, 2, 0, 1, 2, 3, 0, 1, 0}, {1, 3, 1, 2, 3, 2, 3, 2, 0, 2, 0, 1, 1, 0, 3, 0}, {0, 2, 0, 3, 1, 0, 0, 1, 1, 3, 3, 2, 3, 2, 2, 1}, {2, 1, 3, 2, 3, 1, 2, 1, 0, 3, 0, 2, 0, 2, 0, 2}, {0, 3, 1, 0, 0, 2, 0, 3, 2, 1, 3, 1, 1, 3, 1, 3}}; if (filters == 1) return filter[(row + top_margin) & 15][(col + left_margin) & 15]; if (filters == 9) return xtrans[(row + 6) % 6][(col + 6) % 6]; return FC(row, col); } #if !defined(__FreeBSD__) static size_t local_strnlen(const char *s, size_t n) { const char *p = (const char *)memchr(s, 0, n); return (p ? p - s : n); } /* add OS X version check here ?? */ #define strnlen(a, b) local_strnlen(a, b) #endif #ifdef LIBRAW_LIBRARY_BUILD static int Fuji_wb_list1[] = {LIBRAW_WBI_FineWeather, LIBRAW_WBI_Shade, LIBRAW_WBI_FL_D, LIBRAW_WBI_FL_L, LIBRAW_WBI_FL_W, LIBRAW_WBI_Tungsten}; static int nFuji_wb_list1 = sizeof(Fuji_wb_list1) / sizeof(int); static int FujiCCT_K[31] = {2500, 2550, 2650, 2700, 2800, 2850, 2950, 3000, 3100, 3200, 3300, 3400, 3600, 3700, 3800, 4000, 4200, 4300, 4500, 4800, 5000, 5300, 5600, 5900, 6300, 6700, 7100, 7700, 8300, 9100, 10000}; static int Fuji_wb_list2[] = {LIBRAW_WBI_Auto, 0, LIBRAW_WBI_Custom, 6, LIBRAW_WBI_FineWeather, 1, LIBRAW_WBI_Shade, 8, LIBRAW_WBI_FL_D, 10, LIBRAW_WBI_FL_L, 11, LIBRAW_WBI_FL_W, 12, LIBRAW_WBI_Tungsten, 2, LIBRAW_WBI_Underwater, 35, LIBRAW_WBI_Ill_A, 82, LIBRAW_WBI_D65, 83}; static int nFuji_wb_list2 = sizeof(Fuji_wb_list2) / sizeof(int); static int Oly_wb_list1[] = {LIBRAW_WBI_Shade, LIBRAW_WBI_Cloudy, LIBRAW_WBI_FineWeather, LIBRAW_WBI_Tungsten, LIBRAW_WBI_Sunset, LIBRAW_WBI_FL_D, LIBRAW_WBI_FL_N, LIBRAW_WBI_FL_W, LIBRAW_WBI_FL_WW}; static int Oly_wb_list2[] = {LIBRAW_WBI_Auto, 0, LIBRAW_WBI_Tungsten, 3000, 0x100, 3300, 0x100, 3600, 0x100, 3900, LIBRAW_WBI_FL_W, 4000, 0x100, 4300, LIBRAW_WBI_FL_D, 4500, 0x100, 4800, LIBRAW_WBI_FineWeather, 5300, LIBRAW_WBI_Cloudy, 6000, LIBRAW_WBI_FL_N, 6600, LIBRAW_WBI_Shade, 7500, LIBRAW_WBI_Custom1, 0, LIBRAW_WBI_Custom2, 0, LIBRAW_WBI_Custom3, 0, LIBRAW_WBI_Custom4, 0}; static int Pentax_wb_list1[] = {LIBRAW_WBI_Daylight, LIBRAW_WBI_Shade, LIBRAW_WBI_Cloudy, LIBRAW_WBI_Tungsten, LIBRAW_WBI_FL_D, LIBRAW_WBI_FL_N, LIBRAW_WBI_FL_W, LIBRAW_WBI_Flash}; static int Pentax_wb_list2[] = {LIBRAW_WBI_Daylight, LIBRAW_WBI_Shade, LIBRAW_WBI_Cloudy, LIBRAW_WBI_Tungsten, LIBRAW_WBI_FL_D, LIBRAW_WBI_FL_N, LIBRAW_WBI_FL_W, LIBRAW_WBI_Flash, LIBRAW_WBI_FL_L}; static int nPentax_wb_list2 = sizeof(Pentax_wb_list2) / sizeof(int); static int stread(char *buf, size_t len, LibRaw_abstract_datastream *fp) { int r = fp->read(buf, len, 1); buf[len - 1] = 0; return r; } #define stmread(buf, maxlen, fp) stread(buf, MIN(maxlen, sizeof(buf)), fp) #endif #if !defined(__GLIBC__) && !defined(__FreeBSD__) char *my_memmem(char *haystack, size_t haystacklen, char *needle, size_t needlelen) { char *c; for (c = haystack; c <= haystack + haystacklen - needlelen; c++) if (!memcmp(c, needle, needlelen)) return c; return 0; } #define memmem my_memmem char *my_strcasestr(char *haystack, const char *needle) { char *c; for (c = haystack; *c; c++) if (!strncasecmp(c, needle, strlen(needle))) return c; return 0; } #define strcasestr my_strcasestr #endif #define strbuflen(buf) strnlen(buf, sizeof(buf) - 1) //@end COMMON void CLASS merror(void *ptr, const char *where) { if (ptr) return; fprintf(stderr, _("%s: Out of memory in %s\n"), ifname, where); longjmp(failure, 1); } void CLASS derror() { if (!data_error) { fprintf(stderr, "%s: ", ifname); if (feof(ifp)) fprintf(stderr, _("Unexpected end of file\n")); else fprintf(stderr, _("Corrupt data near 0x%llx\n"), (INT64)ftello(ifp)); } data_error++; } //@out COMMON ushort CLASS sget2(uchar *s) { if (order == 0x4949) /* "II" means little-endian */ return s[0] | s[1] << 8; else /* "MM" means big-endian */ return s[0] << 8 | s[1]; } // DNG was written by: #define nonDNG 0 #define CameraDNG 1 #define AdobeDNG 2 #ifdef LIBRAW_LIBRARY_BUILD static int getwords(char *line, char *words[], int maxwords, int maxlen) { line[maxlen - 1] = 0; char *p = line; int nwords = 0; while (1) { while (isspace(*p)) p++; if (*p == '\0') return nwords; words[nwords++] = p; while (!isspace(*p) && *p != '\0') p++; if (*p == '\0') return nwords; *p++ = '\0'; if (nwords >= maxwords) return nwords; } } static ushort saneSonyCameraInfo(uchar a, uchar b, uchar c, uchar d, uchar e, uchar f) { if ((a >> 4) > 9) return 0; else if ((a & 0x0f) > 9) return 0; else if ((b >> 4) > 9) return 0; else if ((b & 0x0f) > 9) return 0; else if ((c >> 4) > 9) return 0; else if ((c & 0x0f) > 9) return 0; else if ((d >> 4) > 9) return 0; else if ((d & 0x0f) > 9) return 0; else if ((e >> 4) > 9) return 0; else if ((e & 0x0f) > 9) return 0; else if ((f >> 4) > 9) return 0; else if ((f & 0x0f) > 9) return 0; return 1; } static ushort bcd2dec(uchar data) { if ((data >> 4) > 9) return 0; else if ((data & 0x0f) > 9) return 0; else return (data >> 4) * 10 + (data & 0x0f); } static uchar SonySubstitution[257] = "\x00\x01\x32\xb1\x0a\x0e\x87\x28\x02\xcc\xca\xad\x1b\xdc\x08\xed\x64\x86\xf0\x4f\x8c\x6c\xb8\xcb\x69\xc4\x2c\x03" "\x97\xb6\x93\x7c\x14\xf3\xe2\x3e\x30\x8e\xd7\x60\x1c\xa1\xab\x37\xec\x75\xbe\x23\x15\x6a\x59\x3f\xd0\xb9\x96\xb5" "\x50\x27\x88\xe3\x81\x94\xe0\xc0\x04\x5c\xc6\xe8\x5f\x4b\x70\x38\x9f\x82\x80\x51\x2b\xc5\x45\x49\x9b\x21\x52\x53" "\x54\x85\x0b\x5d\x61\xda\x7b\x55\x26\x24\x07\x6e\x36\x5b\x47\xb7\xd9\x4a\xa2\xdf\xbf\x12\x25\xbc\x1e\x7f\x56\xea" "\x10\xe6\xcf\x67\x4d\x3c\x91\x83\xe1\x31\xb3\x6f\xf4\x05\x8a\x46\xc8\x18\x76\x68\xbd\xac\x92\x2a\x13\xe9\x0f\xa3" "\x7a\xdb\x3d\xd4\xe7\x3a\x1a\x57\xaf\x20\x42\xb2\x9e\xc3\x8b\xf2\xd5\xd3\xa4\x7e\x1f\x98\x9c\xee\x74\xa5\xa6\xa7" "\xd8\x5e\xb0\xb4\x34\xce\xa8\x79\x77\x5a\xc1\x89\xae\x9a\x11\x33\x9d\xf5\x39\x19\x65\x78\x16\x71\xd2\xa9\x44\x63" "\x40\x29\xba\xa0\x8f\xe4\xd6\x3b\x84\x0d\xc2\x4e\x58\xdd\x99\x22\x6b\xc9\xbb\x17\x06\xe5\x7d\x66\x43\x62\xf6\xcd" "\x35\x90\x2e\x41\x8d\x6d\xaa\x09\x73\x95\x0c\xf1\x1d\xde\x4c\x2f\x2d\xf7\xd1\x72\xeb\xef\x48\xc7\xf8\xf9\xfa\xfb" "\xfc\xfd\xfe\xff"; ushort CLASS sget2Rev(uchar *s) // specific to some Canon Makernotes fields, where they have endian in reverse { if (order == 0x4d4d) /* "II" means little-endian, and we reverse to "MM" - big endian */ return s[0] | s[1] << 8; else /* "MM" means big-endian... */ return s[0] << 8 | s[1]; } #endif ushort CLASS get2() { uchar str[2] = {0xff, 0xff}; fread(str, 1, 2, ifp); return sget2(str); } unsigned CLASS sget4(uchar *s) { if (order == 0x4949) return s[0] | s[1] << 8 | s[2] << 16 | s[3] << 24; else return s[0] << 24 | s[1] << 16 | s[2] << 8 | s[3]; } #define sget4(s) sget4((uchar *)s) unsigned CLASS get4() { uchar str[4] = {0xff, 0xff, 0xff, 0xff}; fread(str, 1, 4, ifp); return sget4(str); } unsigned CLASS getint(int type) { return type == 3 ? get2() : get4(); } float CLASS int_to_float(int i) { union { int i; float f; } u; u.i = i; return u.f; } double CLASS getreal(int type) { union { char c[8]; double d; } u, v; int i, rev; switch (type) { case 3: return (unsigned short)get2(); case 4: return (unsigned int)get4(); case 5: u.d = (unsigned int)get4(); v.d = (unsigned int)get4(); return u.d / (v.d ? v.d : 1); case 8: return (signed short)get2(); case 9: return (signed int)get4(); case 10: u.d = (signed int)get4(); v.d = (signed int)get4(); return u.d / (v.d ? v.d : 1); case 11: return int_to_float(get4()); case 12: rev = 7 * ((order == 0x4949) == (ntohs(0x1234) == 0x1234)); for (i = 0; i < 8; i++) u.c[i ^ rev] = fgetc(ifp); return u.d; default: return fgetc(ifp); } } void CLASS read_shorts(ushort *pixel, int count) { if (fread(pixel, 2, count, ifp) < count) derror(); if ((order == 0x4949) == (ntohs(0x1234) == 0x1234)) swab((char *)pixel, (char *)pixel, count * 2); } void CLASS cubic_spline(const int *x_, const int *y_, const int len) { float **A, *b, *c, *d, *x, *y; int i, j; A = (float **)calloc(((2 * len + 4) * sizeof **A + sizeof *A), 2 * len); if (!A) return; A[0] = (float *)(A + 2 * len); for (i = 1; i < 2 * len; i++) A[i] = A[0] + 2 * len * i; y = len + (x = i + (d = i + (c = i + (b = A[0] + i * i)))); for (i = 0; i < len; i++) { x[i] = x_[i] / 65535.0; y[i] = y_[i] / 65535.0; } for (i = len - 1; i > 0; i--) { b[i] = (y[i] - y[i - 1]) / (x[i] - x[i - 1]); d[i - 1] = x[i] - x[i - 1]; } for (i = 1; i < len - 1; i++) { A[i][i] = 2 * (d[i - 1] + d[i]); if (i > 1) { A[i][i - 1] = d[i - 1]; A[i - 1][i] = d[i - 1]; } A[i][len - 1] = 6 * (b[i + 1] - b[i]); } for (i = 1; i < len - 2; i++) { float v = A[i + 1][i] / A[i][i]; for (j = 1; j <= len - 1; j++) A[i + 1][j] -= v * A[i][j]; } for (i = len - 2; i > 0; i--) { float acc = 0; for (j = i; j <= len - 2; j++) acc += A[i][j] * c[j]; c[i] = (A[i][len - 1] - acc) / A[i][i]; } for (i = 0; i < 0x10000; i++) { float x_out = (float)(i / 65535.0); float y_out = 0; for (j = 0; j < len - 1; j++) { if (x[j] <= x_out && x_out <= x[j + 1]) { float v = x_out - x[j]; y_out = y[j] + ((y[j + 1] - y[j]) / d[j] - (2 * d[j] * c[j] + c[j + 1] * d[j]) / 6) * v + (c[j] * 0.5) * v * v + ((c[j + 1] - c[j]) / (6 * d[j])) * v * v * v; } } curve[i] = y_out < 0.0 ? 0 : (y_out >= 1.0 ? 65535 : (ushort)(y_out * 65535.0 + 0.5)); } free(A); } void CLASS canon_600_fixed_wb(int temp) { static const short mul[4][5] = { {667, 358, 397, 565, 452}, {731, 390, 367, 499, 517}, {1119, 396, 348, 448, 537}, {1399, 485, 431, 508, 688}}; int lo, hi, i; float frac = 0; for (lo = 4; --lo;) if (*mul[lo] <= temp) break; for (hi = 0; hi < 3; hi++) if (*mul[hi] >= temp) break; if (lo != hi) frac = (float)(temp - *mul[lo]) / (*mul[hi] - *mul[lo]); for (i = 1; i < 5; i++) pre_mul[i - 1] = 1 / (frac * mul[hi][i] + (1 - frac) * mul[lo][i]); } /* Return values: 0 = white 1 = near white 2 = not white */ int CLASS canon_600_color(int ratio[2], int mar) { int clipped = 0, target, miss; if (flash_used) { if (ratio[1] < -104) { ratio[1] = -104; clipped = 1; } if (ratio[1] > 12) { ratio[1] = 12; clipped = 1; } } else { if (ratio[1] < -264 || ratio[1] > 461) return 2; if (ratio[1] < -50) { ratio[1] = -50; clipped = 1; } if (ratio[1] > 307) { ratio[1] = 307; clipped = 1; } } target = flash_used || ratio[1] < 197 ? -38 - (398 * ratio[1] >> 10) : -123 + (48 * ratio[1] >> 10); if (target - mar <= ratio[0] && target + 20 >= ratio[0] && !clipped) return 0; miss = target - ratio[0]; if (abs(miss) >= mar * 4) return 2; if (miss < -20) miss = -20; if (miss > mar) miss = mar; ratio[0] = target - miss; return 1; } void CLASS canon_600_auto_wb() { int mar, row, col, i, j, st, count[] = {0, 0}; int test[8], total[2][8], ratio[2][2], stat[2]; memset(&total, 0, sizeof total); i = canon_ev + 0.5; if (i < 10) mar = 150; else if (i > 12) mar = 20; else mar = 280 - 20 * i; if (flash_used) mar = 80; for (row = 14; row < height - 14; row += 4) for (col = 10; col < width; col += 2) { for (i = 0; i < 8; i++) test[(i & 4) + FC(row + (i >> 1), col + (i & 1))] = BAYER(row + (i >> 1), col + (i & 1)); for (i = 0; i < 8; i++) if (test[i] < 150 || test[i] > 1500) goto next; for (i = 0; i < 4; i++) if (abs(test[i] - test[i + 4]) > 50) goto next; for (i = 0; i < 2; i++) { for (j = 0; j < 4; j += 2) ratio[i][j >> 1] = ((test[i * 4 + j + 1] - test[i * 4 + j]) << 10) / test[i * 4 + j]; stat[i] = canon_600_color(ratio[i], mar); } if ((st = stat[0] | stat[1]) > 1) goto next; for (i = 0; i < 2; i++) if (stat[i]) for (j = 0; j < 2; j++) test[i * 4 + j * 2 + 1] = test[i * 4 + j * 2] * (0x400 + ratio[i][j]) >> 10; for (i = 0; i < 8; i++) total[st][i] += test[i]; count[st]++; next:; } if (count[0] | count[1]) { st = count[0] * 200 < count[1]; for (i = 0; i < 4; i++) pre_mul[i] = 1.0 / (total[st][i] + total[st][i + 4]); } } void CLASS canon_600_coeff() { static const short table[6][12] = {{-190, 702, -1878, 2390, 1861, -1349, 905, -393, -432, 944, 2617, -2105}, {-1203, 1715, -1136, 1648, 1388, -876, 267, 245, -1641, 2153, 3921, -3409}, {-615, 1127, -1563, 2075, 1437, -925, 509, 3, -756, 1268, 2519, -2007}, {-190, 702, -1886, 2398, 2153, -1641, 763, -251, -452, 964, 3040, -2528}, {-190, 702, -1878, 2390, 1861, -1349, 905, -393, -432, 944, 2617, -2105}, {-807, 1319, -1785, 2297, 1388, -876, 769, -257, -230, 742, 2067, -1555}}; int t = 0, i, c; float mc, yc; mc = pre_mul[1] / pre_mul[2]; yc = pre_mul[3] / pre_mul[2]; if (mc > 1 && mc <= 1.28 && yc < 0.8789) t = 1; if (mc > 1.28 && mc <= 2) { if (yc < 0.8789) t = 3; else if (yc <= 2) t = 4; } if (flash_used) t = 5; for (raw_color = i = 0; i < 3; i++) FORCC rgb_cam[i][c] = table[t][i * 4 + c] / 1024.0; } void CLASS canon_600_load_raw() { uchar data[1120], *dp; ushort *pix; int irow, row; for (irow = row = 0; irow < height; irow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread(data, 1, 1120, ifp) < 1120) derror(); pix = raw_image + row * raw_width; for (dp = data; dp < data + 1120; dp += 10, pix += 8) { pix[0] = (dp[0] << 2) + (dp[1] >> 6); pix[1] = (dp[2] << 2) + (dp[1] >> 4 & 3); pix[2] = (dp[3] << 2) + (dp[1] >> 2 & 3); pix[3] = (dp[4] << 2) + (dp[1] & 3); pix[4] = (dp[5] << 2) + (dp[9] & 3); pix[5] = (dp[6] << 2) + (dp[9] >> 2 & 3); pix[6] = (dp[7] << 2) + (dp[9] >> 4 & 3); pix[7] = (dp[8] << 2) + (dp[9] >> 6); } if ((row += 2) > height) row = 1; } } void CLASS canon_600_correct() { int row, col, val; static const short mul[4][2] = {{1141, 1145}, {1128, 1109}, {1178, 1149}, {1128, 1109}}; for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < width; col++) { if ((val = BAYER(row, col) - black) < 0) val = 0; val = val * mul[row & 3][col & 1] >> 9; BAYER(row, col) = val; } } canon_600_fixed_wb(1311); canon_600_auto_wb(); canon_600_coeff(); maximum = (0x3ff - black) * 1109 >> 9; black = 0; } int CLASS canon_s2is() { unsigned row; for (row = 0; row < 100; row++) { fseek(ifp, row * 3340 + 3284, SEEK_SET); if (getc(ifp) > 15) return 1; } return 0; } unsigned CLASS getbithuff(int nbits, ushort *huff) { #ifdef LIBRAW_NOTHREADS static unsigned bitbuf = 0; static int vbits = 0, reset = 0; #else #define bitbuf tls->getbits.bitbuf #define vbits tls->getbits.vbits #define reset tls->getbits.reset #endif unsigned c; if (nbits > 25) return 0; if (nbits < 0) return bitbuf = vbits = reset = 0; if (nbits == 0 || vbits < 0) return 0; while (!reset && vbits < nbits && (c = fgetc(ifp)) != EOF && !(reset = zero_after_ff && c == 0xff && fgetc(ifp))) { bitbuf = (bitbuf << 8) + (uchar)c; vbits += 8; } c = bitbuf << (32 - vbits) >> (32 - nbits); if (huff) { vbits -= huff[c] >> 8; c = (uchar)huff[c]; } else vbits -= nbits; if (vbits < 0) derror(); return c; #ifndef LIBRAW_NOTHREADS #undef bitbuf #undef vbits #undef reset #endif } #define getbits(n) getbithuff(n, 0) #define gethuff(h) getbithuff(*h, h + 1) /* Construct a decode tree according the specification in *source. The first 16 bytes specify how many codes should be 1-bit, 2-bit 3-bit, etc. Bytes after that are the leaf values. For example, if the source is { 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0, 0x04,0x03,0x05,0x06,0x02,0x07,0x01,0x08,0x09,0x00,0x0a,0x0b,0xff }, then the code is 00 0x04 010 0x03 011 0x05 100 0x06 101 0x02 1100 0x07 1101 0x01 11100 0x08 11101 0x09 11110 0x00 111110 0x0a 1111110 0x0b 1111111 0xff */ ushort *CLASS make_decoder_ref(const uchar **source) { int max, len, h, i, j; const uchar *count; ushort *huff; count = (*source += 16) - 17; for (max = 16; max && !count[max]; max--) ; huff = (ushort *)calloc(1 + (1 << max), sizeof *huff); merror(huff, "make_decoder()"); huff[0] = max; for (h = len = 1; len <= max; len++) for (i = 0; i < count[len]; i++, ++*source) for (j = 0; j < 1 << (max - len); j++) if (h <= 1 << max) huff[h++] = len << 8 | **source; return huff; } ushort *CLASS make_decoder(const uchar *source) { return make_decoder_ref(&source); } void CLASS crw_init_tables(unsigned table, ushort *huff[2]) { static const uchar first_tree[3][29] = { {0, 1, 4, 2, 3, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x04, 0x03, 0x05, 0x06, 0x02, 0x07, 0x01, 0x08, 0x09, 0x00, 0x0a, 0x0b, 0xff}, {0, 2, 2, 3, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0x03, 0x02, 0x04, 0x01, 0x05, 0x00, 0x06, 0x07, 0x09, 0x08, 0x0a, 0x0b, 0xff}, {0, 0, 6, 3, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x06, 0x05, 0x07, 0x04, 0x08, 0x03, 0x09, 0x02, 0x00, 0x0a, 0x01, 0x0b, 0xff}, }; static const uchar second_tree[3][180] = { {0, 2, 2, 2, 1, 4, 2, 1, 2, 5, 1, 1, 0, 0, 0, 139, 0x03, 0x04, 0x02, 0x05, 0x01, 0x06, 0x07, 0x08, 0x12, 0x13, 0x11, 0x14, 0x09, 0x15, 0x22, 0x00, 0x21, 0x16, 0x0a, 0xf0, 0x23, 0x17, 0x24, 0x31, 0x32, 0x18, 0x19, 0x33, 0x25, 0x41, 0x34, 0x42, 0x35, 0x51, 0x36, 0x37, 0x38, 0x29, 0x79, 0x26, 0x1a, 0x39, 0x56, 0x57, 0x28, 0x27, 0x52, 0x55, 0x58, 0x43, 0x76, 0x59, 0x77, 0x54, 0x61, 0xf9, 0x71, 0x78, 0x75, 0x96, 0x97, 0x49, 0xb7, 0x53, 0xd7, 0x74, 0xb6, 0x98, 0x47, 0x48, 0x95, 0x69, 0x99, 0x91, 0xfa, 0xb8, 0x68, 0xb5, 0xb9, 0xd6, 0xf7, 0xd8, 0x67, 0x46, 0x45, 0x94, 0x89, 0xf8, 0x81, 0xd5, 0xf6, 0xb4, 0x88, 0xb1, 0x2a, 0x44, 0x72, 0xd9, 0x87, 0x66, 0xd4, 0xf5, 0x3a, 0xa7, 0x73, 0xa9, 0xa8, 0x86, 0x62, 0xc7, 0x65, 0xc8, 0xc9, 0xa1, 0xf4, 0xd1, 0xe9, 0x5a, 0x92, 0x85, 0xa6, 0xe7, 0x93, 0xe8, 0xc1, 0xc6, 0x7a, 0x64, 0xe1, 0x4a, 0x6a, 0xe6, 0xb3, 0xf1, 0xd3, 0xa5, 0x8a, 0xb2, 0x9a, 0xba, 0x84, 0xa4, 0x63, 0xe5, 0xc5, 0xf3, 0xd2, 0xc4, 0x82, 0xaa, 0xda, 0xe4, 0xf2, 0xca, 0x83, 0xa3, 0xa2, 0xc3, 0xea, 0xc2, 0xe2, 0xe3, 0xff, 0xff}, {0, 2, 2, 1, 4, 1, 4, 1, 3, 3, 1, 0, 0, 0, 0, 140, 0x02, 0x03, 0x01, 0x04, 0x05, 0x12, 0x11, 0x06, 0x13, 0x07, 0x08, 0x14, 0x22, 0x09, 0x21, 0x00, 0x23, 0x15, 0x31, 0x32, 0x0a, 0x16, 0xf0, 0x24, 0x33, 0x41, 0x42, 0x19, 0x17, 0x25, 0x18, 0x51, 0x34, 0x43, 0x52, 0x29, 0x35, 0x61, 0x39, 0x71, 0x62, 0x36, 0x53, 0x26, 0x38, 0x1a, 0x37, 0x81, 0x27, 0x91, 0x79, 0x55, 0x45, 0x28, 0x72, 0x59, 0xa1, 0xb1, 0x44, 0x69, 0x54, 0x58, 0xd1, 0xfa, 0x57, 0xe1, 0xf1, 0xb9, 0x49, 0x47, 0x63, 0x6a, 0xf9, 0x56, 0x46, 0xa8, 0x2a, 0x4a, 0x78, 0x99, 0x3a, 0x75, 0x74, 0x86, 0x65, 0xc1, 0x76, 0xb6, 0x96, 0xd6, 0x89, 0x85, 0xc9, 0xf5, 0x95, 0xb4, 0xc7, 0xf7, 0x8a, 0x97, 0xb8, 0x73, 0xb7, 0xd8, 0xd9, 0x87, 0xa7, 0x7a, 0x48, 0x82, 0x84, 0xea, 0xf4, 0xa6, 0xc5, 0x5a, 0x94, 0xa4, 0xc6, 0x92, 0xc3, 0x68, 0xb5, 0xc8, 0xe4, 0xe5, 0xe6, 0xe9, 0xa2, 0xa3, 0xe3, 0xc2, 0x66, 0x67, 0x93, 0xaa, 0xd4, 0xd5, 0xe7, 0xf8, 0x88, 0x9a, 0xd7, 0x77, 0xc4, 0x64, 0xe2, 0x98, 0xa5, 0xca, 0xda, 0xe8, 0xf3, 0xf6, 0xa9, 0xb2, 0xb3, 0xf2, 0xd2, 0x83, 0xba, 0xd3, 0xff, 0xff}, {0, 0, 6, 2, 1, 3, 3, 2, 5, 1, 2, 2, 8, 10, 0, 117, 0x04, 0x05, 0x03, 0x06, 0x02, 0x07, 0x01, 0x08, 0x09, 0x12, 0x13, 0x14, 0x11, 0x15, 0x0a, 0x16, 0x17, 0xf0, 0x00, 0x22, 0x21, 0x18, 0x23, 0x19, 0x24, 0x32, 0x31, 0x25, 0x33, 0x38, 0x37, 0x34, 0x35, 0x36, 0x39, 0x79, 0x57, 0x58, 0x59, 0x28, 0x56, 0x78, 0x27, 0x41, 0x29, 0x77, 0x26, 0x42, 0x76, 0x99, 0x1a, 0x55, 0x98, 0x97, 0xf9, 0x48, 0x54, 0x96, 0x89, 0x47, 0xb7, 0x49, 0xfa, 0x75, 0x68, 0xb6, 0x67, 0x69, 0xb9, 0xb8, 0xd8, 0x52, 0xd7, 0x88, 0xb5, 0x74, 0x51, 0x46, 0xd9, 0xf8, 0x3a, 0xd6, 0x87, 0x45, 0x7a, 0x95, 0xd5, 0xf6, 0x86, 0xb4, 0xa9, 0x94, 0x53, 0x2a, 0xa8, 0x43, 0xf5, 0xf7, 0xd4, 0x66, 0xa7, 0x5a, 0x44, 0x8a, 0xc9, 0xe8, 0xc8, 0xe7, 0x9a, 0x6a, 0x73, 0x4a, 0x61, 0xc7, 0xf4, 0xc6, 0x65, 0xe9, 0x72, 0xe6, 0x71, 0x91, 0x93, 0xa6, 0xda, 0x92, 0x85, 0x62, 0xf3, 0xc5, 0xb2, 0xa4, 0x84, 0xba, 0x64, 0xa5, 0xb3, 0xd2, 0x81, 0xe5, 0xd3, 0xaa, 0xc4, 0xca, 0xf2, 0xb1, 0xe4, 0xd1, 0x83, 0x63, 0xea, 0xc3, 0xe2, 0x82, 0xf1, 0xa3, 0xc2, 0xa1, 0xc1, 0xe3, 0xa2, 0xe1, 0xff, 0xff}}; if (table > 2) table = 2; huff[0] = make_decoder(first_tree[table]); huff[1] = make_decoder(second_tree[table]); } /* Return 0 if the image starts with compressed data, 1 if it starts with uncompressed low-order bits. In Canon compressed data, 0xff is always followed by 0x00. */ int CLASS canon_has_lowbits() { uchar test[0x4000]; int ret = 1, i; fseek(ifp, 0, SEEK_SET); fread(test, 1, sizeof test, ifp); for (i = 540; i < sizeof test - 1; i++) if (test[i] == 0xff) { if (test[i + 1]) return 1; ret = 0; } return ret; } void CLASS canon_load_raw() { ushort *pixel, *prow, *huff[2]; int nblocks, lowbits, i, c, row, r, save, val; int block, diffbuf[64], leaf, len, diff, carry = 0, pnum = 0, base[2]; crw_init_tables(tiff_compress, huff); lowbits = canon_has_lowbits(); if (!lowbits) maximum = 0x3ff; fseek(ifp, 540 + lowbits * raw_height * raw_width / 4, SEEK_SET); zero_after_ff = 1; getbits(-1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < raw_height; row += 8) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif pixel = raw_image + row * raw_width; nblocks = MIN(8, raw_height - row) * raw_width >> 6; for (block = 0; block < nblocks; block++) { memset(diffbuf, 0, sizeof diffbuf); for (i = 0; i < 64; i++) { leaf = gethuff(huff[i > 0]); if (leaf == 0 && i) break; if (leaf == 0xff) continue; i += leaf >> 4; len = leaf & 15; if (len == 0) continue; diff = getbits(len); if ((diff & (1 << (len - 1))) == 0) diff -= (1 << len) - 1; if (i < 64) diffbuf[i] = diff; } diffbuf[0] += carry; carry = diffbuf[0]; for (i = 0; i < 64; i++) { if (pnum++ % raw_width == 0) base[0] = base[1] = 512; if ((pixel[(block << 6) + i] = base[i & 1] += diffbuf[i]) >> 10) derror(); } } if (lowbits) { save = ftell(ifp); fseek(ifp, 26 + row * raw_width / 4, SEEK_SET); for (prow = pixel, i = 0; i < raw_width * 2; i++) { c = fgetc(ifp); for (r = 0; r < 8; r += 2, prow++) { val = (*prow << 2) + ((c >> r) & 3); if (raw_width == 2672 && val < 512) val += 2; *prow = val; } } fseek(ifp, save, SEEK_SET); } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { FORC(2) free(huff[c]); throw; } #endif FORC(2) free(huff[c]); } //@end COMMON struct jhead { int algo, bits, high, wide, clrs, sraw, psv, restart, vpred[6]; ushort quant[64], idct[64], *huff[20], *free[20], *row; }; //@out COMMON int CLASS ljpeg_start(struct jhead *jh, int info_only) { ushort c, tag, len; int cnt = 0; uchar data[0x10000]; const uchar *dp; memset(jh, 0, sizeof *jh); jh->restart = INT_MAX; if ((fgetc(ifp), fgetc(ifp)) != 0xd8) return 0; do { if (feof(ifp)) return 0; if (cnt++ > 1024) return 0; // 1024 tags limit if (!fread(data, 2, 2, ifp)) return 0; tag = data[0] << 8 | data[1]; len = (data[2] << 8 | data[3]) - 2; if (tag <= 0xff00) return 0; fread(data, 1, len, ifp); switch (tag) { case 0xffc3: // start of frame; lossless, Huffman jh->sraw = ((data[7] >> 4) * (data[7] & 15) - 1) & 3; case 0xffc1: case 0xffc0: jh->algo = tag & 0xff; jh->bits = data[0]; jh->high = data[1] << 8 | data[2]; jh->wide = data[3] << 8 | data[4]; jh->clrs = data[5] + jh->sraw; if (len == 9 && !dng_version) getc(ifp); break; case 0xffc4: // define Huffman tables if (info_only) break; for (dp = data; dp < data + len && !((c = *dp++) & -20);) jh->free[c] = jh->huff[c] = make_decoder_ref(&dp); break; case 0xffda: // start of scan jh->psv = data[1 + data[0] * 2]; jh->bits -= data[3 + data[0] * 2] & 15; break; case 0xffdb: FORC(64) jh->quant[c] = data[c * 2 + 1] << 8 | data[c * 2 + 2]; break; case 0xffdd: jh->restart = data[0] << 8 | data[1]; } } while (tag != 0xffda); if (jh->bits > 16 || jh->clrs > 6 || !jh->bits || !jh->high || !jh->wide || !jh->clrs) return 0; if (info_only) return 1; if (!jh->huff[0]) return 0; FORC(19) if (!jh->huff[c + 1]) jh->huff[c + 1] = jh->huff[c]; if (jh->sraw) { FORC(4) jh->huff[2 + c] = jh->huff[1]; FORC(jh->sraw) jh->huff[1 + c] = jh->huff[0]; } jh->row = (ushort *)calloc(jh->wide * jh->clrs, 4); merror(jh->row, "ljpeg_start()"); return zero_after_ff = 1; } void CLASS ljpeg_end(struct jhead *jh) { int c; FORC4 if (jh->free[c]) free(jh->free[c]); free(jh->row); } int CLASS ljpeg_diff(ushort *huff) { int len, diff; if (!huff) #ifdef LIBRAW_LIBRARY_BUILD throw LIBRAW_EXCEPTION_IO_CORRUPT; #else longjmp(failure, 2); #endif len = gethuff(huff); if (len == 16 && (!dng_version || dng_version >= 0x1010000)) return -32768; diff = getbits(len); if ((diff & (1 << (len - 1))) == 0) diff -= (1 << len) - 1; return diff; } ushort *CLASS ljpeg_row(int jrow, struct jhead *jh) { int col, c, diff, pred, spred = 0; ushort mark = 0, *row[3]; if (jrow * jh->wide % jh->restart == 0) { FORC(6) jh->vpred[c] = 1 << (jh->bits - 1); if (jrow) { fseek(ifp, -2, SEEK_CUR); do mark = (mark << 8) + (c = fgetc(ifp)); while (c != EOF && mark >> 4 != 0xffd); } getbits(-1); } FORC3 row[c] = jh->row + jh->wide * jh->clrs * ((jrow + c) & 1); for (col = 0; col < jh->wide; col++) FORC(jh->clrs) { diff = ljpeg_diff(jh->huff[c]); if (jh->sraw && c <= jh->sraw && (col | c)) pred = spred; else if (col) pred = row[0][-jh->clrs]; else pred = (jh->vpred[c] += diff) - diff; if (jrow && col) switch (jh->psv) { case 1: break; case 2: pred = row[1][0]; break; case 3: pred = row[1][-jh->clrs]; break; case 4: pred = pred + row[1][0] - row[1][-jh->clrs]; break; case 5: pred = pred + ((row[1][0] - row[1][-jh->clrs]) >> 1); break; case 6: pred = row[1][0] + ((pred - row[1][-jh->clrs]) >> 1); break; case 7: pred = (pred + row[1][0]) >> 1; break; default: pred = 0; } if ((**row = pred + diff) >> jh->bits) derror(); if (c <= jh->sraw) spred = **row; row[0]++; row[1]++; } return row[2]; } void CLASS lossless_jpeg_load_raw() { int jwide, jhigh, jrow, jcol, val, jidx, i, j, row = 0, col = 0; struct jhead jh; ushort *rp; if (!ljpeg_start(&jh, 0)) return; if (jh.wide < 1 || jh.high < 1 || jh.clrs < 1 || jh.bits < 1) #ifdef LIBRAW_LIBRARY_BUILD throw LIBRAW_EXCEPTION_IO_CORRUPT; #else longjmp(failure, 2); #endif jwide = jh.wide * jh.clrs; jhigh = jh.high; if (jh.clrs == 4 && jwide >= raw_width * 2) jhigh *= 2; #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (jrow = 0; jrow < jh.high; jrow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif rp = ljpeg_row(jrow, &jh); if (load_flags & 1) row = jrow & 1 ? height - 1 - jrow / 2 : jrow / 2; for (jcol = 0; jcol < jwide; jcol++) { val = curve[*rp++]; if (cr2_slice[0]) { jidx = jrow * jwide + jcol; i = jidx / (cr2_slice[1] * raw_height); if ((j = i >= cr2_slice[0])) i = cr2_slice[0]; jidx -= i * (cr2_slice[1] * raw_height); row = jidx / cr2_slice[1 + j]; col = jidx % cr2_slice[1 + j] + i * cr2_slice[1]; } if (raw_width == 3984 && (col -= 2) < 0) col += (row--, raw_width); if (row > raw_height) #ifdef LIBRAW_LIBRARY_BUILD throw LIBRAW_EXCEPTION_IO_CORRUPT; #else longjmp(failure, 3); #endif if ((unsigned)row < raw_height) RAW(row, col) = val; if (++col >= raw_width) col = (row++, 0); } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end(&jh); throw; } #endif ljpeg_end(&jh); } void CLASS canon_sraw_load_raw() { struct jhead jh; short *rp = 0, (*ip)[4]; int jwide, slice, scol, ecol, row, col, jrow = 0, jcol = 0, pix[3], c; int v[3] = {0, 0, 0}, ver, hue; #ifdef LIBRAW_LIBRARY_BUILD int saved_w = width, saved_h = height; #endif char *cp; if (!ljpeg_start(&jh, 0) || jh.clrs < 4) return; jwide = (jh.wide >>= 1) * jh.clrs; #ifdef LIBRAW_LIBRARY_BUILD if (load_flags & 256) { width = raw_width; height = raw_height; } try { #endif for (ecol = slice = 0; slice <= cr2_slice[0]; slice++) { scol = ecol; ecol += cr2_slice[1] * 2 / jh.clrs; if (!cr2_slice[0] || ecol > raw_width - 1) ecol = raw_width & -2; for (row = 0; row < height; row += (jh.clrs >> 1) - 1) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif ip = (short(*)[4])image + row * width; for (col = scol; col < ecol; col += 2, jcol += jh.clrs) { if ((jcol %= jwide) == 0) rp = (short *)ljpeg_row(jrow++, &jh); if (col >= width) continue; #ifdef LIBRAW_LIBRARY_BUILD if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE) { FORC(jh.clrs - 2) { ip[col + (c >> 1) * width + (c & 1)][0] = rp[jcol + c]; ip[col + (c >> 1) * width + (c & 1)][1] = ip[col + (c >> 1) * width + (c & 1)][2] = 8192; } ip[col][1] = rp[jcol + jh.clrs - 2] - 8192; ip[col][2] = rp[jcol + jh.clrs - 1] - 8192; } else if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_RGB) { FORC(jh.clrs - 2) ip[col + (c >> 1) * width + (c & 1)][0] = rp[jcol + c]; ip[col][1] = rp[jcol + jh.clrs - 2] - 8192; ip[col][2] = rp[jcol + jh.clrs - 1] - 8192; } else #endif { FORC(jh.clrs - 2) ip[col + (c >> 1) * width + (c & 1)][0] = rp[jcol + c]; ip[col][1] = rp[jcol + jh.clrs - 2] - 16384; ip[col][2] = rp[jcol + jh.clrs - 1] - 16384; } } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end(&jh); throw; } #endif #ifdef LIBRAW_LIBRARY_BUILD if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE) { ljpeg_end(&jh); maximum = 0x3fff; height = saved_h; width = saved_w; return; } #endif #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (cp = model2; *cp && !isdigit(*cp); cp++) ; sscanf(cp, "%d.%d.%d", v, v + 1, v + 2); ver = (v[0] * 1000 + v[1]) * 1000 + v[2]; hue = (jh.sraw + 1) << 2; if (unique_id >= 0x80000281 || (unique_id == 0x80000218 && ver > 1000006)) hue = jh.sraw << 1; ip = (short(*)[4])image; rp = ip[0]; for (row = 0; row < height; row++, ip += width) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (row & (jh.sraw >> 1)) { for (col = 0; col < width; col += 2) for (c = 1; c < 3; c++) if (row == height - 1) { ip[col][c] = ip[col - width][c]; } else { ip[col][c] = (ip[col - width][c] + ip[col + width][c] + 1) >> 1; } } for (col = 1; col < width; col += 2) for (c = 1; c < 3; c++) if (col == width - 1) ip[col][c] = ip[col - 1][c]; else ip[col][c] = (ip[col - 1][c] + ip[col + 1][c] + 1) >> 1; } #ifdef LIBRAW_LIBRARY_BUILD if (!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_RGB)) #endif for (; rp < ip[0]; rp += 4) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (unique_id == 0x80000218 || unique_id == 0x80000250 || unique_id == 0x80000261 || unique_id == 0x80000281 || unique_id == 0x80000287) { rp[1] = (rp[1] << 2) + hue; rp[2] = (rp[2] << 2) + hue; pix[0] = rp[0] + ((50 * rp[1] + 22929 * rp[2]) >> 14); pix[1] = rp[0] + ((-5640 * rp[1] - 11751 * rp[2]) >> 14); pix[2] = rp[0] + ((29040 * rp[1] - 101 * rp[2]) >> 14); } else { if (unique_id < 0x80000218) rp[0] -= 512; pix[0] = rp[0] + rp[2]; pix[2] = rp[0] + rp[1]; pix[1] = rp[0] + ((-778 * rp[1] - (rp[2] << 11)) >> 12); } FORC3 rp[c] = CLIP(pix[c] * sraw_mul[c] >> 10); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end(&jh); throw; } height = saved_h; width = saved_w; #endif ljpeg_end(&jh); maximum = 0x3fff; } void CLASS adobe_copy_pixel(unsigned row, unsigned col, ushort **rp) { int c; if (tiff_samples == 2 && shot_select) (*rp)++; if (raw_image) { if (row < raw_height && col < raw_width) RAW(row, col) = curve[**rp]; *rp += tiff_samples; } else { #ifdef LIBRAW_LIBRARY_BUILD FORC(tiff_samples) image[row * raw_width + col][c] = curve[(*rp)[c]]; *rp += tiff_samples; #else if (row < height && col < width) FORC(tiff_samples) image[row * width + col][c] = curve[(*rp)[c]]; *rp += tiff_samples; #endif } if (tiff_samples == 2 && shot_select) (*rp)--; } void CLASS ljpeg_idct(struct jhead *jh) { int c, i, j, len, skip, coef; float work[3][8][8]; static float cs[106] = {0}; static const uchar zigzag[80] = {0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63}; if (!cs[0]) FORC(106) cs[c] = cos((c & 31) * M_PI / 16) / 2; memset(work, 0, sizeof work); work[0][0][0] = jh->vpred[0] += ljpeg_diff(jh->huff[0]) * jh->quant[0]; for (i = 1; i < 64; i++) { len = gethuff(jh->huff[16]); i += skip = len >> 4; if (!(len &= 15) && skip < 15) break; coef = getbits(len); if ((coef & (1 << (len - 1))) == 0) coef -= (1 << len) - 1; ((float *)work)[zigzag[i]] = coef * jh->quant[i]; } FORC(8) work[0][0][c] *= M_SQRT1_2; FORC(8) work[0][c][0] *= M_SQRT1_2; for (i = 0; i < 8; i++) for (j = 0; j < 8; j++) FORC(8) work[1][i][j] += work[0][i][c] * cs[(j * 2 + 1) * c]; for (i = 0; i < 8; i++) for (j = 0; j < 8; j++) FORC(8) work[2][i][j] += work[1][c][j] * cs[(i * 2 + 1) * c]; FORC(64) jh->idct[c] = CLIP(((float *)work[2])[c] + 0.5); } void CLASS lossless_dng_load_raw() { unsigned save, trow = 0, tcol = 0, jwide, jrow, jcol, row, col, i, j; struct jhead jh; ushort *rp; while (trow < raw_height) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif save = ftell(ifp); if (tile_length < INT_MAX) fseek(ifp, get4(), SEEK_SET); if (!ljpeg_start(&jh, 0)) break; jwide = jh.wide; if (filters) jwide *= jh.clrs; jwide /= MIN(is_raw, tiff_samples); #ifdef LIBRAW_LIBRARY_BUILD try { #endif switch (jh.algo) { case 0xc1: jh.vpred[0] = 16384; getbits(-1); for (jrow = 0; jrow + 7 < jh.high; jrow += 8) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (jcol = 0; jcol + 7 < jh.wide; jcol += 8) { ljpeg_idct(&jh); rp = jh.idct; row = trow + jcol / tile_width + jrow * 2; col = tcol + jcol % tile_width; for (i = 0; i < 16; i += 2) for (j = 0; j < 8; j++) adobe_copy_pixel(row + i, col + j, &rp); } } break; case 0xc3: for (row = col = jrow = 0; jrow < jh.high; jrow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif rp = ljpeg_row(jrow, &jh); for (jcol = 0; jcol < jwide; jcol++) { adobe_copy_pixel(trow + row, tcol + col, &rp); if (++col >= tile_width || col >= raw_width) row += 1 + (col = 0); } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end(&jh); throw; } #endif fseek(ifp, save + 4, SEEK_SET); if ((tcol += tile_width) >= raw_width) trow += tile_length + (tcol = 0); ljpeg_end(&jh); } } void CLASS packed_dng_load_raw() { ushort *pixel, *rp; int row, col; pixel = (ushort *)calloc(raw_width, tiff_samples * sizeof *pixel); merror(pixel, "packed_dng_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (tiff_bps == 16) read_shorts(pixel, raw_width * tiff_samples); else { getbits(-1); for (col = 0; col < raw_width * tiff_samples; col++) pixel[col] = getbits(tiff_bps); } for (rp = pixel, col = 0; col < raw_width; col++) adobe_copy_pixel(row, col, &rp); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free(pixel); } void CLASS pentax_load_raw() { ushort bit[2][15], huff[4097]; int dep, row, col, diff, c, i; ushort vpred[2][2] = {{0, 0}, {0, 0}}, hpred[2]; fseek(ifp, meta_offset, SEEK_SET); dep = (get2() + 12) & 15; fseek(ifp, 12, SEEK_CUR); FORC(dep) bit[0][c] = get2(); FORC(dep) bit[1][c] = fgetc(ifp); FORC(dep) for (i = bit[0][c]; i <= ((bit[0][c] + (4096 >> bit[1][c]) - 1) & 4095);) huff[++i] = bit[1][c] << 8 | c; huff[0] = 12; fseek(ifp, data_offset, SEEK_SET); getbits(-1); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < raw_width; col++) { diff = ljpeg_diff(huff); if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; RAW(row, col) = hpred[col & 1]; if (hpred[col & 1] >> tiff_bps) derror(); } } } #ifdef LIBRAW_LIBRARY_BUILD void CLASS nikon_coolscan_load_raw() { int bufsize = width * 3 * tiff_bps / 8; if (tiff_bps <= 8) gamma_curve(1.0 / imgdata.params.coolscan_nef_gamma, 0., 1, 255); else gamma_curve(1.0 / imgdata.params.coolscan_nef_gamma, 0., 1, 65535); fseek(ifp, data_offset, SEEK_SET); unsigned char *buf = (unsigned char *)malloc(bufsize); unsigned short *ubuf = (unsigned short *)buf; for (int row = 0; row < raw_height; row++) { int red = fread(buf, 1, bufsize, ifp); unsigned short(*ip)[4] = (unsigned short(*)[4])image + row * width; if (tiff_bps <= 8) for (int col = 0; col < width; col++) { ip[col][0] = curve[buf[col * 3]]; ip[col][1] = curve[buf[col * 3 + 1]]; ip[col][2] = curve[buf[col * 3 + 2]]; ip[col][3] = 0; } else for (int col = 0; col < width; col++) { ip[col][0] = curve[ubuf[col * 3]]; ip[col][1] = curve[ubuf[col * 3 + 1]]; ip[col][2] = curve[ubuf[col * 3 + 2]]; ip[col][3] = 0; } } free(buf); } #endif void CLASS nikon_load_raw() { static const uchar nikon_tree[][32] = { {0, 1, 5, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, /* 12-bit lossy */ 5, 4, 3, 6, 2, 7, 1, 0, 8, 9, 11, 10, 12}, {0, 1, 5, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, /* 12-bit lossy after split */ 0x39, 0x5a, 0x38, 0x27, 0x16, 5, 4, 3, 2, 1, 0, 11, 12, 12}, {0, 1, 4, 2, 3, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 12-bit lossless */ 5, 4, 6, 3, 7, 2, 8, 1, 9, 0, 10, 11, 12}, {0, 1, 4, 3, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, /* 14-bit lossy */ 5, 6, 4, 7, 8, 3, 9, 2, 1, 0, 10, 11, 12, 13, 14}, {0, 1, 5, 1, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, /* 14-bit lossy after split */ 8, 0x5c, 0x4b, 0x3a, 0x29, 7, 6, 5, 4, 3, 2, 1, 0, 13, 14}, {0, 1, 4, 2, 2, 3, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, /* 14-bit lossless */ 7, 6, 8, 5, 9, 4, 10, 3, 11, 12, 2, 0, 1, 13, 14}}; ushort *huff, ver0, ver1, vpred[2][2], hpred[2], csize; int i, min, max, step = 0, tree = 0, split = 0, row, col, len, shl, diff; fseek(ifp, meta_offset, SEEK_SET); ver0 = fgetc(ifp); ver1 = fgetc(ifp); if (ver0 == 0x49 || ver1 == 0x58) fseek(ifp, 2110, SEEK_CUR); if (ver0 == 0x46) tree = 2; if (tiff_bps == 14) tree += 3; read_shorts(vpred[0], 4); max = 1 << tiff_bps & 0x7fff; if ((csize = get2()) > 1) step = max / (csize - 1); if (ver0 == 0x44 && ver1 == 0x20 && step > 0) { for (i = 0; i < csize; i++) curve[i * step] = get2(); for (i = 0; i < max; i++) curve[i] = (curve[i - i % step] * (step - i % step) + curve[i - i % step + step] * (i % step)) / step; fseek(ifp, meta_offset + 562, SEEK_SET); split = get2(); } else if (ver0 != 0x46 && csize <= 0x4001) read_shorts(curve, max = csize); while (curve[max - 2] == curve[max - 1]) max--; huff = make_decoder(nikon_tree[tree]); fseek(ifp, data_offset, SEEK_SET); getbits(-1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (min = row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (split && row == split) { free(huff); huff = make_decoder(nikon_tree[tree + 1]); max += (min = 16) << 1; } for (col = 0; col < raw_width; col++) { i = gethuff(huff); len = i & 15; shl = i >> 4; diff = ((getbits(len - shl) << 1) + 1) << shl >> 1; if ((diff & (1 << (len - 1))) == 0) diff -= (1 << len) - !shl; if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; if ((ushort)(hpred[col & 1] + min) >= max) derror(); RAW(row, col) = curve[LIM((short)hpred[col & 1], 0, 0x3fff)]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(huff); throw; } #endif free(huff); } void CLASS nikon_yuv_load_raw() { int row, col, yuv[4], rgb[3], b, c; UINT64 bitbuf = 0; float cmul[4]; FORC4 { cmul[c] = cam_mul[c] > 0.001f ? cam_mul[c] : 1.f; } for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < raw_width; col++) { if (!(b = col & 1)) { bitbuf = 0; FORC(6) bitbuf |= (UINT64)fgetc(ifp) << c * 8; FORC(4) yuv[c] = (bitbuf >> c * 12 & 0xfff) - (c >> 1 << 11); } rgb[0] = yuv[b] + 1.370705 * yuv[3]; rgb[1] = yuv[b] - 0.337633 * yuv[2] - 0.698001 * yuv[3]; rgb[2] = yuv[b] + 1.732446 * yuv[2]; FORC3 image[row * width + col][c] = curve[LIM(rgb[c], 0, 0xfff)] / cmul[c]; } } } /* Returns 1 for a Coolpix 995, 0 for anything else. */ int CLASS nikon_e995() { int i, histo[256]; const uchar often[] = {0x00, 0x55, 0xaa, 0xff}; memset(histo, 0, sizeof histo); fseek(ifp, -2000, SEEK_END); for (i = 0; i < 2000; i++) histo[fgetc(ifp)]++; for (i = 0; i < 4; i++) if (histo[often[i]] < 200) return 0; return 1; } /* Returns 1 for a Coolpix 2100, 0 for anything else. */ int CLASS nikon_e2100() { uchar t[12]; int i; fseek(ifp, 0, SEEK_SET); for (i = 0; i < 1024; i++) { fread(t, 1, 12, ifp); if (((t[2] & t[4] & t[7] & t[9]) >> 4 & t[1] & t[6] & t[8] & t[11] & 3) != 3) return 0; } return 1; } void CLASS nikon_3700() { int bits, i; uchar dp[24]; static const struct { int bits; char t_make[12], t_model[15]; } table[] = { {0x00, "Pentax", "Optio 33WR"}, {0x03, "Nikon", "E3200"}, {0x32, "Nikon", "E3700"}, {0x33, "Olympus", "C740UZ"}}; fseek(ifp, 3072, SEEK_SET); fread(dp, 1, 24, ifp); bits = (dp[8] & 3) << 4 | (dp[20] & 3); for (i = 0; i < sizeof table / sizeof *table; i++) if (bits == table[i].bits) { strcpy(make, table[i].t_make); strcpy(model, table[i].t_model); } } /* Separates a Minolta DiMAGE Z2 from a Nikon E4300. */ int CLASS minolta_z2() { int i, nz; char tail[424]; fseek(ifp, -sizeof tail, SEEK_END); fread(tail, 1, sizeof tail, ifp); for (nz = i = 0; i < sizeof tail; i++) if (tail[i]) nz++; return nz > 20; } //@end COMMON void CLASS jpeg_thumb(); //@out COMMON void CLASS ppm_thumb() { char *thumb; thumb_length = thumb_width * thumb_height * 3; thumb = (char *)malloc(thumb_length); merror(thumb, "ppm_thumb()"); fprintf(ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); fread(thumb, 1, thumb_length, ifp); fwrite(thumb, 1, thumb_length, ofp); free(thumb); } void CLASS ppm16_thumb() { int i; char *thumb; thumb_length = thumb_width * thumb_height * 3; thumb = (char *)calloc(thumb_length, 2); merror(thumb, "ppm16_thumb()"); read_shorts((ushort *)thumb, thumb_length); for (i = 0; i < thumb_length; i++) thumb[i] = ((ushort *)thumb)[i] >> 8; fprintf(ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); fwrite(thumb, 1, thumb_length, ofp); free(thumb); } void CLASS layer_thumb() { int i, c; char *thumb, map[][4] = {"012", "102"}; colors = thumb_misc >> 5 & 7; thumb_length = thumb_width * thumb_height; thumb = (char *)calloc(colors, thumb_length); merror(thumb, "layer_thumb()"); fprintf(ofp, "P%d\n%d %d\n255\n", 5 + (colors >> 1), thumb_width, thumb_height); fread(thumb, thumb_length, colors, ifp); for (i = 0; i < thumb_length; i++) FORCC putc(thumb[i + thumb_length * (map[thumb_misc >> 8][c] - '0')], ofp); free(thumb); } void CLASS rollei_thumb() { unsigned i; ushort *thumb; thumb_length = thumb_width * thumb_height; thumb = (ushort *)calloc(thumb_length, 2); merror(thumb, "rollei_thumb()"); fprintf(ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); read_shorts(thumb, thumb_length); for (i = 0; i < thumb_length; i++) { putc(thumb[i] << 3, ofp); putc(thumb[i] >> 5 << 2, ofp); putc(thumb[i] >> 11 << 3, ofp); } free(thumb); } void CLASS rollei_load_raw() { uchar pixel[10]; unsigned iten = 0, isix, i, buffer = 0, todo[16]; isix = raw_width * raw_height * 5 / 8; while (fread(pixel, 1, 10, ifp) == 10) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (i = 0; i < 10; i += 2) { todo[i] = iten++; todo[i + 1] = pixel[i] << 8 | pixel[i + 1]; buffer = pixel[i] >> 2 | buffer << 6; } for (; i < 16; i += 2) { todo[i] = isix++; todo[i + 1] = buffer >> (14 - i) * 5; } for (i = 0; i < 16; i += 2) raw_image[todo[i]] = (todo[i + 1] & 0x3ff); } maximum = 0x3ff; } int CLASS raw(unsigned row, unsigned col) { return (row < raw_height && col < raw_width) ? RAW(row, col) : 0; } void CLASS phase_one_flat_field(int is_float, int nc) { ushort head[8]; unsigned wide, high, y, x, c, rend, cend, row, col; float *mrow, num, mult[4]; read_shorts(head, 8); if (head[2] * head[3] * head[4] * head[5] == 0) return; wide = head[2] / head[4] + (head[2] % head[4] != 0); high = head[3] / head[5] + (head[3] % head[5] != 0); mrow = (float *)calloc(nc * wide, sizeof *mrow); merror(mrow, "phase_one_flat_field()"); for (y = 0; y < high; y++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (x = 0; x < wide; x++) for (c = 0; c < nc; c += 2) { num = is_float ? getreal(11) : get2() / 32768.0; if (y == 0) mrow[c * wide + x] = num; else mrow[(c + 1) * wide + x] = (num - mrow[c * wide + x]) / head[5]; } if (y == 0) continue; rend = head[1] + y * head[5]; for (row = rend - head[5]; row < raw_height && row < rend && row < head[1] + head[3] - head[5]; row++) { for (x = 1; x < wide; x++) { for (c = 0; c < nc; c += 2) { mult[c] = mrow[c * wide + x - 1]; mult[c + 1] = (mrow[c * wide + x] - mult[c]) / head[4]; } cend = head[0] + x * head[4]; for (col = cend - head[4]; col < raw_width && col < cend && col < head[0] + head[2] - head[4]; col++) { c = nc > 2 ? FC(row - top_margin, col - left_margin) : 0; if (!(c & 1)) { c = RAW(row, col) * mult[c]; RAW(row, col) = LIM(c, 0, 65535); } for (c = 0; c < nc; c += 2) mult[c] += mult[c + 1]; } } for (x = 0; x < wide; x++) for (c = 0; c < nc; c += 2) mrow[c * wide + x] += mrow[(c + 1) * wide + x]; } } free(mrow); } int CLASS phase_one_correct() { unsigned entries, tag, data, save, col, row, type; int len, i, j, k, cip, val[4], dev[4], sum, max; int head[9], diff, mindiff = INT_MAX, off_412 = 0; /* static */ const signed char dir[12][2] = {{-1, -1}, {-1, 1}, {1, -1}, {1, 1}, {-2, 0}, {0, -2}, {0, 2}, {2, 0}, {-2, -2}, {-2, 2}, {2, -2}, {2, 2}}; float poly[8], num, cfrac, frac, mult[2], *yval[2] = {NULL, NULL}; ushort *xval[2]; int qmult_applied = 0, qlin_applied = 0; #ifdef LIBRAW_LIBRARY_BUILD if (!meta_length) #else if (half_size || !meta_length) #endif return 0; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Phase One correction...\n")); #endif fseek(ifp, meta_offset, SEEK_SET); order = get2(); fseek(ifp, 6, SEEK_CUR); fseek(ifp, meta_offset + get4(), SEEK_SET); entries = get4(); get4(); #ifdef LIBRAW_LIBRARY_BUILD try { #endif while (entries--) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif tag = get4(); len = get4(); data = get4(); save = ftell(ifp); fseek(ifp, meta_offset + data, SEEK_SET); if (tag == 0x419) { /* Polynomial curve */ for (get4(), i = 0; i < 8; i++) poly[i] = getreal(11); poly[3] += (ph1.tag_210 - poly[7]) * poly[6] + 1; for (i = 0; i < 0x10000; i++) { num = (poly[5] * i + poly[3]) * i + poly[1]; curve[i] = LIM(num, 0, 65535); } goto apply; /* apply to right half */ } else if (tag == 0x41a) { /* Polynomial curve */ for (i = 0; i < 4; i++) poly[i] = getreal(11); for (i = 0; i < 0x10000; i++) { for (num = 0, j = 4; j--;) num = num * i + poly[j]; curve[i] = LIM(num + i, 0, 65535); } apply: /* apply to whole image */ for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = (tag & 1) * ph1.split_col; col < raw_width; col++) RAW(row, col) = curve[RAW(row, col)]; } } else if (tag == 0x400) { /* Sensor defects */ while ((len -= 8) >= 0) { col = get2(); row = get2(); type = get2(); get2(); if (col >= raw_width) continue; if (type == 131 || type == 137) /* Bad column */ for (row = 0; row < raw_height; row++) if (FC(row - top_margin, col - left_margin) == 1) { for (sum = i = 0; i < 4; i++) sum += val[i] = raw(row + dir[i][0], col + dir[i][1]); for (max = i = 0; i < 4; i++) { dev[i] = abs((val[i] << 2) - sum); if (dev[max] < dev[i]) max = i; } RAW(row, col) = (sum - val[max]) / 3.0 + 0.5; } else { for (sum = 0, i = 8; i < 12; i++) sum += raw(row + dir[i][0], col + dir[i][1]); RAW(row, col) = 0.5 + sum * 0.0732233 + (raw(row, col - 2) + raw(row, col + 2)) * 0.3535534; } else if (type == 129) { /* Bad pixel */ if (row >= raw_height) continue; j = (FC(row - top_margin, col - left_margin) != 1) * 4; for (sum = 0, i = j; i < j + 8; i++) sum += raw(row + dir[i][0], col + dir[i][1]); RAW(row, col) = (sum + 4) >> 3; } } } else if (tag == 0x401) { /* All-color flat fields */ phase_one_flat_field(1, 2); } else if (tag == 0x416 || tag == 0x410) { phase_one_flat_field(0, 2); } else if (tag == 0x40b) { /* Red+blue flat field */ phase_one_flat_field(0, 4); } else if (tag == 0x412) { fseek(ifp, 36, SEEK_CUR); diff = abs(get2() - ph1.tag_21a); if (mindiff > diff) { mindiff = diff; off_412 = ftell(ifp) - 38; } } else if (tag == 0x41f && !qlin_applied) { /* Quadrant linearization */ ushort lc[2][2][16], ref[16]; int qr, qc; for (qr = 0; qr < 2; qr++) for (qc = 0; qc < 2; qc++) for (i = 0; i < 16; i++) lc[qr][qc][i] = get4(); for (i = 0; i < 16; i++) { int v = 0; for (qr = 0; qr < 2; qr++) for (qc = 0; qc < 2; qc++) v += lc[qr][qc][i]; ref[i] = (v + 2) >> 2; } for (qr = 0; qr < 2; qr++) { for (qc = 0; qc < 2; qc++) { int cx[19], cf[19]; for (i = 0; i < 16; i++) { cx[1 + i] = lc[qr][qc][i]; cf[1 + i] = ref[i]; } cx[0] = cf[0] = 0; cx[17] = cf[17] = ((unsigned int)ref[15] * 65535) / lc[qr][qc][15]; cf[18] = cx[18] = 65535; cubic_spline(cx, cf, 19); for (row = (qr ? ph1.split_row : 0); row < (qr ? raw_height : ph1.split_row); row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = (qc ? ph1.split_col : 0); col < (qc ? raw_width : ph1.split_col); col++) RAW(row, col) = curve[RAW(row, col)]; } } } qlin_applied = 1; } else if (tag == 0x41e && !qmult_applied) { /* Quadrant multipliers */ float qmult[2][2] = {{1, 1}, {1, 1}}; get4(); get4(); get4(); get4(); qmult[0][0] = 1.0 + getreal(11); get4(); get4(); get4(); get4(); get4(); qmult[0][1] = 1.0 + getreal(11); get4(); get4(); get4(); qmult[1][0] = 1.0 + getreal(11); get4(); get4(); get4(); qmult[1][1] = 1.0 + getreal(11); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < raw_width; col++) { i = qmult[row >= ph1.split_row][col >= ph1.split_col] * RAW(row, col); RAW(row, col) = LIM(i, 0, 65535); } } qmult_applied = 1; } else if (tag == 0x431 && !qmult_applied) { /* Quadrant combined */ ushort lc[2][2][7], ref[7]; int qr, qc; for (i = 0; i < 7; i++) ref[i] = get4(); for (qr = 0; qr < 2; qr++) for (qc = 0; qc < 2; qc++) for (i = 0; i < 7; i++) lc[qr][qc][i] = get4(); for (qr = 0; qr < 2; qr++) { for (qc = 0; qc < 2; qc++) { int cx[9], cf[9]; for (i = 0; i < 7; i++) { cx[1 + i] = ref[i]; cf[1 + i] = ((unsigned)ref[i] * lc[qr][qc][i]) / 10000; } cx[0] = cf[0] = 0; cx[8] = cf[8] = 65535; cubic_spline(cx, cf, 9); for (row = (qr ? ph1.split_row : 0); row < (qr ? raw_height : ph1.split_row); row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = (qc ? ph1.split_col : 0); col < (qc ? raw_width : ph1.split_col); col++) RAW(row, col) = curve[RAW(row, col)]; } } } qmult_applied = 1; qlin_applied = 1; } fseek(ifp, save, SEEK_SET); } if (off_412) { fseek(ifp, off_412, SEEK_SET); for (i = 0; i < 9; i++) head[i] = get4() & 0x7fff; yval[0] = (float *)calloc(head[1] * head[3] + head[2] * head[4], 6); merror(yval[0], "phase_one_correct()"); yval[1] = (float *)(yval[0] + head[1] * head[3]); xval[0] = (ushort *)(yval[1] + head[2] * head[4]); xval[1] = (ushort *)(xval[0] + head[1] * head[3]); get2(); for (i = 0; i < 2; i++) for (j = 0; j < head[i + 1] * head[i + 3]; j++) yval[i][j] = getreal(11); for (i = 0; i < 2; i++) for (j = 0; j < head[i + 1] * head[i + 3]; j++) xval[i][j] = get2(); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < raw_width; col++) { cfrac = (float)col * head[3] / raw_width; cfrac -= cip = cfrac; num = RAW(row, col) * 0.5; for (i = cip; i < cip + 2; i++) { for (k = j = 0; j < head[1]; j++) if (num < xval[0][k = head[1] * i + j]) break; frac = (j == 0 || j == head[1]) ? 0 : (xval[0][k] - num) / (xval[0][k] - xval[0][k - 1]); mult[i - cip] = yval[0][k - 1] * frac + yval[0][k] * (1 - frac); } i = ((mult[0] * (1 - cfrac) + mult[1] * cfrac) * row + num) * 2; RAW(row, col) = LIM(i, 0, 65535); } } free(yval[0]); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { if (yval[0]) free(yval[0]); return LIBRAW_CANCELLED_BY_CALLBACK; } #endif return 0; } void CLASS phase_one_load_raw() { int a, b, i; ushort akey, bkey, t_mask; fseek(ifp, ph1.key_off, SEEK_SET); akey = get2(); bkey = get2(); t_mask = ph1.format == 1 ? 0x5555 : 0x1354; #ifdef LIBRAW_LIBRARY_BUILD if (ph1.black_col || ph1.black_row) { imgdata.rawdata.ph1_cblack = (short(*)[2])calloc(raw_height * 2, sizeof(ushort)); merror(imgdata.rawdata.ph1_cblack, "phase_one_load_raw()"); imgdata.rawdata.ph1_rblack = (short(*)[2])calloc(raw_width * 2, sizeof(ushort)); merror(imgdata.rawdata.ph1_rblack, "phase_one_load_raw()"); if (ph1.black_col) { fseek(ifp, ph1.black_col, SEEK_SET); read_shorts((ushort *)imgdata.rawdata.ph1_cblack[0], raw_height * 2); } if (ph1.black_row) { fseek(ifp, ph1.black_row, SEEK_SET); read_shorts((ushort *)imgdata.rawdata.ph1_rblack[0], raw_width * 2); } } #endif fseek(ifp, data_offset, SEEK_SET); read_shorts(raw_image, raw_width * raw_height); if (ph1.format) for (i = 0; i < raw_width * raw_height; i += 2) { a = raw_image[i + 0] ^ akey; b = raw_image[i + 1] ^ bkey; raw_image[i + 0] = (a & t_mask) | (b & ~t_mask); raw_image[i + 1] = (b & t_mask) | (a & ~t_mask); } } unsigned CLASS ph1_bithuff(int nbits, ushort *huff) { #ifndef LIBRAW_NOTHREADS #define bitbuf tls->ph1_bits.bitbuf #define vbits tls->ph1_bits.vbits #else static UINT64 bitbuf = 0; static int vbits = 0; #endif unsigned c; if (nbits == -1) return bitbuf = vbits = 0; if (nbits == 0) return 0; if (vbits < nbits) { bitbuf = bitbuf << 32 | get4(); vbits += 32; } c = bitbuf << (64 - vbits) >> (64 - nbits); if (huff) { vbits -= huff[c] >> 8; return (uchar)huff[c]; } vbits -= nbits; return c; #ifndef LIBRAW_NOTHREADS #undef bitbuf #undef vbits #endif } #define ph1_bits(n) ph1_bithuff(n, 0) #define ph1_huff(h) ph1_bithuff(*h, h + 1) void CLASS phase_one_load_raw_c() { static const int length[] = {8, 7, 6, 9, 11, 10, 5, 12, 14, 13}; int *offset, len[2], pred[2], row, col, i, j; ushort *pixel; short(*c_black)[2], (*r_black)[2]; #ifdef LIBRAW_LIBRARY_BUILD if (ph1.format == 6) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif pixel = (ushort *)calloc(raw_width * 3 + raw_height * 4, 2); merror(pixel, "phase_one_load_raw_c()"); offset = (int *)(pixel + raw_width); fseek(ifp, strip_offset, SEEK_SET); for (row = 0; row < raw_height; row++) offset[row] = get4(); c_black = (short(*)[2])(offset + raw_height); fseek(ifp, ph1.black_col, SEEK_SET); if (ph1.black_col) read_shorts((ushort *)c_black[0], raw_height * 2); r_black = c_black + raw_height; fseek(ifp, ph1.black_row, SEEK_SET); if (ph1.black_row) read_shorts((ushort *)r_black[0], raw_width * 2); #ifdef LIBRAW_LIBRARY_BUILD // Copy data to internal copy (ever if not read) if (ph1.black_col || ph1.black_row) { imgdata.rawdata.ph1_cblack = (short(*)[2])calloc(raw_height * 2, sizeof(ushort)); merror(imgdata.rawdata.ph1_cblack, "phase_one_load_raw_c()"); memmove(imgdata.rawdata.ph1_cblack, (ushort *)c_black[0], raw_height * 2 * sizeof(ushort)); imgdata.rawdata.ph1_rblack = (short(*)[2])calloc(raw_width * 2, sizeof(ushort)); merror(imgdata.rawdata.ph1_rblack, "phase_one_load_raw_c()"); memmove(imgdata.rawdata.ph1_rblack, (ushort *)r_black[0], raw_width * 2 * sizeof(ushort)); } #endif for (i = 0; i < 256; i++) curve[i] = i * i / 3.969 + 0.5; #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek(ifp, data_offset + offset[row], SEEK_SET); ph1_bits(-1); pred[0] = pred[1] = 0; for (col = 0; col < raw_width; col++) { if (col >= (raw_width & -8)) len[0] = len[1] = 14; else if ((col & 7) == 0) for (i = 0; i < 2; i++) { for (j = 0; j < 5 && !ph1_bits(1); j++) ; if (j--) len[i] = length[j * 2 + ph1_bits(1)]; } if ((i = len[col & 1]) == 14) pixel[col] = pred[col & 1] = ph1_bits(16); else pixel[col] = pred[col & 1] += ph1_bits(i) + 1 - (1 << (i - 1)); if (pred[col & 1] >> 16) derror(); if (ph1.format == 5 && pixel[col] < 256) pixel[col] = curve[pixel[col]]; } #ifndef LIBRAW_LIBRARY_BUILD for (col = 0; col < raw_width; col++) { int shift = ph1.format == 8 ? 0 : 2; i = (pixel[col] << shift) - ph1.t_black + c_black[row][col >= ph1.split_col] + r_black[col][row >= ph1.split_row]; if (i > 0) RAW(row, col) = i; } #else if (ph1.format == 8) memmove(&RAW(row, 0), &pixel[0], raw_width * 2); else for (col = 0; col < raw_width; col++) RAW(row, col) = pixel[col] << 2; #endif } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free(pixel); maximum = 0xfffc - ph1.t_black; } void CLASS hasselblad_load_raw() { struct jhead jh; int shot, row, col, *back[5], len[2], diff[12], pred, sh, f, s, c; unsigned upix, urow, ucol; ushort *ip; if (!ljpeg_start(&jh, 0)) return; order = 0x4949; ph1_bits(-1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif back[4] = (int *)calloc(raw_width, 3 * sizeof **back); merror(back[4], "hasselblad_load_raw()"); FORC3 back[c] = back[4] + c * raw_width; cblack[6] >>= sh = tiff_samples > 1; shot = LIM(shot_select, 1, tiff_samples) - 1; for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif FORC4 back[(c + 3) & 3] = back[c]; for (col = 0; col < raw_width; col += 2) { for (s = 0; s < tiff_samples * 2; s += 2) { FORC(2) len[c] = ph1_huff(jh.huff[0]); FORC(2) { diff[s + c] = ph1_bits(len[c]); if ((diff[s + c] & (1 << (len[c] - 1))) == 0) diff[s + c] -= (1 << len[c]) - 1; if (diff[s + c] == 65535) diff[s + c] = -32768; } } for (s = col; s < col + 2; s++) { pred = 0x8000 + load_flags; if (col) pred = back[2][s - 2]; if (col && row > 1) switch (jh.psv) { case 11: pred += back[0][s] / 2 - back[0][s - 2] / 2; break; } f = (row & 1) * 3 ^ ((col + s) & 1); FORC(tiff_samples) { pred += diff[(s & 1) * tiff_samples + c]; upix = pred >> sh & 0xffff; if (raw_image && c == shot) RAW(row, s) = upix; if (image) { urow = row - top_margin + (c & 1); ucol = col - left_margin - ((c >> 1) & 1); ip = &image[urow * width + ucol][f]; if (urow < height && ucol < width) *ip = c < 4 ? upix : (*ip + upix) >> 1; } } back[2][s] = pred; } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(back[4]); ljpeg_end(&jh); throw; } #endif free(back[4]); ljpeg_end(&jh); if (image) mix_green = 1; } void CLASS leaf_hdr_load_raw() { ushort *pixel = 0; unsigned tile = 0, r, c, row, col; if (!filters || !raw_image) { pixel = (ushort *)calloc(raw_width, sizeof *pixel); merror(pixel, "leaf_hdr_load_raw()"); } #ifdef LIBRAW_LIBRARY_BUILD try { #endif FORC(tiff_samples) for (r = 0; r < raw_height; r++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (r % tile_length == 0) { fseek(ifp, data_offset + 4 * tile++, SEEK_SET); fseek(ifp, get4(), SEEK_SET); } if (filters && c != shot_select) continue; if (filters && raw_image) pixel = raw_image + r * raw_width; read_shorts(pixel, raw_width); if (!filters && image && (row = r - top_margin) < height) for (col = 0; col < width; col++) image[row * width + col][c] = pixel[col + left_margin]; } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { if (!filters) free(pixel); throw; } #endif if (!filters) { maximum = 0xffff; raw_color = 1; free(pixel); } } void CLASS unpacked_load_raw() { int row, col, bits = 0; while (1 << ++bits < maximum) ; read_shorts(raw_image, raw_width * raw_height); if (maximum < 0xffff || load_flags) for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < raw_width; col++) if ((RAW(row, col) >>= load_flags) >> bits && (unsigned)(row - top_margin) < height && (unsigned)(col - left_margin) < width) derror(); } } void CLASS unpacked_load_raw_reversed() { int row, col, bits = 0; while (1 << ++bits < maximum) ; for (row = raw_height - 1; row >= 0; row--) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif read_shorts(&raw_image[row * raw_width], raw_width); for (col = 0; col < raw_width; col++) if ((RAW(row, col) >>= load_flags) >> bits && (unsigned)(row - top_margin) < height && (unsigned)(col - left_margin) < width) derror(); } } void CLASS sinar_4shot_load_raw() { ushort *pixel; unsigned shot, row, col, r, c; if (raw_image) { shot = LIM(shot_select, 1, 4) - 1; fseek(ifp, data_offset + shot * 4, SEEK_SET); fseek(ifp, get4(), SEEK_SET); unpacked_load_raw(); return; } pixel = (ushort *)calloc(raw_width, sizeof *pixel); merror(pixel, "sinar_4shot_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (shot = 0; shot < 4; shot++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek(ifp, data_offset + shot * 4, SEEK_SET); fseek(ifp, get4(), SEEK_SET); for (row = 0; row < raw_height; row++) { read_shorts(pixel, raw_width); if ((r = row - top_margin - (shot >> 1 & 1)) >= height) continue; for (col = 0; col < raw_width; col++) { if ((c = col - left_margin - (shot & 1)) >= width) continue; image[r * width + c][(row & 1) * 3 ^ (~col & 1)] = pixel[col]; } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free(pixel); mix_green = 1; } void CLASS imacon_full_load_raw() { int row, col; if (!image) return; #ifdef LIBRAW_LIBRARY_BUILD unsigned short *buf = (unsigned short *)malloc(width * 3 * sizeof(unsigned short)); merror(buf, "imacon_full_load_raw"); #endif for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); read_shorts(buf, width * 3); unsigned short(*rowp)[4] = &image[row * width]; for (col = 0; col < width; col++) { rowp[col][0] = buf[col * 3]; rowp[col][1] = buf[col * 3 + 1]; rowp[col][2] = buf[col * 3 + 2]; rowp[col][3] = 0; } #else for (col = 0; col < width; col++) read_shorts(image[row * width + col], 3); #endif } #ifdef LIBRAW_LIBRARY_BUILD free(buf); #endif } void CLASS packed_load_raw() { int vbits = 0, bwide, rbits, bite, half, irow, row, col, val, i; UINT64 bitbuf = 0; bwide = raw_width * tiff_bps / 8; bwide += bwide & load_flags >> 7; rbits = bwide * 8 - raw_width * tiff_bps; if (load_flags & 1) bwide = bwide * 16 / 15; bite = 8 + (load_flags & 24); half = (raw_height + 1) >> 1; for (irow = 0; irow < raw_height; irow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif row = irow; if (load_flags & 2 && (row = irow % half * 2 + irow / half) == 1 && load_flags & 4) { if (vbits = 0, tiff_compress) fseek(ifp, data_offset - (-half * bwide & -2048), SEEK_SET); else { fseek(ifp, 0, SEEK_END); fseek(ifp, ftell(ifp) >> 3 << 2, SEEK_SET); } } for (col = 0; col < raw_width; col++) { for (vbits -= tiff_bps; vbits < 0; vbits += bite) { bitbuf <<= bite; for (i = 0; i < bite; i += 8) bitbuf |= (unsigned)(fgetc(ifp) << i); } val = bitbuf << (64 - tiff_bps - vbits) >> (64 - tiff_bps); RAW(row, col ^ (load_flags >> 6 & 1)) = val; if (load_flags & 1 && (col % 10) == 9 && fgetc(ifp) && row < height + top_margin && col < width + left_margin) derror(); } vbits -= rbits; } } #ifdef LIBRAW_LIBRARY_BUILD ushort raw_stride; void CLASS parse_broadcom() { /* This structure is at offset 0xb0 from the 'BRCM' ident. */ struct { uint8_t umode[32]; uint16_t uwidth; uint16_t uheight; uint16_t padding_right; uint16_t padding_down; uint32_t unknown_block[6]; uint16_t transform; uint16_t format; uint8_t bayer_order; uint8_t bayer_format; } header; header.bayer_order = 0; fseek(ifp, 0xb0 - 0x20, SEEK_CUR); fread(&header, 1, sizeof(header), ifp); raw_stride = ((((((header.uwidth + header.padding_right) * 5) + 3) >> 2) + 0x1f) & (~0x1f)); raw_width = width = header.uwidth; raw_height = height = header.uheight; filters = 0x16161616; /* default Bayer order is 2, BGGR */ switch (header.bayer_order) { case 0: /* RGGB */ filters = 0x94949494; break; case 1: /* GBRG */ filters = 0x49494949; break; case 3: /* GRBG */ filters = 0x61616161; break; } } void CLASS broadcom_load_raw() { uchar *data, *dp; int rev, row, col, c; rev = 3 * (order == 0x4949); data = (uchar *)malloc(raw_stride * 2); merror(data, "broadcom_load_raw()"); for (row = 0; row < raw_height; row++) { if (fread(data + raw_stride, 1, raw_stride, ifp) < raw_stride) derror(); FORC(raw_stride) data[c] = data[raw_stride + (c ^ rev)]; for (dp = data, col = 0; col < raw_width; dp += 5, col += 4) FORC4 RAW(row, col + c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3); } free(data); } #endif void CLASS nokia_load_raw() { uchar *data, *dp; int rev, dwide, row, col, c; double sum[] = {0, 0}; rev = 3 * (order == 0x4949); dwide = (raw_width * 5 + 1) / 4; data = (uchar *)malloc(dwide * 2); merror(data, "nokia_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread(data + dwide, 1, dwide, ifp) < dwide) derror(); FORC(dwide) data[c] = data[dwide + (c ^ rev)]; for (dp = data, col = 0; col < raw_width; dp += 5, col += 4) FORC4 RAW(row, col + c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(data); throw; } #endif free(data); maximum = 0x3ff; if (strncmp(make, "OmniVision", 10)) return; row = raw_height / 2; FORC(width - 1) { sum[c & 1] += SQR(RAW(row, c) - RAW(row + 1, c + 1)); sum[~c & 1] += SQR(RAW(row + 1, c) - RAW(row, c + 1)); } if (sum[1] > sum[0]) filters = 0x4b4b4b4b; } void CLASS android_tight_load_raw() { uchar *data, *dp; int bwide, row, col, c; bwide = -(-5 * raw_width >> 5) << 3; data = (uchar *)malloc(bwide); merror(data, "android_tight_load_raw()"); for (row = 0; row < raw_height; row++) { if (fread(data, 1, bwide, ifp) < bwide) derror(); for (dp = data, col = 0; col < raw_width; dp += 5, col += 4) FORC4 RAW(row, col + c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3); } free(data); } void CLASS android_loose_load_raw() { uchar *data, *dp; int bwide, row, col, c; UINT64 bitbuf = 0; bwide = (raw_width + 5) / 6 << 3; data = (uchar *)malloc(bwide); merror(data, "android_loose_load_raw()"); for (row = 0; row < raw_height; row++) { if (fread(data, 1, bwide, ifp) < bwide) derror(); for (dp = data, col = 0; col < raw_width; dp += 8, col += 6) { FORC(8) bitbuf = (bitbuf << 8) | dp[c ^ 7]; FORC(6) RAW(row, col + c) = (bitbuf >> c * 10) & 0x3ff; } } free(data); } void CLASS canon_rmf_load_raw() { int row, col, bits, orow, ocol, c; #ifdef LIBRAW_LIBRARY_BUILD int *words = (int *)malloc(sizeof(int) * (raw_width / 3 + 1)); merror(words, "canon_rmf_load_raw"); #endif for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); fread(words, sizeof(int), raw_width / 3, ifp); for (col = 0; col < raw_width - 2; col += 3) { bits = words[col / 3]; FORC3 { orow = row; if ((ocol = col + c - 4) < 0) { ocol += raw_width; if ((orow -= 2) < 0) orow += raw_height; } RAW(orow, ocol) = curve[bits >> (10 * c + 2) & 0x3ff]; } } #else for (col = 0; col < raw_width - 2; col += 3) { bits = get4(); FORC3 { orow = row; if ((ocol = col + c - 4) < 0) { ocol += raw_width; if ((orow -= 2) < 0) orow += raw_height; } RAW(orow, ocol) = curve[bits >> (10 * c + 2) & 0x3ff]; } } #endif } #ifdef LIBRAW_LIBRARY_BUILD free(words); #endif maximum = curve[0x3ff]; } unsigned CLASS pana_bits(int nbits) { #ifndef LIBRAW_NOTHREADS #define buf tls->pana_bits.buf #define vbits tls->pana_bits.vbits #else static uchar buf[0x4000]; static int vbits; #endif int byte; if (!nbits) return vbits = 0; if (!vbits) { fread(buf + load_flags, 1, 0x4000 - load_flags, ifp); fread(buf, 1, load_flags, ifp); } vbits = (vbits - nbits) & 0x1ffff; byte = vbits >> 3 ^ 0x3ff0; return (buf[byte] | buf[byte + 1] << 8) >> (vbits & 7) & ~((~0u) << nbits); #ifndef LIBRAW_NOTHREADS #undef buf #undef vbits #endif } void CLASS panasonic_load_raw() { int row, col, i, j, sh = 0, pred[2], nonz[2]; pana_bits(0); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < raw_width; col++) { if ((i = col % 14) == 0) pred[0] = pred[1] = nonz[0] = nonz[1] = 0; if (i % 3 == 2) sh = 4 >> (3 - pana_bits(2)); if (nonz[i & 1]) { if ((j = pana_bits(8))) { if ((pred[i & 1] -= 0x80 << sh) < 0 || sh == 4) pred[i & 1] &= ~((~0u) << sh); pred[i & 1] += j << sh; } } else if ((nonz[i & 1] = pana_bits(8)) || i > 11) pred[i & 1] = nonz[i & 1] << 4 | pana_bits(4); if ((RAW(row, col) = pred[col & 1]) > 4098 && col < width && row < height) derror(); } } } void CLASS olympus_load_raw() { ushort huff[4096]; int row, col, nbits, sign, low, high, i, c, w, n, nw; int acarry[2][3], *carry, pred, diff; huff[n = 0] = 0xc0c; for (i = 12; i--;) FORC(2048 >> i) huff[++n] = (i + 1) << 8 | i; fseek(ifp, 7, SEEK_CUR); getbits(-1); for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif memset(acarry, 0, sizeof acarry); for (col = 0; col < raw_width; col++) { carry = acarry[col & 1]; i = 2 * (carry[2] < 3); for (nbits = 2 + i; (ushort)carry[0] >> (nbits + i); nbits++) ; low = (sign = getbits(3)) & 3; sign = sign << 29 >> 31; if ((high = getbithuff(12, huff)) == 12) high = getbits(16 - nbits) >> 1; carry[0] = (high << nbits) | getbits(nbits); diff = (carry[0] ^ sign) + carry[1]; carry[1] = (diff * 3 + carry[1]) >> 5; carry[2] = carry[0] > 16 ? 0 : carry[2] + 1; if (col >= width) continue; if (row < 2 && col < 2) pred = 0; else if (row < 2) pred = RAW(row, col - 2); else if (col < 2) pred = RAW(row - 2, col); else { w = RAW(row, col - 2); n = RAW(row - 2, col); nw = RAW(row - 2, col - 2); if ((w < nw && nw < n) || (n < nw && nw < w)) { if (ABS(w - nw) > 32 || ABS(n - nw) > 32) pred = w + n - nw; else pred = (w + n) >> 1; } else pred = ABS(w - nw) > ABS(n - nw) ? w : n; } if ((RAW(row, col) = pred + ((diff << 2) | low)) >> 12) derror(); } } } void CLASS minolta_rd175_load_raw() { uchar pixel[768]; unsigned irow, box, row, col; for (irow = 0; irow < 1481; irow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread(pixel, 1, 768, ifp) < 768) derror(); box = irow / 82; row = irow % 82 * 12 + ((box < 12) ? box | 1 : (box - 12) * 2); switch (irow) { case 1477: case 1479: continue; case 1476: row = 984; break; case 1480: row = 985; break; case 1478: row = 985; box = 1; } if ((box < 12) && (box & 1)) { for (col = 0; col < 1533; col++, row ^= 1) if (col != 1) RAW(row, col) = (col + 1) & 2 ? pixel[col / 2 - 1] + pixel[col / 2 + 1] : pixel[col / 2] << 1; RAW(row, 1) = pixel[1] << 1; RAW(row, 1533) = pixel[765] << 1; } else for (col = row & 1; col < 1534; col += 2) RAW(row, col) = pixel[col / 2] << 1; } maximum = 0xff << 1; } void CLASS quicktake_100_load_raw() { uchar pixel[484][644]; static const short gstep[16] = {-89, -60, -44, -32, -22, -15, -8, -2, 2, 8, 15, 22, 32, 44, 60, 89}; static const short rstep[6][4] = {{-3, -1, 1, 3}, {-5, -1, 1, 5}, {-8, -2, 2, 8}, {-13, -3, 3, 13}, {-19, -4, 4, 19}, {-28, -6, 6, 28}}; static const short t_curve[256] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 86, 88, 90, 92, 94, 97, 99, 101, 103, 105, 107, 110, 112, 114, 116, 118, 120, 123, 125, 127, 129, 131, 134, 136, 138, 140, 142, 144, 147, 149, 151, 153, 155, 158, 160, 162, 164, 166, 168, 171, 173, 175, 177, 179, 181, 184, 186, 188, 190, 192, 195, 197, 199, 201, 203, 205, 208, 210, 212, 214, 216, 218, 221, 223, 226, 230, 235, 239, 244, 248, 252, 257, 261, 265, 270, 274, 278, 283, 287, 291, 296, 300, 305, 309, 313, 318, 322, 326, 331, 335, 339, 344, 348, 352, 357, 361, 365, 370, 374, 379, 383, 387, 392, 396, 400, 405, 409, 413, 418, 422, 426, 431, 435, 440, 444, 448, 453, 457, 461, 466, 470, 474, 479, 483, 487, 492, 496, 500, 508, 519, 531, 542, 553, 564, 575, 587, 598, 609, 620, 631, 643, 654, 665, 676, 687, 698, 710, 721, 732, 743, 754, 766, 777, 788, 799, 810, 822, 833, 844, 855, 866, 878, 889, 900, 911, 922, 933, 945, 956, 967, 978, 989, 1001, 1012, 1023}; int rb, row, col, sharp, val = 0; getbits(-1); memset(pixel, 0x80, sizeof pixel); for (row = 2; row < height + 2; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 2 + (row & 1); col < width + 2; col += 2) { val = ((pixel[row - 1][col - 1] + 2 * pixel[row - 1][col + 1] + pixel[row][col - 2]) >> 2) + gstep[getbits(4)]; pixel[row][col] = val = LIM(val, 0, 255); if (col < 4) pixel[row][col - 2] = pixel[row + 1][~row & 1] = val; if (row == 2) pixel[row - 1][col + 1] = pixel[row - 1][col + 3] = val; } pixel[row][col] = val; } for (rb = 0; rb < 2; rb++) for (row = 2 + rb; row < height + 2; row += 2) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 3 - (row & 1); col < width + 2; col += 2) { if (row < 4 || col < 4) sharp = 2; else { val = ABS(pixel[row - 2][col] - pixel[row][col - 2]) + ABS(pixel[row - 2][col] - pixel[row - 2][col - 2]) + ABS(pixel[row][col - 2] - pixel[row - 2][col - 2]); sharp = val < 4 ? 0 : val < 8 ? 1 : val < 16 ? 2 : val < 32 ? 3 : val < 48 ? 4 : 5; } val = ((pixel[row - 2][col] + pixel[row][col - 2]) >> 1) + rstep[sharp][getbits(2)]; pixel[row][col] = val = LIM(val, 0, 255); if (row < 4) pixel[row - 2][col + 2] = val; if (col < 4) pixel[row + 2][col - 2] = val; } } for (row = 2; row < height + 2; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 3 - (row & 1); col < width + 2; col += 2) { val = ((pixel[row][col - 1] + (pixel[row][col] << 2) + pixel[row][col + 1]) >> 1) - 0x100; pixel[row][col] = LIM(val, 0, 255); } } for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < width; col++) RAW(row, col) = t_curve[pixel[row + 2][col + 2]]; } maximum = 0x3ff; } #define radc_token(tree) ((signed char)getbithuff(8, huff[tree])) #define FORYX \ for (y = 1; y < 3; y++) \ for (x = col + 1; x >= col; x--) #define PREDICTOR \ (c ? (buf[c][y - 1][x] + buf[c][y][x + 1]) / 2 : (buf[c][y - 1][x + 1] + 2 * buf[c][y - 1][x] + buf[c][y][x + 1]) / 4) #ifdef __GNUC__ #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) #pragma GCC optimize("no-aggressive-loop-optimizations") #endif #endif void CLASS kodak_radc_load_raw() { static const signed char src[] = { 1, 1, 2, 3, 3, 4, 4, 2, 5, 7, 6, 5, 7, 6, 7, 8, 1, 0, 2, 1, 3, 3, 4, 4, 5, 2, 6, 7, 7, 6, 8, 5, 8, 8, 2, 1, 2, 3, 3, 0, 3, 2, 3, 4, 4, 6, 5, 5, 6, 7, 6, 8, 2, 0, 2, 1, 2, 3, 3, 2, 4, 4, 5, 6, 6, 7, 7, 5, 7, 8, 2, 1, 2, 4, 3, 0, 3, 2, 3, 3, 4, 7, 5, 5, 6, 6, 6, 8, 2, 3, 3, 1, 3, 2, 3, 4, 3, 5, 3, 6, 4, 7, 5, 0, 5, 8, 2, 3, 2, 6, 3, 0, 3, 1, 4, 4, 4, 5, 4, 7, 5, 2, 5, 8, 2, 4, 2, 7, 3, 3, 3, 6, 4, 1, 4, 2, 4, 5, 5, 0, 5, 8, 2, 6, 3, 1, 3, 3, 3, 5, 3, 7, 3, 8, 4, 0, 5, 2, 5, 4, 2, 0, 2, 1, 3, 2, 3, 3, 4, 4, 4, 5, 5, 6, 5, 7, 4, 8, 1, 0, 2, 2, 2, -2, 1, -3, 1, 3, 2, -17, 2, -5, 2, 5, 2, 17, 2, -7, 2, 2, 2, 9, 2, 18, 2, -18, 2, -9, 2, -2, 2, 7, 2, -28, 2, 28, 3, -49, 3, -9, 3, 9, 4, 49, 5, -79, 5, 79, 2, -1, 2, 13, 2, 26, 3, 39, 4, -16, 5, 55, 6, -37, 6, 76, 2, -26, 2, -13, 2, 1, 3, -39, 4, 16, 5, -55, 6, -76, 6, 37}; ushort huff[19][256]; int row, col, tree, nreps, rep, step, i, c, s, r, x, y, val; short last[3] = {16, 16, 16}, mul[3], buf[3][3][386]; static const ushort pt[] = {0, 0, 1280, 1344, 2320, 3616, 3328, 8000, 4095, 16383, 65535, 16383}; for (i = 2; i < 12; i += 2) for (c = pt[i - 2]; c <= pt[i]; c++) curve[c] = (float)(c - pt[i - 2]) / (pt[i] - pt[i - 2]) * (pt[i + 1] - pt[i - 1]) + pt[i - 1] + 0.5; for (s = i = 0; i < sizeof src; i += 2) FORC(256 >> src[i]) ((ushort *)huff)[s++] = src[i] << 8 | (uchar)src[i + 1]; s = kodak_cbpp == 243 ? 2 : 3; FORC(256) huff[18][c] = (8 - s) << 8 | c >> s << s | 1 << (s - 1); getbits(-1); for (i = 0; i < sizeof(buf) / sizeof(short); i++) ((short *)buf)[i] = 2048; for (row = 0; row < height; row += 4) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif FORC3 mul[c] = getbits(6); FORC3 { val = ((0x1000000 / last[c] + 0x7ff) >> 12) * mul[c]; s = val > 65564 ? 10 : 12; x = ~((~0u) << (s - 1)); val <<= 12 - s; for (i = 0; i < sizeof(buf[0]) / sizeof(short); i++) ((short *)buf[c])[i] = (((short *)buf[c])[i] * val + x) >> s; last[c] = mul[c]; for (r = 0; r <= !c; r++) { buf[c][1][width / 2] = buf[c][2][width / 2] = mul[c] << 7; for (tree = 1, col = width / 2; col > 0;) { if ((tree = radc_token(tree))) { col -= 2; if (tree == 8) FORYX buf[c][y][x] = (uchar)radc_token(18) * mul[c]; else FORYX buf[c][y][x] = radc_token(tree + 10) * 16 + PREDICTOR; } else do { nreps = (col > 2) ? radc_token(9) + 1 : 1; for (rep = 0; rep < 8 && rep < nreps && col > 0; rep++) { col -= 2; FORYX buf[c][y][x] = PREDICTOR; if (rep & 1) { step = radc_token(10) << 4; FORYX buf[c][y][x] += step; } } } while (nreps == 9); } for (y = 0; y < 2; y++) for (x = 0; x < width / 2; x++) { val = (buf[c][y + 1][x] << 4) / mul[c]; if (val < 0) val = 0; if (c) RAW(row + y * 2 + c - 1, x * 2 + 2 - c) = val; else RAW(row + r * 2 + y, x * 2 + y) = val; } memcpy(buf[c][0] + !c, buf[c][2], sizeof buf[c][0] - 2 * !c); } } for (y = row; y < row + 4; y++) for (x = 0; x < width; x++) if ((x + y) & 1) { r = x ? x - 1 : x + 1; s = x + 1 < width ? x + 1 : x - 1; val = (RAW(y, x) - 2048) * 2 + (RAW(y, r) + RAW(y, s)) / 2; if (val < 0) val = 0; RAW(y, x) = val; } } for (i = 0; i < height * width; i++) raw_image[i] = curve[raw_image[i]]; maximum = 0x3fff; } #undef FORYX #undef PREDICTOR #ifdef NO_JPEG void CLASS kodak_jpeg_load_raw() {} void CLASS lossy_dng_load_raw() {} #else #ifndef LIBRAW_LIBRARY_BUILD METHODDEF(boolean) fill_input_buffer(j_decompress_ptr cinfo) { static uchar jpeg_buffer[4096]; size_t nbytes; nbytes = fread(jpeg_buffer, 1, 4096, ifp); swab(jpeg_buffer, jpeg_buffer, nbytes); cinfo->src->next_input_byte = jpeg_buffer; cinfo->src->bytes_in_buffer = nbytes; return TRUE; } void CLASS kodak_jpeg_load_raw() { struct jpeg_decompress_struct cinfo; struct jpeg_error_mgr jerr; JSAMPARRAY buf; JSAMPLE(*pixel)[3]; int row, col; cinfo.err = jpeg_std_error(&jerr); jpeg_create_decompress(&cinfo); jpeg_stdio_src(&cinfo, ifp); cinfo.src->fill_input_buffer = fill_input_buffer; jpeg_read_header(&cinfo, TRUE); jpeg_start_decompress(&cinfo); if ((cinfo.output_width != width) || (cinfo.output_height * 2 != height) || (cinfo.output_components != 3)) { fprintf(stderr, _("%s: incorrect JPEG dimensions\n"), ifname); jpeg_destroy_decompress(&cinfo); longjmp(failure, 3); } buf = (*cinfo.mem->alloc_sarray)((j_common_ptr)&cinfo, JPOOL_IMAGE, width * 3, 1); while (cinfo.output_scanline < cinfo.output_height) { row = cinfo.output_scanline * 2; jpeg_read_scanlines(&cinfo, buf, 1); pixel = (JSAMPLE(*)[3])buf[0]; for (col = 0; col < width; col += 2) { RAW(row + 0, col + 0) = pixel[col + 0][1] << 1; RAW(row + 1, col + 1) = pixel[col + 1][1] << 1; RAW(row + 0, col + 1) = pixel[col][0] + pixel[col + 1][0]; RAW(row + 1, col + 0) = pixel[col][2] + pixel[col + 1][2]; } } jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); maximum = 0xff << 1; } #else struct jpegErrorManager { struct jpeg_error_mgr pub; }; static void jpegErrorExit(j_common_ptr cinfo) { jpegErrorManager *myerr = (jpegErrorManager *)cinfo->err; throw LIBRAW_EXCEPTION_DECODE_JPEG; } // LibRaw's Kodak_jpeg_load_raw void CLASS kodak_jpeg_load_raw() { if (data_size < 1) throw LIBRAW_EXCEPTION_DECODE_JPEG; int row, col; jpegErrorManager jerr; struct jpeg_decompress_struct cinfo; cinfo.err = jpeg_std_error(&jerr.pub); jerr.pub.error_exit = jpegErrorExit; unsigned char *jpg_buf = (unsigned char *)malloc(data_size); merror(jpg_buf, "kodak_jpeg_load_raw"); unsigned char *pixel_buf = (unsigned char *)malloc(width * 3); jpeg_create_decompress(&cinfo); merror(pixel_buf, "kodak_jpeg_load_raw"); fread(jpg_buf, data_size, 1, ifp); swab((char *)jpg_buf, (char *)jpg_buf, data_size); try { jpeg_mem_src(&cinfo, jpg_buf, data_size); int rc = jpeg_read_header(&cinfo, TRUE); if (rc != 1) throw LIBRAW_EXCEPTION_DECODE_JPEG; jpeg_start_decompress(&cinfo); if ((cinfo.output_width != width) || (cinfo.output_height * 2 != height) || (cinfo.output_components != 3)) { throw LIBRAW_EXCEPTION_DECODE_JPEG; } unsigned char *buf[1]; buf[0] = pixel_buf; while (cinfo.output_scanline < cinfo.output_height) { checkCancel(); row = cinfo.output_scanline * 2; jpeg_read_scanlines(&cinfo, buf, 1); unsigned char(*pixel)[3] = (unsigned char(*)[3])buf[0]; for (col = 0; col < width; col += 2) { RAW(row + 0, col + 0) = pixel[col + 0][1] << 1; RAW(row + 1, col + 1) = pixel[col + 1][1] << 1; RAW(row + 0, col + 1) = pixel[col][0] + pixel[col + 1][0]; RAW(row + 1, col + 0) = pixel[col][2] + pixel[col + 1][2]; } } } catch (...) { jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); free(jpg_buf); free(pixel_buf); throw; } jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); free(jpg_buf); free(pixel_buf); maximum = 0xff << 1; } #endif #ifndef LIBRAW_LIBRARY_BUILD void CLASS gamma_curve(double pwr, double ts, int mode, int imax); #endif void CLASS lossy_dng_load_raw() { struct jpeg_decompress_struct cinfo; struct jpeg_error_mgr jerr; JSAMPARRAY buf; JSAMPLE(*pixel)[3]; unsigned sorder = order, ntags, opcode, deg, i, j, c; unsigned save = data_offset - 4, trow = 0, tcol = 0, row, col; ushort cur[3][256]; double coeff[9], tot; if (meta_offset) { fseek(ifp, meta_offset, SEEK_SET); order = 0x4d4d; ntags = get4(); while (ntags--) { opcode = get4(); get4(); get4(); if (opcode != 8) { fseek(ifp, get4(), SEEK_CUR); continue; } fseek(ifp, 20, SEEK_CUR); if ((c = get4()) > 2) break; fseek(ifp, 12, SEEK_CUR); if ((deg = get4()) > 8) break; for (i = 0; i <= deg && i < 9; i++) coeff[i] = getreal(12); for (i = 0; i < 256; i++) { for (tot = j = 0; j <= deg; j++) tot += coeff[j] * pow(i / 255.0, (int)j); cur[c][i] = tot * 0xffff; } } order = sorder; } else { gamma_curve(1 / 2.4, 12.92, 1, 255); FORC3 memcpy(cur[c], curve, sizeof cur[0]); } cinfo.err = jpeg_std_error(&jerr); jpeg_create_decompress(&cinfo); while (trow < raw_height) { fseek(ifp, save += 4, SEEK_SET); if (tile_length < INT_MAX) fseek(ifp, get4(), SEEK_SET); #ifdef LIBRAW_LIBRARY_BUILD if (libraw_internal_data.internal_data.input->jpeg_src(&cinfo) == -1) { jpeg_destroy_decompress(&cinfo); throw LIBRAW_EXCEPTION_DECODE_JPEG; } #else jpeg_stdio_src(&cinfo, ifp); #endif jpeg_read_header(&cinfo, TRUE); jpeg_start_decompress(&cinfo); buf = (*cinfo.mem->alloc_sarray)((j_common_ptr)&cinfo, JPOOL_IMAGE, cinfo.output_width * 3, 1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif while (cinfo.output_scanline < cinfo.output_height && (row = trow + cinfo.output_scanline) < height) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif jpeg_read_scanlines(&cinfo, buf, 1); pixel = (JSAMPLE(*)[3])buf[0]; for (col = 0; col < cinfo.output_width && tcol + col < width; col++) { FORC3 image[row * width + tcol + col][c] = cur[c][pixel[col][c]]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { jpeg_destroy_decompress(&cinfo); throw; } #endif jpeg_abort_decompress(&cinfo); if ((tcol += tile_width) >= raw_width) trow += tile_length + (tcol = 0); } jpeg_destroy_decompress(&cinfo); maximum = 0xffff; } #endif void CLASS kodak_dc120_load_raw() { static const int mul[4] = {162, 192, 187, 92}; static const int add[4] = {0, 636, 424, 212}; uchar pixel[848]; int row, shift, col; for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread(pixel, 1, 848, ifp) < 848) derror(); shift = row * mul[row & 3] + add[row & 3]; for (col = 0; col < width; col++) RAW(row, col) = (ushort)pixel[(col + shift) % 848]; } maximum = 0xff; } void CLASS eight_bit_load_raw() { uchar *pixel; unsigned row, col; pixel = (uchar *)calloc(raw_width, sizeof *pixel); merror(pixel, "eight_bit_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread(pixel, 1, raw_width, ifp) < raw_width) derror(); for (col = 0; col < raw_width; col++) RAW(row, col) = curve[pixel[col]]; } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free(pixel); maximum = curve[0xff]; } void CLASS kodak_c330_load_raw() { uchar *pixel; int row, col, y, cb, cr, rgb[3], c; pixel = (uchar *)calloc(raw_width, 2 * sizeof *pixel); merror(pixel, "kodak_c330_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread(pixel, raw_width, 2, ifp) < 2) derror(); if (load_flags && (row & 31) == 31) fseek(ifp, raw_width * 32, SEEK_CUR); for (col = 0; col < width; col++) { y = pixel[col * 2]; cb = pixel[(col * 2 & -4) | 1] - 128; cr = pixel[(col * 2 & -4) | 3] - 128; rgb[1] = y - ((cb + cr + 2) >> 2); rgb[2] = rgb[1] + cb; rgb[0] = rgb[1] + cr; FORC3 image[row * width + col][c] = curve[LIM(rgb[c], 0, 255)]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free(pixel); maximum = curve[0xff]; } void CLASS kodak_c603_load_raw() { uchar *pixel; int row, col, y, cb, cr, rgb[3], c; pixel = (uchar *)calloc(raw_width, 3 * sizeof *pixel); merror(pixel, "kodak_c603_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (~row & 1) if (fread(pixel, raw_width, 3, ifp) < 3) derror(); for (col = 0; col < width; col++) { y = pixel[width * 2 * (row & 1) + col]; cb = pixel[width + (col & -2)] - 128; cr = pixel[width + (col & -2) + 1] - 128; rgb[1] = y - ((cb + cr + 2) >> 2); rgb[2] = rgb[1] + cb; rgb[0] = rgb[1] + cr; FORC3 image[row * width + col][c] = curve[LIM(rgb[c], 0, 255)]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free(pixel); maximum = curve[0xff]; } void CLASS kodak_262_load_raw() { static const uchar kodak_tree[2][26] = { {0, 1, 5, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {0, 3, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}}; ushort *huff[2]; uchar *pixel; int *strip, ns, c, row, col, chess, pi = 0, pi1, pi2, pred, val; FORC(2) huff[c] = make_decoder(kodak_tree[c]); ns = (raw_height + 63) >> 5; pixel = (uchar *)malloc(raw_width * 32 + ns * 4); merror(pixel, "kodak_262_load_raw()"); strip = (int *)(pixel + raw_width * 32); order = 0x4d4d; FORC(ns) strip[c] = get4(); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if ((row & 31) == 0) { fseek(ifp, strip[row >> 5], SEEK_SET); getbits(-1); pi = 0; } for (col = 0; col < raw_width; col++) { chess = (row + col) & 1; pi1 = chess ? pi - 2 : pi - raw_width - 1; pi2 = chess ? pi - 2 * raw_width : pi - raw_width + 1; if (col <= chess) pi1 = -1; if (pi1 < 0) pi1 = pi2; if (pi2 < 0) pi2 = pi1; if (pi1 < 0 && col > 1) pi1 = pi2 = pi - 2; pred = (pi1 < 0) ? 0 : (pixel[pi1] + pixel[pi2]) >> 1; pixel[pi] = val = pred + ljpeg_diff(huff[chess]); if (val >> 8) derror(); val = curve[pixel[pi++]]; RAW(row, col) = val; } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free(pixel); FORC(2) free(huff[c]); } int CLASS kodak_65000_decode(short *out, int bsize) { uchar c, blen[768]; ushort raw[6]; INT64 bitbuf = 0; int save, bits = 0, i, j, len, diff; save = ftell(ifp); bsize = (bsize + 3) & -4; for (i = 0; i < bsize; i += 2) { c = fgetc(ifp); if ((blen[i] = c & 15) > 12 || (blen[i + 1] = c >> 4) > 12) { fseek(ifp, save, SEEK_SET); for (i = 0; i < bsize; i += 8) { read_shorts(raw, 6); out[i] = raw[0] >> 12 << 8 | raw[2] >> 12 << 4 | raw[4] >> 12; out[i + 1] = raw[1] >> 12 << 8 | raw[3] >> 12 << 4 | raw[5] >> 12; for (j = 0; j < 6; j++) out[i + 2 + j] = raw[j] & 0xfff; } return 1; } } if ((bsize & 7) == 4) { bitbuf = fgetc(ifp) << 8; bitbuf += fgetc(ifp); bits = 16; } for (i = 0; i < bsize; i++) { len = blen[i]; if (bits < len) { for (j = 0; j < 32; j += 8) bitbuf += (INT64)fgetc(ifp) << (bits + (j ^ 8)); bits += 32; } diff = bitbuf & (0xffff >> (16 - len)); bitbuf >>= len; bits -= len; if ((diff & (1 << (len - 1))) == 0) diff -= (1 << len) - 1; out[i] = diff; } return 0; } void CLASS kodak_65000_load_raw() { short buf[256]; int row, col, len, pred[2], ret, i; for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < width; col += 256) { pred[0] = pred[1] = 0; len = MIN(256, width - col); ret = kodak_65000_decode(buf, len); for (i = 0; i < len; i++) if ((RAW(row, col + i) = curve[ret ? buf[i] : (pred[i & 1] += buf[i])]) >> 12) derror(); } } } void CLASS kodak_ycbcr_load_raw() { short buf[384], *bp; int row, col, len, c, i, j, k, y[2][2], cb, cr, rgb[3]; ushort *ip; if (!image) return; unsigned int bits = (load_flags && load_flags > 9 && load_flags < 17) ? load_flags : 10; for (row = 0; row < height; row += 2) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < width; col += 128) { len = MIN(128, width - col); kodak_65000_decode(buf, len * 3); y[0][1] = y[1][1] = cb = cr = 0; for (bp = buf, i = 0; i < len; i += 2, bp += 2) { cb += bp[4]; cr += bp[5]; rgb[1] = -((cb + cr + 2) >> 2); rgb[2] = rgb[1] + cb; rgb[0] = rgb[1] + cr; for (j = 0; j < 2; j++) for (k = 0; k < 2; k++) { if ((y[j][k] = y[j][k ^ 1] + *bp++) >> bits) derror(); ip = image[(row + j) * width + col + i + k]; FORC3 ip[c] = curve[LIM(y[j][k] + rgb[c], 0, 0xfff)]; } } } } } void CLASS kodak_rgb_load_raw() { short buf[768], *bp; int row, col, len, c, i, rgb[3], ret; ushort *ip = image[0]; for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < width; col += 256) { len = MIN(256, width - col); ret = kodak_65000_decode(buf, len * 3); memset(rgb, 0, sizeof rgb); for (bp = buf, i = 0; i < len; i++, ip += 4) #ifdef LIBRAW_LIBRARY_BUILD if (load_flags == 12) { FORC3 ip[c] = ret ? (*bp++) : (rgb[c] += *bp++); } else #endif FORC3 if ((ip[c] = ret ? (*bp++) : (rgb[c] += *bp++)) >> 12) derror(); } } } void CLASS kodak_thumb_load_raw() { int row, col; colors = thumb_misc >> 5; for (row = 0; row < height; row++) for (col = 0; col < width; col++) read_shorts(image[row * width + col], colors); maximum = (1 << (thumb_misc & 31)) - 1; } void CLASS sony_decrypt(unsigned *data, int len, int start, int key) { #ifndef LIBRAW_NOTHREADS #define pad tls->sony_decrypt.pad #define p tls->sony_decrypt.p #else static unsigned pad[128], p; #endif if (start) { for (p = 0; p < 4; p++) pad[p] = key = key * 48828125 + 1; pad[3] = pad[3] << 1 | (pad[0] ^ pad[2]) >> 31; for (p = 4; p < 127; p++) pad[p] = (pad[p - 4] ^ pad[p - 2]) << 1 | (pad[p - 3] ^ pad[p - 1]) >> 31; for (p = 0; p < 127; p++) pad[p] = htonl(pad[p]); } while (len--) { *data++ ^= pad[p & 127] = pad[(p + 1) & 127] ^ pad[(p + 65) & 127]; p++; } #ifndef LIBRAW_NOTHREADS #undef pad #undef p #endif } void CLASS sony_load_raw() { uchar head[40]; ushort *pixel; unsigned i, key, row, col; fseek(ifp, 200896, SEEK_SET); fseek(ifp, (unsigned)fgetc(ifp) * 4 - 1, SEEK_CUR); order = 0x4d4d; key = get4(); fseek(ifp, 164600, SEEK_SET); fread(head, 1, 40, ifp); sony_decrypt((unsigned *)head, 10, 1, key); for (i = 26; i-- > 22;) key = key << 8 | head[i]; fseek(ifp, data_offset, SEEK_SET); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif pixel = raw_image + row * raw_width; if (fread(pixel, 2, raw_width, ifp) < raw_width) derror(); sony_decrypt((unsigned *)pixel, raw_width / 2, !row, key); for (col = 0; col < raw_width; col++) if ((pixel[col] = ntohs(pixel[col])) >> 14) derror(); } maximum = 0x3ff0; } void CLASS sony_arw_load_raw() { ushort huff[32770]; static const ushort tab[18] = {0xf11, 0xf10, 0xe0f, 0xd0e, 0xc0d, 0xb0c, 0xa0b, 0x90a, 0x809, 0x708, 0x607, 0x506, 0x405, 0x304, 0x303, 0x300, 0x202, 0x201}; int i, c, n, col, row, sum = 0; huff[0] = 15; for (n = i = 0; i < 18; i++) FORC(32768 >> (tab[i] >> 8)) huff[++n] = tab[i]; getbits(-1); for (col = raw_width; col--;) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (row = 0; row < raw_height + 1; row += 2) { if (row == raw_height) row = 1; if ((sum += ljpeg_diff(huff)) >> 12) derror(); if (row < height) RAW(row, col) = sum; } } } void CLASS sony_arw2_load_raw() { uchar *data, *dp; ushort pix[16]; int row, col, val, max, min, imax, imin, sh, bit, i; data = (uchar *)malloc(raw_width + 1); merror(data, "sony_arw2_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fread(data, 1, raw_width, ifp); for (dp = data, col = 0; col < raw_width - 30; dp += 16) { max = 0x7ff & (val = sget4(dp)); min = 0x7ff & val >> 11; imax = 0x0f & val >> 22; imin = 0x0f & val >> 26; for (sh = 0; sh < 4 && 0x80 << sh <= max - min; sh++) ; #ifdef LIBRAW_LIBRARY_BUILD /* flag checks if outside of loop */ if (!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_ALLFLAGS) // no flag set || (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE)) { for (bit = 30, i = 0; i < 16; i++) if (i == imax) pix[i] = max; else if (i == imin) pix[i] = min; else { pix[i] = ((sget2(dp + (bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min; if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } } else if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_BASEONLY) { for (bit = 30, i = 0; i < 16; i++) if (i == imax) pix[i] = max; else if (i == imin) pix[i] = min; else pix[i] = 0; } else if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTAONLY) { for (bit = 30, i = 0; i < 16; i++) if (i == imax) pix[i] = 0; else if (i == imin) pix[i] = 0; else { pix[i] = ((sget2(dp + (bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min; if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } } else if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTAZEROBASE) { for (bit = 30, i = 0; i < 16; i++) if (i == imax) pix[i] = 0; else if (i == imin) pix[i] = 0; else { pix[i] = ((sget2(dp + (bit >> 3)) >> (bit & 7) & 0x7f) << sh); if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } } #else /* unaltered dcraw processing */ for (bit = 30, i = 0; i < 16; i++) if (i == imax) pix[i] = max; else if (i == imin) pix[i] = min; else { pix[i] = ((sget2(dp + (bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min; if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } #endif #ifdef LIBRAW_LIBRARY_BUILD if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE) { for (i = 0; i < 16; i++, col += 2) { unsigned slope = pix[i] < 1001 ? 2 : curve[pix[i] << 1] - curve[(pix[i] << 1) - 2]; unsigned step = 1 << sh; RAW(row, col) = curve[pix[i] << 1] > black + imgdata.params.sony_arw2_posterization_thr ? LIM(((slope * step * 1000) / (curve[pix[i] << 1] - black)), 0, 10000) : 0; } } else { for (i = 0; i < 16; i++, col += 2) RAW(row, col) = curve[pix[i] << 1]; } #else for (i = 0; i < 16; i++, col += 2) RAW(row, col) = curve[pix[i] << 1] >> 2; #endif col -= col & 1 ? 1 : 31; } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(data); throw; } if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE) maximum = 10000; #endif free(data); } void CLASS samsung_load_raw() { int row, col, c, i, dir, op[4], len[4]; order = 0x4949; for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek(ifp, strip_offset + row * 4, SEEK_SET); fseek(ifp, data_offset + get4(), SEEK_SET); ph1_bits(-1); FORC4 len[c] = row < 2 ? 7 : 4; for (col = 0; col < raw_width; col += 16) { dir = ph1_bits(1); FORC4 op[c] = ph1_bits(2); FORC4 switch (op[c]) { case 3: len[c] = ph1_bits(4); break; case 2: len[c]--; break; case 1: len[c]++; } for (c = 0; c < 16; c += 2) { i = len[((c & 1) << 1) | (c >> 3)]; RAW(row, col + c) = ((signed)ph1_bits(i) << (32 - i) >> (32 - i)) + (dir ? RAW(row + (~c | -2), col + c) : col ? RAW(row, col + (c | -2)) : 128); if (c == 14) c = -1; } } } for (row = 0; row < raw_height - 1; row += 2) for (col = 0; col < raw_width - 1; col += 2) SWAP(RAW(row, col + 1), RAW(row + 1, col)); } void CLASS samsung2_load_raw() { static const ushort tab[14] = {0x304, 0x307, 0x206, 0x205, 0x403, 0x600, 0x709, 0x80a, 0x90b, 0xa0c, 0xa0d, 0x501, 0x408, 0x402}; ushort huff[1026], vpred[2][2] = {{0, 0}, {0, 0}}, hpred[2]; int i, c, n, row, col, diff; huff[0] = 10; for (n = i = 0; i < 14; i++) FORC(1024 >> (tab[i] >> 8)) huff[++n] = tab[i]; getbits(-1); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < raw_width; col++) { diff = ljpeg_diff(huff); if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; RAW(row, col) = hpred[col & 1]; if (hpred[col & 1] >> tiff_bps) derror(); } } } void CLASS samsung3_load_raw() { int opt, init, mag, pmode, row, tab, col, pred, diff, i, c; ushort lent[3][2], len[4], *prow[2]; order = 0x4949; fseek(ifp, 9, SEEK_CUR); opt = fgetc(ifp); init = (get2(), get2()); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek(ifp, (data_offset - ftell(ifp)) & 15, SEEK_CUR); ph1_bits(-1); mag = 0; pmode = 7; FORC(6)((ushort *)lent)[c] = row < 2 ? 7 : 4; prow[row & 1] = &RAW(row - 1, 1 - ((row & 1) << 1)); // green prow[~row & 1] = &RAW(row - 2, 0); // red and blue for (tab = 0; tab + 15 < raw_width; tab += 16) { if (~opt & 4 && !(tab & 63)) { i = ph1_bits(2); mag = i < 3 ? mag - '2' + "204"[i] : ph1_bits(12); } if (opt & 2) pmode = 7 - 4 * ph1_bits(1); else if (!ph1_bits(1)) pmode = ph1_bits(3); if (opt & 1 || !ph1_bits(1)) { FORC4 len[c] = ph1_bits(2); FORC4 { i = ((row & 1) << 1 | (c & 1)) % 3; len[c] = len[c] < 3 ? lent[i][0] - '1' + "120"[len[c]] : ph1_bits(4); lent[i][0] = lent[i][1]; lent[i][1] = len[c]; } } FORC(16) { col = tab + (((c & 7) << 1) ^ (c >> 3) ^ (row & 1)); pred = (pmode == 7 || row < 2) ? (tab ? RAW(row, tab - 2 + (col & 1)) : init) : (prow[col & 1][col - '4' + "0224468"[pmode]] + prow[col & 1][col - '4' + "0244668"[pmode]] + 1) >> 1; diff = ph1_bits(i = len[c >> 2]); if (diff >> (i - 1)) diff -= 1 << i; diff = diff * (mag * 2 + 1) + mag; RAW(row, col) = pred + diff; } } } } #define HOLE(row) ((holes >> (((row)-raw_height) & 7)) & 1) /* Kudos to Rich Taylor for figuring out SMaL's compression algorithm. */ void CLASS smal_decode_segment(unsigned seg[2][2], int holes) { uchar hist[3][13] = {{7, 7, 0, 0, 63, 55, 47, 39, 31, 23, 15, 7, 0}, {7, 7, 0, 0, 63, 55, 47, 39, 31, 23, 15, 7, 0}, {3, 3, 0, 0, 63, 47, 31, 15, 0}}; int low, high = 0xff, carry = 0, nbits = 8; int pix, s, count, bin, next, i, sym[3]; uchar diff, pred[] = {0, 0}; ushort data = 0, range = 0; fseek(ifp, seg[0][1] + 1, SEEK_SET); getbits(-1); if (seg[1][0] > raw_width * raw_height) seg[1][0] = raw_width * raw_height; for (pix = seg[0][0]; pix < seg[1][0]; pix++) { for (s = 0; s < 3; s++) { data = data << nbits | getbits(nbits); if (carry < 0) carry = (nbits += carry + 1) < 1 ? nbits - 1 : 0; while (--nbits >= 0) if ((data >> nbits & 0xff) == 0xff) break; if (nbits > 0) data = ((data & ((1 << (nbits - 1)) - 1)) << 1) | ((data + (((data & (1 << (nbits - 1)))) << 1)) & ((~0u) << nbits)); if (nbits >= 0) { data += getbits(1); carry = nbits - 8; } count = ((((data - range + 1) & 0xffff) << 2) - 1) / (high >> 4); for (bin = 0; hist[s][bin + 5] > count; bin++) ; low = hist[s][bin + 5] * (high >> 4) >> 2; if (bin) high = hist[s][bin + 4] * (high >> 4) >> 2; high -= low; for (nbits = 0; high << nbits < 128; nbits++) ; range = (range + low) << nbits; high <<= nbits; next = hist[s][1]; if (++hist[s][2] > hist[s][3]) { next = (next + 1) & hist[s][0]; hist[s][3] = (hist[s][next + 4] - hist[s][next + 5]) >> 2; hist[s][2] = 1; } if (hist[s][hist[s][1] + 4] - hist[s][hist[s][1] + 5] > 1) { if (bin < hist[s][1]) for (i = bin; i < hist[s][1]; i++) hist[s][i + 5]--; else if (next <= bin) for (i = hist[s][1]; i < bin; i++) hist[s][i + 5]++; } hist[s][1] = next; sym[s] = bin; } diff = sym[2] << 5 | sym[1] << 2 | (sym[0] & 3); if (sym[0] & 4) diff = diff ? -diff : 0x80; if (ftell(ifp) + 12 >= seg[1][1]) diff = 0; #ifdef LIBRAW_LIBRARY_BUILD if (pix >= raw_width * raw_height) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif raw_image[pix] = pred[pix & 1] += diff; if (!(pix & 1) && HOLE(pix / raw_width)) pix += 2; } maximum = 0xff; } void CLASS smal_v6_load_raw() { unsigned seg[2][2]; fseek(ifp, 16, SEEK_SET); seg[0][0] = 0; seg[0][1] = get2(); seg[1][0] = raw_width * raw_height; seg[1][1] = INT_MAX; smal_decode_segment(seg, 0); } int CLASS median4(int *p) { int min, max, sum, i; min = max = sum = p[0]; for (i = 1; i < 4; i++) { sum += p[i]; if (min > p[i]) min = p[i]; if (max < p[i]) max = p[i]; } return (sum - min - max) >> 1; } void CLASS fill_holes(int holes) { int row, col, val[4]; for (row = 2; row < height - 2; row++) { if (!HOLE(row)) continue; for (col = 1; col < width - 1; col += 4) { val[0] = RAW(row - 1, col - 1); val[1] = RAW(row - 1, col + 1); val[2] = RAW(row + 1, col - 1); val[3] = RAW(row + 1, col + 1); RAW(row, col) = median4(val); } for (col = 2; col < width - 2; col += 4) if (HOLE(row - 2) || HOLE(row + 2)) RAW(row, col) = (RAW(row, col - 2) + RAW(row, col + 2)) >> 1; else { val[0] = RAW(row, col - 2); val[1] = RAW(row, col + 2); val[2] = RAW(row - 2, col); val[3] = RAW(row + 2, col); RAW(row, col) = median4(val); } } } void CLASS smal_v9_load_raw() { unsigned seg[256][2], offset, nseg, holes, i; fseek(ifp, 67, SEEK_SET); offset = get4(); nseg = (uchar)fgetc(ifp); fseek(ifp, offset, SEEK_SET); for (i = 0; i < nseg * 2; i++) ((unsigned *)seg)[i] = get4() + data_offset * (i & 1); fseek(ifp, 78, SEEK_SET); holes = fgetc(ifp); fseek(ifp, 88, SEEK_SET); seg[nseg][0] = raw_height * raw_width; seg[nseg][1] = get4() + data_offset; for (i = 0; i < nseg; i++) smal_decode_segment(seg + i, holes); if (holes) fill_holes(holes); } void CLASS redcine_load_raw() { #ifndef NO_JASPER int c, row, col; jas_stream_t *in; jas_image_t *jimg; jas_matrix_t *jmat; jas_seqent_t *data; ushort *img, *pix; jas_init(); #ifndef LIBRAW_LIBRARY_BUILD in = jas_stream_fopen(ifname, "rb"); #else in = (jas_stream_t *)ifp->make_jas_stream(); if (!in) throw LIBRAW_EXCEPTION_DECODE_JPEG2000; #endif jas_stream_seek(in, data_offset + 20, SEEK_SET); jimg = jas_image_decode(in, -1, 0); #ifndef LIBRAW_LIBRARY_BUILD if (!jimg) longjmp(failure, 3); #else if (!jimg) { jas_stream_close(in); throw LIBRAW_EXCEPTION_DECODE_JPEG2000; } #endif jmat = jas_matrix_create(height / 2, width / 2); merror(jmat, "redcine_load_raw()"); img = (ushort *)calloc((height + 2), (width + 2) * 2); merror(img, "redcine_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD bool fastexitflag = false; try { #endif FORC4 { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif jas_image_readcmpt(jimg, c, 0, 0, width / 2, height / 2, jmat); data = jas_matrix_getref(jmat, 0, 0); for (row = c >> 1; row < height; row += 2) for (col = c & 1; col < width; col += 2) img[(row + 1) * (width + 2) + col + 1] = data[(row / 2) * (width / 2) + col / 2]; } for (col = 1; col <= width; col++) { img[col] = img[2 * (width + 2) + col]; img[(height + 1) * (width + 2) + col] = img[(height - 1) * (width + 2) + col]; } for (row = 0; row < height + 2; row++) { img[row * (width + 2)] = img[row * (width + 2) + 2]; img[(row + 1) * (width + 2) - 1] = img[(row + 1) * (width + 2) - 3]; } for (row = 1; row <= height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif pix = img + row * (width + 2) + (col = 1 + (FC(row, 1) & 1)); for (; col <= width; col += 2, pix += 2) { c = (((pix[0] - 0x800) << 3) + pix[-(width + 2)] + pix[width + 2] + pix[-1] + pix[1]) >> 2; pix[0] = LIM(c, 0, 4095); } } for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < width; col++) RAW(row, col) = curve[img[(row + 1) * (width + 2) + col + 1]]; } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { fastexitflag = true; } #endif free(img); jas_matrix_destroy(jmat); jas_image_destroy(jimg); jas_stream_close(in); #ifdef LIBRAW_LIBRARY_BUILD if (fastexitflag) throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK; #endif #endif } //@end COMMON /* RESTRICTED code starts here */ void CLASS foveon_decoder(unsigned size, unsigned code) { static unsigned huff[1024]; struct decode *cur; int i, len; if (!code) { for (i = 0; i < size; i++) huff[i] = get4(); memset(first_decode, 0, sizeof first_decode); free_decode = first_decode; } cur = free_decode++; if (free_decode > first_decode + 2048) { fprintf(stderr, _("%s: decoder table overflow\n"), ifname); longjmp(failure, 2); } if (code) for (i = 0; i < size; i++) if (huff[i] == code) { cur->leaf = i; return; } if ((len = code >> 27) > 26) return; code = (len + 1) << 27 | (code & 0x3ffffff) << 1; cur->branch[0] = free_decode; foveon_decoder(size, code); cur->branch[1] = free_decode; foveon_decoder(size, code + 1); } void CLASS foveon_thumb() { unsigned bwide, row, col, bitbuf = 0, bit = 1, c, i; char *buf; struct decode *dindex; short pred[3]; bwide = get4(); fprintf(ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); if (bwide > 0) { if (bwide < thumb_width * 3) return; buf = (char *)malloc(bwide); merror(buf, "foveon_thumb()"); for (row = 0; row < thumb_height; row++) { fread(buf, 1, bwide, ifp); fwrite(buf, 3, thumb_width, ofp); } free(buf); return; } foveon_decoder(256, 0); for (row = 0; row < thumb_height; row++) { memset(pred, 0, sizeof pred); if (!bit) get4(); for (bit = col = 0; col < thumb_width; col++) FORC3 { for (dindex = first_decode; dindex->branch[0];) { if ((bit = (bit - 1) & 31) == 31) for (i = 0; i < 4; i++) bitbuf = (bitbuf << 8) + fgetc(ifp); dindex = dindex->branch[bitbuf >> bit & 1]; } pred[c] += dindex->leaf; fputc(pred[c], ofp); } } } void CLASS foveon_sd_load_raw() { struct decode *dindex; short diff[1024]; unsigned bitbuf = 0; int pred[3], row, col, bit = -1, c, i; read_shorts((ushort *)diff, 1024); if (!load_flags) foveon_decoder(1024, 0); for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif memset(pred, 0, sizeof pred); if (!bit && !load_flags && atoi(model + 2) < 14) get4(); for (col = bit = 0; col < width; col++) { if (load_flags) { bitbuf = get4(); FORC3 pred[2 - c] += diff[bitbuf >> c * 10 & 0x3ff]; } else FORC3 { for (dindex = first_decode; dindex->branch[0];) { if ((bit = (bit - 1) & 31) == 31) for (i = 0; i < 4; i++) bitbuf = (bitbuf << 8) + fgetc(ifp); dindex = dindex->branch[bitbuf >> bit & 1]; } pred[c] += diff[dindex->leaf]; if (pred[c] >> 16 && ~pred[c] >> 16) derror(); } FORC3 image[row * width + col][c] = pred[c]; } } } void CLASS foveon_huff(ushort *huff) { int i, j, clen, code; huff[0] = 8; for (i = 0; i < 13; i++) { clen = getc(ifp); code = getc(ifp); for (j = 0; j<256>> clen;) huff[code + ++j] = clen << 8 | i; } get2(); } void CLASS foveon_dp_load_raw() { unsigned c, roff[4], row, col, diff; ushort huff[512], vpred[2][2], hpred[2]; fseek(ifp, 8, SEEK_CUR); foveon_huff(huff); roff[0] = 48; FORC3 roff[c + 1] = -(-(roff[c] + get4()) & -16); FORC3 { fseek(ifp, data_offset + roff[c], SEEK_SET); getbits(-1); vpred[0][0] = vpred[0][1] = vpred[1][0] = vpred[1][1] = 512; for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < width; col++) { diff = ljpeg_diff(huff); if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; image[row * width + col][c] = hpred[col & 1]; } } } } void CLASS foveon_load_camf() { unsigned type, wide, high, i, j, row, col, diff; ushort huff[258], vpred[2][2] = {{512, 512}, {512, 512}}, hpred[2]; fseek(ifp, meta_offset, SEEK_SET); type = get4(); get4(); get4(); wide = get4(); high = get4(); if (type == 2) { fread(meta_data, 1, meta_length, ifp); for (i = 0; i < meta_length; i++) { high = (high * 1597 + 51749) % 244944; wide = high * (INT64)301593171 >> 24; meta_data[i] ^= ((((high << 8) - wide) >> 1) + wide) >> 17; } } else if (type == 4) { free(meta_data); meta_data = (char *)malloc(meta_length = wide * high * 3 / 2); merror(meta_data, "foveon_load_camf()"); foveon_huff(huff); get4(); getbits(-1); for (j = row = 0; row < high; row++) { for (col = 0; col < wide; col++) { diff = ljpeg_diff(huff); if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; if (col & 1) { meta_data[j++] = hpred[0] >> 4; meta_data[j++] = hpred[0] << 4 | hpred[1] >> 8; meta_data[j++] = hpred[1]; } } } } #ifdef DCRAW_VERBOSE else fprintf(stderr, _("%s has unknown CAMF type %d.\n"), ifname, type); #endif } const char *CLASS foveon_camf_param(const char *block, const char *param) { unsigned idx, num; char *pos, *cp, *dp; for (idx = 0; idx < meta_length; idx += sget4(pos + 8)) { pos = meta_data + idx; if (strncmp(pos, "CMb", 3)) break; if (pos[3] != 'P') continue; if (strcmp(block, pos + sget4(pos + 12))) continue; cp = pos + sget4(pos + 16); num = sget4(cp); dp = pos + sget4(cp + 4); while (num--) { cp += 8; if (!strcmp(param, dp + sget4(cp))) return dp + sget4(cp + 4); } } return 0; } void *CLASS foveon_camf_matrix(unsigned dim[3], const char *name) { unsigned i, idx, type, ndim, size, *mat; char *pos, *cp, *dp; double dsize; for (idx = 0; idx < meta_length; idx += sget4(pos + 8)) { pos = meta_data + idx; if (strncmp(pos, "CMb", 3)) break; if (pos[3] != 'M') continue; if (strcmp(name, pos + sget4(pos + 12))) continue; dim[0] = dim[1] = dim[2] = 1; cp = pos + sget4(pos + 16); type = sget4(cp); if ((ndim = sget4(cp + 4)) > 3) break; dp = pos + sget4(cp + 8); for (i = ndim; i--;) { cp += 12; dim[i] = sget4(cp); } if ((dsize = (double)dim[0] * dim[1] * dim[2]) > meta_length / 4) break; mat = (unsigned *)malloc((size = dsize) * 4); merror(mat, "foveon_camf_matrix()"); for (i = 0; i < size; i++) if (type && type != 6) mat[i] = sget4(dp + i * 4); else mat[i] = sget4(dp + i * 2) & 0xffff; return mat; } #ifdef DCRAW_VERBOSE fprintf(stderr, _("%s: \"%s\" matrix not found!\n"), ifname, name); #endif return 0; } int CLASS foveon_fixed(void *ptr, int size, const char *name) { void *dp; unsigned dim[3]; if (!name) return 0; dp = foveon_camf_matrix(dim, name); if (!dp) return 0; memcpy(ptr, dp, size * 4); free(dp); return 1; } float CLASS foveon_avg(short *pix, int range[2], float cfilt) { int i; float val, min = FLT_MAX, max = -FLT_MAX, sum = 0; for (i = range[0]; i <= range[1]; i++) { sum += val = pix[i * 4] + (pix[i * 4] - pix[(i - 1) * 4]) * cfilt; if (min > val) min = val; if (max < val) max = val; } if (range[1] - range[0] == 1) return sum / 2; return (sum - min - max) / (range[1] - range[0] - 1); } short *CLASS foveon_make_curve(double max, double mul, double filt) { short *curve; unsigned i, size; double x; if (!filt) filt = 0.8; size = 4 * M_PI * max / filt; if (size == UINT_MAX) size--; curve = (short *)calloc(size + 1, sizeof *curve); merror(curve, "foveon_make_curve()"); curve[0] = size; for (i = 0; i < size; i++) { x = i * filt / max / 4; curve[i + 1] = (cos(x) + 1) / 2 * tanh(i * filt / mul) * mul + 0.5; } return curve; } void CLASS foveon_make_curves(short **curvep, float dq[3], float div[3], float filt) { double mul[3], max = 0; int c; FORC3 mul[c] = dq[c] / div[c]; FORC3 if (max < mul[c]) max = mul[c]; FORC3 curvep[c] = foveon_make_curve(max, mul[c], filt); } int CLASS foveon_apply_curve(short *curve, int i) { if (abs(i) >= curve[0]) return 0; return i < 0 ? -curve[1 - i] : curve[1 + i]; } #define image ((short(*)[4])image) void CLASS foveon_interpolate() { static const short hood[] = {-1, -1, -1, 0, -1, 1, 0, -1, 0, 1, 1, -1, 1, 0, 1, 1}; short *pix, prev[3], *curve[8], (*shrink)[3]; float cfilt = 0, ddft[3][3][2], ppm[3][3][3]; float cam_xyz[3][3], correct[3][3], last[3][3], trans[3][3]; float chroma_dq[3], color_dq[3], diag[3][3], div[3]; float(*black)[3], (*sgain)[3], (*sgrow)[3]; float fsum[3], val, frow, num; int row, col, c, i, j, diff, sgx, irow, sum, min, max, limit; int dscr[2][2], dstb[4], (*smrow[7])[3], total[4], ipix[3]; int work[3][3], smlast, smred, smred_p = 0, dev[3]; int satlev[3], keep[4], active[4]; unsigned dim[3], *badpix; double dsum = 0, trsum[3]; char str[128]; const char *cp; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Foveon interpolation...\n")); #endif foveon_load_camf(); foveon_fixed(dscr, 4, "DarkShieldColRange"); foveon_fixed(ppm[0][0], 27, "PostPolyMatrix"); foveon_fixed(satlev, 3, "SaturationLevel"); foveon_fixed(keep, 4, "KeepImageArea"); foveon_fixed(active, 4, "ActiveImageArea"); foveon_fixed(chroma_dq, 3, "ChromaDQ"); foveon_fixed(color_dq, 3, foveon_camf_param("IncludeBlocks", "ColorDQ") ? "ColorDQ" : "ColorDQCamRGB"); if (foveon_camf_param("IncludeBlocks", "ColumnFilter")) foveon_fixed(&cfilt, 1, "ColumnFilter"); memset(ddft, 0, sizeof ddft); if (!foveon_camf_param("IncludeBlocks", "DarkDrift") || !foveon_fixed(ddft[1][0], 12, "DarkDrift")) for (i = 0; i < 2; i++) { foveon_fixed(dstb, 4, i ? "DarkShieldBottom" : "DarkShieldTop"); for (row = dstb[1]; row <= dstb[3]; row++) for (col = dstb[0]; col <= dstb[2]; col++) FORC3 ddft[i + 1][c][1] += (short)image[row * width + col][c]; FORC3 ddft[i + 1][c][1] /= (dstb[3] - dstb[1] + 1) * (dstb[2] - dstb[0] + 1); } if (!(cp = foveon_camf_param("WhiteBalanceIlluminants", model2))) { #ifdef DCRAW_VERBOSE fprintf(stderr, _("%s: Invalid white balance \"%s\"\n"), ifname, model2); #endif return; } foveon_fixed(cam_xyz, 9, cp); foveon_fixed(correct, 9, foveon_camf_param("WhiteBalanceCorrections", model2)); memset(last, 0, sizeof last); for (i = 0; i < 3; i++) for (j = 0; j < 3; j++) FORC3 last[i][j] += correct[i][c] * cam_xyz[c][j]; #define LAST(x, y) last[(i + x) % 3][(c + y) % 3] for (i = 0; i < 3; i++) FORC3 diag[c][i] = LAST(1, 1) * LAST(2, 2) - LAST(1, 2) * LAST(2, 1); #undef LAST FORC3 div[c] = diag[c][0] * 0.3127 + diag[c][1] * 0.329 + diag[c][2] * 0.3583; sprintf(str, "%sRGBNeutral", model2); if (foveon_camf_param("IncludeBlocks", str)) foveon_fixed(div, 3, str); num = 0; FORC3 if (num < div[c]) num = div[c]; FORC3 div[c] /= num; memset(trans, 0, sizeof trans); for (i = 0; i < 3; i++) for (j = 0; j < 3; j++) FORC3 trans[i][j] += rgb_cam[i][c] * last[c][j] * div[j]; FORC3 trsum[c] = trans[c][0] + trans[c][1] + trans[c][2]; dsum = (6 * trsum[0] + 11 * trsum[1] + 3 * trsum[2]) / 20; for (i = 0; i < 3; i++) FORC3 last[i][c] = trans[i][c] * dsum / trsum[i]; memset(trans, 0, sizeof trans); for (i = 0; i < 3; i++) for (j = 0; j < 3; j++) FORC3 trans[i][j] += (i == c ? 32 : -1) * last[c][j] / 30; foveon_make_curves(curve, color_dq, div, cfilt); FORC3 chroma_dq[c] /= 3; foveon_make_curves(curve + 3, chroma_dq, div, cfilt); FORC3 dsum += chroma_dq[c] / div[c]; curve[6] = foveon_make_curve(dsum, dsum, cfilt); curve[7] = foveon_make_curve(dsum * 2, dsum * 2, cfilt); sgain = (float(*)[3])foveon_camf_matrix(dim, "SpatialGain"); if (!sgain) return; sgrow = (float(*)[3])calloc(dim[1], sizeof *sgrow); sgx = (width + dim[1] - 2) / (dim[1] - 1); black = (float(*)[3])calloc(height, sizeof *black); for (row = 0; row < height; row++) { for (i = 0; i < 6; i++) ((float *)ddft[0])[i] = ((float *)ddft[1])[i] + row / (height - 1.0) * (((float *)ddft[2])[i] - ((float *)ddft[1])[i]); FORC3 black[row][c] = (foveon_avg(image[row * width] + c, dscr[0], cfilt) + foveon_avg(image[row * width] + c, dscr[1], cfilt) * 3 - ddft[0][c][0]) / 4 - ddft[0][c][1]; } memcpy(black, black + 8, sizeof *black * 8); memcpy(black + height - 11, black + height - 22, 11 * sizeof *black); memcpy(last, black, sizeof last); for (row = 1; row < height - 1; row++) { FORC3 if (last[1][c] > last[0][c]) { if (last[1][c] > last[2][c]) black[row][c] = (last[0][c] > last[2][c]) ? last[0][c] : last[2][c]; } else if (last[1][c] < last[2][c]) black[row][c] = (last[0][c] < last[2][c]) ? last[0][c] : last[2][c]; memmove(last, last + 1, 2 * sizeof last[0]); memcpy(last[2], black[row + 1], sizeof last[2]); } FORC3 black[row][c] = (last[0][c] + last[1][c]) / 2; FORC3 black[0][c] = (black[1][c] + black[3][c]) / 2; val = 1 - exp(-1 / 24.0); memcpy(fsum, black, sizeof fsum); for (row = 1; row < height; row++) FORC3 fsum[c] += black[row][c] = (black[row][c] - black[row - 1][c]) * val + black[row - 1][c]; memcpy(last[0], black[height - 1], sizeof last[0]); FORC3 fsum[c] /= height; for (row = height; row--;) FORC3 last[0][c] = black[row][c] = (black[row][c] - fsum[c] - last[0][c]) * val + last[0][c]; memset(total, 0, sizeof total); for (row = 2; row < height; row += 4) for (col = 2; col < width; col += 4) { FORC3 total[c] += (short)image[row * width + col][c]; total[3]++; } for (row = 0; row < height; row++) FORC3 black[row][c] += fsum[c] / 2 + total[c] / (total[3] * 100.0); for (row = 0; row < height; row++) { for (i = 0; i < 6; i++) ((float *)ddft[0])[i] = ((float *)ddft[1])[i] + row / (height - 1.0) * (((float *)ddft[2])[i] - ((float *)ddft[1])[i]); pix = image[row * width]; memcpy(prev, pix, sizeof prev); frow = row / (height - 1.0) * (dim[2] - 1); if ((irow = frow) == dim[2] - 1) irow--; frow -= irow; for (i = 0; i < dim[1]; i++) FORC3 sgrow[i][c] = sgain[irow * dim[1] + i][c] * (1 - frow) + sgain[(irow + 1) * dim[1] + i][c] * frow; for (col = 0; col < width; col++) { FORC3 { diff = pix[c] - prev[c]; prev[c] = pix[c]; ipix[c] = pix[c] + floor((diff + (diff * diff >> 14)) * cfilt - ddft[0][c][1] - ddft[0][c][0] * ((float)col / width - 0.5) - black[row][c]); } FORC3 { work[0][c] = ipix[c] * ipix[c] >> 14; work[2][c] = ipix[c] * work[0][c] >> 14; work[1][2 - c] = ipix[(c + 1) % 3] * ipix[(c + 2) % 3] >> 14; } FORC3 { for (val = i = 0; i < 3; i++) for (j = 0; j < 3; j++) val += ppm[c][i][j] * work[i][j]; ipix[c] = floor((ipix[c] + floor(val)) * (sgrow[col / sgx][c] * (sgx - col % sgx) + sgrow[col / sgx + 1][c] * (col % sgx)) / sgx / div[c]); if (ipix[c] > 32000) ipix[c] = 32000; pix[c] = ipix[c]; } pix += 4; } } free(black); free(sgrow); free(sgain); if ((badpix = (unsigned *)foveon_camf_matrix(dim, "BadPixels"))) { for (i = 0; i < dim[0]; i++) { col = (badpix[i] >> 8 & 0xfff) - keep[0]; row = (badpix[i] >> 20) - keep[1]; if ((unsigned)(row - 1) > height - 3 || (unsigned)(col - 1) > width - 3) continue; memset(fsum, 0, sizeof fsum); for (sum = j = 0; j < 8; j++) if (badpix[i] & (1 << j)) { FORC3 fsum[c] += (short)image[(row + hood[j * 2]) * width + col + hood[j * 2 + 1]][c]; sum++; } if (sum) FORC3 image[row * width + col][c] = fsum[c] / sum; } free(badpix); } /* Array for 5x5 Gaussian averaging of red values */ smrow[6] = (int(*)[3])calloc(width * 5, sizeof **smrow); merror(smrow[6], "foveon_interpolate()"); for (i = 0; i < 5; i++) smrow[i] = smrow[6] + i * width; /* Sharpen the reds against these Gaussian averages */ for (smlast = -1, row = 2; row < height - 2; row++) { while (smlast < row + 2) { for (i = 0; i < 6; i++) smrow[(i + 5) % 6] = smrow[i]; pix = image[++smlast * width + 2]; for (col = 2; col < width - 2; col++) { smrow[4][col][0] = (pix[0] * 6 + (pix[-4] + pix[4]) * 4 + pix[-8] + pix[8] + 8) >> 4; pix += 4; } } pix = image[row * width + 2]; for (col = 2; col < width - 2; col++) { smred = (6 * smrow[2][col][0] + 4 * (smrow[1][col][0] + smrow[3][col][0]) + smrow[0][col][0] + smrow[4][col][0] + 8) >> 4; if (col == 2) smred_p = smred; i = pix[0] + ((pix[0] - ((smred * 7 + smred_p) >> 3)) >> 3); if (i > 32000) i = 32000; pix[0] = i; smred_p = smred; pix += 4; } } /* Adjust the brighter pixels for better linearity */ min = 0xffff; FORC3 { i = satlev[c] / div[c]; if (min > i) min = i; } limit = min * 9 >> 4; for (pix = image[0]; pix < image[height * width]; pix += 4) { if (pix[0] <= limit || pix[1] <= limit || pix[2] <= limit) continue; min = max = pix[0]; for (c = 1; c < 3; c++) { if (min > pix[c]) min = pix[c]; if (max < pix[c]) max = pix[c]; } if (min >= limit * 2) { pix[0] = pix[1] = pix[2] = max; } else { i = 0x4000 - ((min - limit) << 14) / limit; i = 0x4000 - (i * i >> 14); i = i * i >> 14; FORC3 pix[c] += (max - pix[c]) * i >> 14; } } /* Because photons that miss one detector often hit another, the sum R+G+B is much less noisy than the individual colors. So smooth the hues without smoothing the total. */ for (smlast = -1, row = 2; row < height - 2; row++) { while (smlast < row + 2) { for (i = 0; i < 6; i++) smrow[(i + 5) % 6] = smrow[i]; pix = image[++smlast * width + 2]; for (col = 2; col < width - 2; col++) { FORC3 smrow[4][col][c] = (pix[c - 4] + 2 * pix[c] + pix[c + 4] + 2) >> 2; pix += 4; } } pix = image[row * width + 2]; for (col = 2; col < width - 2; col++) { FORC3 dev[c] = -foveon_apply_curve(curve[7], pix[c] - ((smrow[1][col][c] + 2 * smrow[2][col][c] + smrow[3][col][c]) >> 2)); sum = (dev[0] + dev[1] + dev[2]) >> 3; FORC3 pix[c] += dev[c] - sum; pix += 4; } } for (smlast = -1, row = 2; row < height - 2; row++) { while (smlast < row + 2) { for (i = 0; i < 6; i++) smrow[(i + 5) % 6] = smrow[i]; pix = image[++smlast * width + 2]; for (col = 2; col < width - 2; col++) { FORC3 smrow[4][col][c] = (pix[c - 8] + pix[c - 4] + pix[c] + pix[c + 4] + pix[c + 8] + 2) >> 2; pix += 4; } } pix = image[row * width + 2]; for (col = 2; col < width - 2; col++) { for (total[3] = 375, sum = 60, c = 0; c < 3; c++) { for (total[c] = i = 0; i < 5; i++) total[c] += smrow[i][col][c]; total[3] += total[c]; sum += pix[c]; } if (sum < 0) sum = 0; j = total[3] > 375 ? (sum << 16) / total[3] : sum * 174; FORC3 pix[c] += foveon_apply_curve(curve[6], ((j * total[c] + 0x8000) >> 16) - pix[c]); pix += 4; } } /* Transform the image to a different colorspace */ for (pix = image[0]; pix < image[height * width]; pix += 4) { FORC3 pix[c] -= foveon_apply_curve(curve[c], pix[c]); sum = (pix[0] + pix[1] + pix[1] + pix[2]) >> 2; FORC3 pix[c] -= foveon_apply_curve(curve[c], pix[c] - sum); FORC3 { for (dsum = i = 0; i < 3; i++) dsum += trans[c][i] * pix[i]; if (dsum < 0) dsum = 0; if (dsum > 24000) dsum = 24000; ipix[c] = dsum + 0.5; } FORC3 pix[c] = ipix[c]; } /* Smooth the image bottom-to-top and save at 1/4 scale */ shrink = (short(*)[3])calloc((height / 4), (width / 4) * sizeof *shrink); merror(shrink, "foveon_interpolate()"); for (row = height / 4; row--;) for (col = 0; col < width / 4; col++) { ipix[0] = ipix[1] = ipix[2] = 0; for (i = 0; i < 4; i++) for (j = 0; j < 4; j++) FORC3 ipix[c] += image[(row * 4 + i) * width + col * 4 + j][c]; FORC3 if (row + 2 > height / 4) shrink[row * (width / 4) + col][c] = ipix[c] >> 4; else shrink[row * (width / 4) + col][c] = (shrink[(row + 1) * (width / 4) + col][c] * 1840 + ipix[c] * 141 + 2048) >> 12; } /* From the 1/4-scale image, smooth right-to-left */ for (row = 0; row < (height & ~3); row++) { ipix[0] = ipix[1] = ipix[2] = 0; if ((row & 3) == 0) for (col = width & ~3; col--;) FORC3 smrow[0][col][c] = ipix[c] = (shrink[(row / 4) * (width / 4) + col / 4][c] * 1485 + ipix[c] * 6707 + 4096) >> 13; /* Then smooth left-to-right */ ipix[0] = ipix[1] = ipix[2] = 0; for (col = 0; col < (width & ~3); col++) FORC3 smrow[1][col][c] = ipix[c] = (smrow[0][col][c] * 1485 + ipix[c] * 6707 + 4096) >> 13; /* Smooth top-to-bottom */ if (row == 0) memcpy(smrow[2], smrow[1], sizeof **smrow * width); else for (col = 0; col < (width & ~3); col++) FORC3 smrow[2][col][c] = (smrow[2][col][c] * 6707 + smrow[1][col][c] * 1485 + 4096) >> 13; /* Adjust the chroma toward the smooth values */ for (col = 0; col < (width & ~3); col++) { for (i = j = 30, c = 0; c < 3; c++) { i += smrow[2][col][c]; j += image[row * width + col][c]; } j = (j << 16) / i; for (sum = c = 0; c < 3; c++) { ipix[c] = foveon_apply_curve(curve[c + 3], ((smrow[2][col][c] * j + 0x8000) >> 16) - image[row * width + col][c]); sum += ipix[c]; } sum >>= 3; FORC3 { i = image[row * width + col][c] + ipix[c] - sum; if (i < 0) i = 0; image[row * width + col][c] = i; } } } free(shrink); free(smrow[6]); for (i = 0; i < 8; i++) free(curve[i]); /* Trim off the black border */ active[1] -= keep[1]; active[3] -= 2; i = active[2] - active[0]; for (row = 0; row < active[3] - active[1]; row++) memcpy(image[row * i], image[(row + active[1]) * width + active[0]], i * sizeof *image); width = i; height = row; } #undef image /* RESTRICTED code ends here */ //@out COMMON void CLASS crop_masked_pixels() { int row, col; unsigned #ifndef LIBRAW_LIBRARY_BUILD r, raw_pitch = raw_width * 2, c, m, mblack[8], zero, val; #else c, m, zero, val; #define mblack imgdata.color.black_stat #endif #ifndef LIBRAW_LIBRARY_BUILD if (load_raw == &CLASS phase_one_load_raw || load_raw == &CLASS phase_one_load_raw_c) phase_one_correct(); if (fuji_width) { for (row = 0; row < raw_height - top_margin * 2; row++) { for (col = 0; col < fuji_width << !fuji_layout; col++) { if (fuji_layout) { r = fuji_width - 1 - col + (row >> 1); c = col + ((row + 1) >> 1); } else { r = fuji_width - 1 + row - (col >> 1); c = row + ((col + 1) >> 1); } if (r < height && c < width) BAYER(r, c) = RAW(row + top_margin, col + left_margin); } } } else { for (row = 0; row < height; row++) for (col = 0; col < width; col++) BAYER2(row, col) = RAW(row + top_margin, col + left_margin); } #endif if (mask[0][3] > 0) goto mask_set; if (load_raw == &CLASS canon_load_raw || load_raw == &CLASS lossless_jpeg_load_raw) { mask[0][1] = mask[1][1] += 2; mask[0][3] -= 2; goto sides; } if (load_raw == &CLASS canon_600_load_raw || load_raw == &CLASS sony_load_raw || (load_raw == &CLASS eight_bit_load_raw && strncmp(model, "DC2", 3)) || load_raw == &CLASS kodak_262_load_raw || (load_raw == &CLASS packed_load_raw && (load_flags & 32))) { sides: mask[0][0] = mask[1][0] = top_margin; mask[0][2] = mask[1][2] = top_margin + height; mask[0][3] += left_margin; mask[1][1] += left_margin + width; mask[1][3] += raw_width; } if (load_raw == &CLASS nokia_load_raw) { mask[0][2] = top_margin; mask[0][3] = width; } #ifdef LIBRAW_LIBRARY_BUILD if (load_raw == &CLASS broadcom_load_raw) { mask[0][2] = top_margin; mask[0][3] = width; } #endif mask_set: memset(mblack, 0, sizeof mblack); for (zero = m = 0; m < 8; m++) for (row = MAX(mask[m][0], 0); row < MIN(mask[m][2], raw_height); row++) for (col = MAX(mask[m][1], 0); col < MIN(mask[m][3], raw_width); col++) { c = FC(row - top_margin, col - left_margin); mblack[c] += val = raw_image[(row)*raw_pitch / 2 + (col)]; mblack[4 + c]++; zero += !val; } if (load_raw == &CLASS canon_600_load_raw && width < raw_width) { black = (mblack[0] + mblack[1] + mblack[2] + mblack[3]) / (mblack[4] + mblack[5] + mblack[6] + mblack[7]) - 4; #ifndef LIBRAW_LIBRARY_BUILD canon_600_correct(); #endif } else if (zero < mblack[4] && mblack[5] && mblack[6] && mblack[7]) { FORC4 cblack[c] = mblack[c] / mblack[4 + c]; black = cblack[4] = cblack[5] = cblack[6] = 0; } } #ifdef LIBRAW_LIBRARY_BUILD #undef mblack #endif void CLASS remove_zeroes() { unsigned row, col, tot, n, r, c; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_REMOVE_ZEROES, 0, 2); #endif for (row = 0; row < height; row++) for (col = 0; col < width; col++) if (BAYER(row, col) == 0) { tot = n = 0; for (r = row - 2; r <= row + 2; r++) for (c = col - 2; c <= col + 2; c++) if (r < height && c < width && FC(r, c) == FC(row, col) && BAYER(r, c)) tot += (n++, BAYER(r, c)); if (n) BAYER(row, col) = tot / n; } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_REMOVE_ZEROES, 1, 2); #endif } //@end COMMON /* @out FILEIO #include <math.h> #define CLASS LibRaw:: #include "libraw/libraw_types.h" #define LIBRAW_LIBRARY_BUILD #include "libraw/libraw.h" #include "internal/defines.h" #include "internal/var_defines.h" @end FILEIO */ // @out FILEIO /* Search from the current directory up to the root looking for a ".badpixels" file, and fix those pixels now. */ void CLASS bad_pixels(const char *cfname) { FILE *fp = NULL; #ifndef LIBRAW_LIBRARY_BUILD char *fname, *cp, line[128]; int len, time, row, col, r, c, rad, tot, n, fixed = 0; #else char *cp, line[128]; int time, row, col, r, c, rad, tot, n; #ifdef DCRAW_VERBOSE int fixed = 0; #endif #endif if (!filters) return; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_BAD_PIXELS, 0, 2); #endif if (cfname) fp = fopen(cfname, "r"); // @end FILEIO else { for (len = 32;; len *= 2) { fname = (char *)malloc(len); if (!fname) return; if (getcwd(fname, len - 16)) break; free(fname); if (errno != ERANGE) return; } #if defined(WIN32) || defined(DJGPP) if (fname[1] == ':') memmove(fname, fname + 2, len - 2); for (cp = fname; *cp; cp++) if (*cp == '\\') *cp = '/'; #endif cp = fname + strlen(fname); if (cp[-1] == '/') cp--; while (*fname == '/') { strcpy(cp, "/.badpixels"); if ((fp = fopen(fname, "r"))) break; if (cp == fname) break; while (*--cp != '/') ; } free(fname); } // @out FILEIO if (!fp) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_BADPIXELMAP; #endif return; } while (fgets(line, 128, fp)) { cp = strchr(line, '#'); if (cp) *cp = 0; if (sscanf(line, "%d %d %d", &col, &row, &time) != 3) continue; if ((unsigned)col >= width || (unsigned)row >= height) continue; if (time > timestamp) continue; for (tot = n = 0, rad = 1; rad < 3 && n == 0; rad++) for (r = row - rad; r <= row + rad; r++) for (c = col - rad; c <= col + rad; c++) if ((unsigned)r < height && (unsigned)c < width && (r != row || c != col) && fcol(r, c) == fcol(row, col)) { tot += BAYER2(r, c); n++; } BAYER2(row, col) = tot / n; #ifdef DCRAW_VERBOSE if (verbose) { if (!fixed++) fprintf(stderr, _("Fixed dead pixels at:")); fprintf(stderr, " %d,%d", col, row); } #endif } #ifdef DCRAW_VERBOSE if (fixed) fputc('\n', stderr); #endif fclose(fp); #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_BAD_PIXELS, 1, 2); #endif } void CLASS subtract(const char *fname) { FILE *fp; int dim[3] = {0, 0, 0}, comment = 0, number = 0, error = 0, nd = 0, c, row, col; ushort *pixel; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_DARK_FRAME, 0, 2); #endif if (!(fp = fopen(fname, "rb"))) { #ifdef DCRAW_VERBOSE perror(fname); #endif #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_BAD_DARKFRAME_FILE; #endif return; } if (fgetc(fp) != 'P' || fgetc(fp) != '5') error = 1; while (!error && nd < 3 && (c = fgetc(fp)) != EOF) { if (c == '#') comment = 1; if (c == '\n') comment = 0; if (comment) continue; if (isdigit(c)) number = 1; if (number) { if (isdigit(c)) dim[nd] = dim[nd] * 10 + c - '0'; else if (isspace(c)) { number = 0; nd++; } else error = 1; } } if (error || nd < 3) { #ifdef DCRAW_VERBOSE fprintf(stderr, _("%s is not a valid PGM file!\n"), fname); #endif fclose(fp); return; } else if (dim[0] != width || dim[1] != height || dim[2] != 65535) { #ifdef DCRAW_VERBOSE fprintf(stderr, _("%s has the wrong dimensions!\n"), fname); #endif #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_BAD_DARKFRAME_DIM; #endif fclose(fp); return; } pixel = (ushort *)calloc(width, sizeof *pixel); merror(pixel, "subtract()"); for (row = 0; row < height; row++) { fread(pixel, 2, width, fp); for (col = 0; col < width; col++) BAYER(row, col) = MAX(BAYER(row, col) - ntohs(pixel[col]), 0); } free(pixel); fclose(fp); memset(cblack, 0, sizeof cblack); black = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_DARK_FRAME, 1, 2); #endif } //@end FILEIO //@out COMMON static const uchar xlat[2][256] = { {0xc1, 0xbf, 0x6d, 0x0d, 0x59, 0xc5, 0x13, 0x9d, 0x83, 0x61, 0x6b, 0x4f, 0xc7, 0x7f, 0x3d, 0x3d, 0x53, 0x59, 0xe3, 0xc7, 0xe9, 0x2f, 0x95, 0xa7, 0x95, 0x1f, 0xdf, 0x7f, 0x2b, 0x29, 0xc7, 0x0d, 0xdf, 0x07, 0xef, 0x71, 0x89, 0x3d, 0x13, 0x3d, 0x3b, 0x13, 0xfb, 0x0d, 0x89, 0xc1, 0x65, 0x1f, 0xb3, 0x0d, 0x6b, 0x29, 0xe3, 0xfb, 0xef, 0xa3, 0x6b, 0x47, 0x7f, 0x95, 0x35, 0xa7, 0x47, 0x4f, 0xc7, 0xf1, 0x59, 0x95, 0x35, 0x11, 0x29, 0x61, 0xf1, 0x3d, 0xb3, 0x2b, 0x0d, 0x43, 0x89, 0xc1, 0x9d, 0x9d, 0x89, 0x65, 0xf1, 0xe9, 0xdf, 0xbf, 0x3d, 0x7f, 0x53, 0x97, 0xe5, 0xe9, 0x95, 0x17, 0x1d, 0x3d, 0x8b, 0xfb, 0xc7, 0xe3, 0x67, 0xa7, 0x07, 0xf1, 0x71, 0xa7, 0x53, 0xb5, 0x29, 0x89, 0xe5, 0x2b, 0xa7, 0x17, 0x29, 0xe9, 0x4f, 0xc5, 0x65, 0x6d, 0x6b, 0xef, 0x0d, 0x89, 0x49, 0x2f, 0xb3, 0x43, 0x53, 0x65, 0x1d, 0x49, 0xa3, 0x13, 0x89, 0x59, 0xef, 0x6b, 0xef, 0x65, 0x1d, 0x0b, 0x59, 0x13, 0xe3, 0x4f, 0x9d, 0xb3, 0x29, 0x43, 0x2b, 0x07, 0x1d, 0x95, 0x59, 0x59, 0x47, 0xfb, 0xe5, 0xe9, 0x61, 0x47, 0x2f, 0x35, 0x7f, 0x17, 0x7f, 0xef, 0x7f, 0x95, 0x95, 0x71, 0xd3, 0xa3, 0x0b, 0x71, 0xa3, 0xad, 0x0b, 0x3b, 0xb5, 0xfb, 0xa3, 0xbf, 0x4f, 0x83, 0x1d, 0xad, 0xe9, 0x2f, 0x71, 0x65, 0xa3, 0xe5, 0x07, 0x35, 0x3d, 0x0d, 0xb5, 0xe9, 0xe5, 0x47, 0x3b, 0x9d, 0xef, 0x35, 0xa3, 0xbf, 0xb3, 0xdf, 0x53, 0xd3, 0x97, 0x53, 0x49, 0x71, 0x07, 0x35, 0x61, 0x71, 0x2f, 0x43, 0x2f, 0x11, 0xdf, 0x17, 0x97, 0xfb, 0x95, 0x3b, 0x7f, 0x6b, 0xd3, 0x25, 0xbf, 0xad, 0xc7, 0xc5, 0xc5, 0xb5, 0x8b, 0xef, 0x2f, 0xd3, 0x07, 0x6b, 0x25, 0x49, 0x95, 0x25, 0x49, 0x6d, 0x71, 0xc7}, {0xa7, 0xbc, 0xc9, 0xad, 0x91, 0xdf, 0x85, 0xe5, 0xd4, 0x78, 0xd5, 0x17, 0x46, 0x7c, 0x29, 0x4c, 0x4d, 0x03, 0xe9, 0x25, 0x68, 0x11, 0x86, 0xb3, 0xbd, 0xf7, 0x6f, 0x61, 0x22, 0xa2, 0x26, 0x34, 0x2a, 0xbe, 0x1e, 0x46, 0x14, 0x68, 0x9d, 0x44, 0x18, 0xc2, 0x40, 0xf4, 0x7e, 0x5f, 0x1b, 0xad, 0x0b, 0x94, 0xb6, 0x67, 0xb4, 0x0b, 0xe1, 0xea, 0x95, 0x9c, 0x66, 0xdc, 0xe7, 0x5d, 0x6c, 0x05, 0xda, 0xd5, 0xdf, 0x7a, 0xef, 0xf6, 0xdb, 0x1f, 0x82, 0x4c, 0xc0, 0x68, 0x47, 0xa1, 0xbd, 0xee, 0x39, 0x50, 0x56, 0x4a, 0xdd, 0xdf, 0xa5, 0xf8, 0xc6, 0xda, 0xca, 0x90, 0xca, 0x01, 0x42, 0x9d, 0x8b, 0x0c, 0x73, 0x43, 0x75, 0x05, 0x94, 0xde, 0x24, 0xb3, 0x80, 0x34, 0xe5, 0x2c, 0xdc, 0x9b, 0x3f, 0xca, 0x33, 0x45, 0xd0, 0xdb, 0x5f, 0xf5, 0x52, 0xc3, 0x21, 0xda, 0xe2, 0x22, 0x72, 0x6b, 0x3e, 0xd0, 0x5b, 0xa8, 0x87, 0x8c, 0x06, 0x5d, 0x0f, 0xdd, 0x09, 0x19, 0x93, 0xd0, 0xb9, 0xfc, 0x8b, 0x0f, 0x84, 0x60, 0x33, 0x1c, 0x9b, 0x45, 0xf1, 0xf0, 0xa3, 0x94, 0x3a, 0x12, 0x77, 0x33, 0x4d, 0x44, 0x78, 0x28, 0x3c, 0x9e, 0xfd, 0x65, 0x57, 0x16, 0x94, 0x6b, 0xfb, 0x59, 0xd0, 0xc8, 0x22, 0x36, 0xdb, 0xd2, 0x63, 0x98, 0x43, 0xa1, 0x04, 0x87, 0x86, 0xf7, 0xa6, 0x26, 0xbb, 0xd6, 0x59, 0x4d, 0xbf, 0x6a, 0x2e, 0xaa, 0x2b, 0xef, 0xe6, 0x78, 0xb6, 0x4e, 0xe0, 0x2f, 0xdc, 0x7c, 0xbe, 0x57, 0x19, 0x32, 0x7e, 0x2a, 0xd0, 0xb8, 0xba, 0x29, 0x00, 0x3c, 0x52, 0x7d, 0xa8, 0x49, 0x3b, 0x2d, 0xeb, 0x25, 0x49, 0xfa, 0xa3, 0xaa, 0x39, 0xa7, 0xc5, 0xa7, 0x50, 0x11, 0x36, 0xfb, 0xc6, 0x67, 0x4a, 0xf5, 0xa5, 0x12, 0x65, 0x7e, 0xb0, 0xdf, 0xaf, 0x4e, 0xb3, 0x61, 0x7f, 0x2f}}; void CLASS gamma_curve(double pwr, double ts, int mode, int imax) { int i; double g[6], bnd[2] = {0, 0}, r; g[0] = pwr; g[1] = ts; g[2] = g[3] = g[4] = 0; bnd[g[1] >= 1] = 1; if (g[1] && (g[1] - 1) * (g[0] - 1) <= 0) { for (i = 0; i < 48; i++) { g[2] = (bnd[0] + bnd[1]) / 2; if (g[0]) bnd[(pow(g[2] / g[1], -g[0]) - 1) / g[0] - 1 / g[2] > -1] = g[2]; else bnd[g[2] / exp(1 - 1 / g[2]) < g[1]] = g[2]; } g[3] = g[2] / g[1]; if (g[0]) g[4] = g[2] * (1 / g[0] - 1); } if (g[0]) g[5] = 1 / (g[1] * SQR(g[3]) / 2 - g[4] * (1 - g[3]) + (1 - pow(g[3], 1 + g[0])) * (1 + g[4]) / (1 + g[0])) - 1; else g[5] = 1 / (g[1] * SQR(g[3]) / 2 + 1 - g[2] - g[3] - g[2] * g[3] * (log(g[3]) - 1)) - 1; if (!mode--) { memcpy(gamm, g, sizeof gamm); return; } for (i = 0; i < 0x10000; i++) { curve[i] = 0xffff; if ((r = (double)i / imax) < 1) curve[i] = 0x10000 * (mode ? (r < g[3] ? r * g[1] : (g[0] ? pow(r, g[0]) * (1 + g[4]) - g[4] : log(r) * g[2] + 1)) : (r < g[2] ? r / g[1] : (g[0] ? pow((r + g[4]) / (1 + g[4]), 1 / g[0]) : exp((r - 1) / g[2])))); } } void CLASS pseudoinverse(double (*in)[3], double (*out)[3], int size) { double work[3][6], num; int i, j, k; for (i = 0; i < 3; i++) { for (j = 0; j < 6; j++) work[i][j] = j == i + 3; for (j = 0; j < 3; j++) for (k = 0; k < size; k++) work[i][j] += in[k][i] * in[k][j]; } for (i = 0; i < 3; i++) { num = work[i][i]; for (j = 0; j < 6; j++) work[i][j] /= num; for (k = 0; k < 3; k++) { if (k == i) continue; num = work[k][i]; for (j = 0; j < 6; j++) work[k][j] -= work[i][j] * num; } } for (i = 0; i < size; i++) for (j = 0; j < 3; j++) for (out[i][j] = k = 0; k < 3; k++) out[i][j] += work[j][k + 3] * in[i][k]; } void CLASS cam_xyz_coeff(float _rgb_cam[3][4], double cam_xyz[4][3]) { double cam_rgb[4][3], inverse[4][3], num; int i, j, k; for (i = 0; i < colors; i++) /* Multiply out XYZ colorspace */ for (j = 0; j < 3; j++) for (cam_rgb[i][j] = k = 0; k < 3; k++) cam_rgb[i][j] += cam_xyz[i][k] * xyz_rgb[k][j]; for (i = 0; i < colors; i++) { /* Normalize cam_rgb so that */ for (num = j = 0; j < 3; j++) /* cam_rgb * (1,1,1) is (1,1,1,1) */ num += cam_rgb[i][j]; if (num > 0.00001) { for (j = 0; j < 3; j++) cam_rgb[i][j] /= num; pre_mul[i] = 1 / num; } else { for (j = 0; j < 3; j++) cam_rgb[i][j] = 0.0; pre_mul[i] = 1.0; } } pseudoinverse(cam_rgb, inverse, colors); for (i = 0; i < 3; i++) for (j = 0; j < colors; j++) _rgb_cam[i][j] = inverse[j][i]; } #ifdef COLORCHECK void CLASS colorcheck() { #define NSQ 24 // Coordinates of the GretagMacbeth ColorChecker squares // width, height, 1st_column, 1st_row int cut[NSQ][4]; // you must set these // ColorChecker Chart under 6500-kelvin illumination static const double gmb_xyY[NSQ][3] = {{0.400, 0.350, 10.1}, // Dark Skin {0.377, 0.345, 35.8}, // Light Skin {0.247, 0.251, 19.3}, // Blue Sky {0.337, 0.422, 13.3}, // Foliage {0.265, 0.240, 24.3}, // Blue Flower {0.261, 0.343, 43.1}, // Bluish Green {0.506, 0.407, 30.1}, // Orange {0.211, 0.175, 12.0}, // Purplish Blue {0.453, 0.306, 19.8}, // Moderate Red {0.285, 0.202, 6.6}, // Purple {0.380, 0.489, 44.3}, // Yellow Green {0.473, 0.438, 43.1}, // Orange Yellow {0.187, 0.129, 6.1}, // Blue {0.305, 0.478, 23.4}, // Green {0.539, 0.313, 12.0}, // Red {0.448, 0.470, 59.1}, // Yellow {0.364, 0.233, 19.8}, // Magenta {0.196, 0.252, 19.8}, // Cyan {0.310, 0.316, 90.0}, // White {0.310, 0.316, 59.1}, // Neutral 8 {0.310, 0.316, 36.2}, // Neutral 6.5 {0.310, 0.316, 19.8}, // Neutral 5 {0.310, 0.316, 9.0}, // Neutral 3.5 {0.310, 0.316, 3.1}}; // Black double gmb_cam[NSQ][4], gmb_xyz[NSQ][3]; double inverse[NSQ][3], cam_xyz[4][3], balance[4], num; int c, i, j, k, sq, row, col, pass, count[4]; memset(gmb_cam, 0, sizeof gmb_cam); for (sq = 0; sq < NSQ; sq++) { FORCC count[c] = 0; for (row = cut[sq][3]; row < cut[sq][3] + cut[sq][1]; row++) for (col = cut[sq][2]; col < cut[sq][2] + cut[sq][0]; col++) { c = FC(row, col); if (c >= colors) c -= 2; gmb_cam[sq][c] += BAYER2(row, col); BAYER2(row, col) = black + (BAYER2(row, col) - black) / 2; count[c]++; } FORCC gmb_cam[sq][c] = gmb_cam[sq][c] / count[c] - black; gmb_xyz[sq][0] = gmb_xyY[sq][2] * gmb_xyY[sq][0] / gmb_xyY[sq][1]; gmb_xyz[sq][1] = gmb_xyY[sq][2]; gmb_xyz[sq][2] = gmb_xyY[sq][2] * (1 - gmb_xyY[sq][0] - gmb_xyY[sq][1]) / gmb_xyY[sq][1]; } pseudoinverse(gmb_xyz, inverse, NSQ); for (pass = 0; pass < 2; pass++) { for (raw_color = i = 0; i < colors; i++) for (j = 0; j < 3; j++) for (cam_xyz[i][j] = k = 0; k < NSQ; k++) cam_xyz[i][j] += gmb_cam[k][i] * inverse[k][j]; cam_xyz_coeff(rgb_cam, cam_xyz); FORCC balance[c] = pre_mul[c] * gmb_cam[20][c]; for (sq = 0; sq < NSQ; sq++) FORCC gmb_cam[sq][c] *= balance[c]; } if (verbose) { printf(" { \"%s %s\", %d,\n\t{", make, model, black); num = 10000 / (cam_xyz[1][0] + cam_xyz[1][1] + cam_xyz[1][2]); FORCC for (j = 0; j < 3; j++) printf("%c%d", (c | j) ? ',' : ' ', (int)(cam_xyz[c][j] * num + 0.5)); puts(" } },"); } #undef NSQ } #endif void CLASS hat_transform(float *temp, float *base, int st, int size, int sc) { int i; for (i = 0; i < sc; i++) temp[i] = 2 * base[st * i] + base[st * (sc - i)] + base[st * (i + sc)]; for (; i + sc < size; i++) temp[i] = 2 * base[st * i] + base[st * (i - sc)] + base[st * (i + sc)]; for (; i < size; i++) temp[i] = 2 * base[st * i] + base[st * (i - sc)] + base[st * (2 * size - 2 - (i + sc))]; } #if !defined(LIBRAW_USE_OPENMP) void CLASS wavelet_denoise() { float *fimg = 0, *temp, thold, mul[2], avg, diff; int scale = 1, size, lev, hpass, lpass, row, col, nc, c, i, wlast, blk[2]; ushort *window[4]; static const float noise[] = {0.8002, 0.2735, 0.1202, 0.0585, 0.0291, 0.0152, 0.0080, 0.0044}; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Wavelet denoising...\n")); #endif while (maximum << scale < 0x10000) scale++; maximum <<= --scale; black <<= scale; FORC4 cblack[c] <<= scale; if ((size = iheight * iwidth) < 0x15550000) fimg = (float *)malloc((size * 3 + iheight + iwidth) * sizeof *fimg); merror(fimg, "wavelet_denoise()"); temp = fimg + size * 3; if ((nc = colors) == 3 && filters) nc++; FORC(nc) { /* denoise R,G1,B,G3 individually */ for (i = 0; i < size; i++) fimg[i] = 256 * sqrt((double)(image[i][c] << scale)); for (hpass = lev = 0; lev < 5; lev++) { lpass = size * ((lev & 1) + 1); for (row = 0; row < iheight; row++) { hat_transform(temp, fimg + hpass + row * iwidth, 1, iwidth, 1 << lev); for (col = 0; col < iwidth; col++) fimg[lpass + row * iwidth + col] = temp[col] * 0.25; } for (col = 0; col < iwidth; col++) { hat_transform(temp, fimg + lpass + col, iwidth, iheight, 1 << lev); for (row = 0; row < iheight; row++) fimg[lpass + row * iwidth + col] = temp[row] * 0.25; } thold = threshold * noise[lev]; for (i = 0; i < size; i++) { fimg[hpass + i] -= fimg[lpass + i]; if (fimg[hpass + i] < -thold) fimg[hpass + i] += thold; else if (fimg[hpass + i] > thold) fimg[hpass + i] -= thold; else fimg[hpass + i] = 0; if (hpass) fimg[i] += fimg[hpass + i]; } hpass = lpass; } for (i = 0; i < size; i++) image[i][c] = CLIP(SQR(fimg[i] + fimg[lpass + i]) / 0x10000); } if (filters && colors == 3) { /* pull G1 and G3 closer together */ for (row = 0; row < 2; row++) { mul[row] = 0.125 * pre_mul[FC(row + 1, 0) | 1] / pre_mul[FC(row, 0) | 1]; blk[row] = cblack[FC(row, 0) | 1]; } for (i = 0; i < 4; i++) window[i] = (ushort *)fimg + width * i; for (wlast = -1, row = 1; row < height - 1; row++) { while (wlast < row + 1) { for (wlast++, i = 0; i < 4; i++) window[(i + 3) & 3] = window[i]; for (col = FC(wlast, 1) & 1; col < width; col += 2) window[2][col] = BAYER(wlast, col); } thold = threshold / 512; for (col = (FC(row, 0) & 1) + 1; col < width - 1; col += 2) { avg = (window[0][col - 1] + window[0][col + 1] + window[2][col - 1] + window[2][col + 1] - blk[~row & 1] * 4) * mul[row & 1] + (window[1][col] + blk[row & 1]) * 0.5; avg = avg < 0 ? 0 : sqrt(avg); diff = sqrt((double)BAYER(row, col)) - avg; if (diff < -thold) diff += thold; else if (diff > thold) diff -= thold; else diff = 0; BAYER(row, col) = CLIP(SQR(avg + diff) + 0.5); } } } free(fimg); } #else /* LIBRAW_USE_OPENMP */ void CLASS wavelet_denoise() { float *fimg = 0, *temp, thold, mul[2], avg, diff; int scale = 1, size, lev, hpass, lpass, row, col, nc, c, i, wlast, blk[2]; ushort *window[4]; static const float noise[] = {0.8002, 0.2735, 0.1202, 0.0585, 0.0291, 0.0152, 0.0080, 0.0044}; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Wavelet denoising...\n")); #endif while (maximum << scale < 0x10000) scale++; maximum <<= --scale; black <<= scale; FORC4 cblack[c] <<= scale; if ((size = iheight * iwidth) < 0x15550000) fimg = (float *)malloc((size * 3 + iheight + iwidth) * sizeof *fimg); merror(fimg, "wavelet_denoise()"); temp = fimg + size * 3; if ((nc = colors) == 3 && filters) nc++; #ifdef LIBRAW_LIBRARY_BUILD #pragma omp parallel default(shared) private(i, col, row, thold, lev, lpass, hpass, temp, c) firstprivate(scale, size) #endif { temp = (float *)malloc((iheight + iwidth) * sizeof *fimg); FORC(nc) { /* denoise R,G1,B,G3 individually */ #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (i = 0; i < size; i++) fimg[i] = 256 * sqrt((double)(image[i][c] << scale)); for (hpass = lev = 0; lev < 5; lev++) { lpass = size * ((lev & 1) + 1); #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (row = 0; row < iheight; row++) { hat_transform(temp, fimg + hpass + row * iwidth, 1, iwidth, 1 << lev); for (col = 0; col < iwidth; col++) fimg[lpass + row * iwidth + col] = temp[col] * 0.25; } #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (col = 0; col < iwidth; col++) { hat_transform(temp, fimg + lpass + col, iwidth, iheight, 1 << lev); for (row = 0; row < iheight; row++) fimg[lpass + row * iwidth + col] = temp[row] * 0.25; } thold = threshold * noise[lev]; #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (i = 0; i < size; i++) { fimg[hpass + i] -= fimg[lpass + i]; if (fimg[hpass + i] < -thold) fimg[hpass + i] += thold; else if (fimg[hpass + i] > thold) fimg[hpass + i] -= thold; else fimg[hpass + i] = 0; if (hpass) fimg[i] += fimg[hpass + i]; } hpass = lpass; } #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (i = 0; i < size; i++) image[i][c] = CLIP(SQR(fimg[i] + fimg[lpass + i]) / 0x10000); } free(temp); } /* end omp parallel */ /* the following loops are hard to parallize, no idea yes, * problem is wlast which is carrying dependency * second part should be easyer, but did not yet get it right. */ if (filters && colors == 3) { /* pull G1 and G3 closer together */ for (row = 0; row < 2; row++) { mul[row] = 0.125 * pre_mul[FC(row + 1, 0) | 1] / pre_mul[FC(row, 0) | 1]; blk[row] = cblack[FC(row, 0) | 1]; } for (i = 0; i < 4; i++) window[i] = (ushort *)fimg + width * i; for (wlast = -1, row = 1; row < height - 1; row++) { while (wlast < row + 1) { for (wlast++, i = 0; i < 4; i++) window[(i + 3) & 3] = window[i]; for (col = FC(wlast, 1) & 1; col < width; col += 2) window[2][col] = BAYER(wlast, col); } thold = threshold / 512; for (col = (FC(row, 0) & 1) + 1; col < width - 1; col += 2) { avg = (window[0][col - 1] + window[0][col + 1] + window[2][col - 1] + window[2][col + 1] - blk[~row & 1] * 4) * mul[row & 1] + (window[1][col] + blk[row & 1]) * 0.5; avg = avg < 0 ? 0 : sqrt(avg); diff = sqrt((double)BAYER(row, col)) - avg; if (diff < -thold) diff += thold; else if (diff > thold) diff -= thold; else diff = 0; BAYER(row, col) = CLIP(SQR(avg + diff) + 0.5); } } } free(fimg); } #endif // green equilibration void CLASS green_matching() { int i, j; double m1, m2, c1, c2; int o1_1, o1_2, o1_3, o1_4; int o2_1, o2_2, o2_3, o2_4; ushort(*img)[4]; const int margin = 3; int oj = 2, oi = 2; float f; const float thr = 0.01f; if (half_size || shrink) return; if (FC(oj, oi) != 3) oj++; if (FC(oj, oi) != 3) oi++; if (FC(oj, oi) != 3) oj--; img = (ushort(*)[4])calloc(height * width, sizeof *image); merror(img, "green_matching()"); memcpy(img, image, height * width * sizeof *image); for (j = oj; j < height - margin; j += 2) for (i = oi; i < width - margin; i += 2) { o1_1 = img[(j - 1) * width + i - 1][1]; o1_2 = img[(j - 1) * width + i + 1][1]; o1_3 = img[(j + 1) * width + i - 1][1]; o1_4 = img[(j + 1) * width + i + 1][1]; o2_1 = img[(j - 2) * width + i][3]; o2_2 = img[(j + 2) * width + i][3]; o2_3 = img[j * width + i - 2][3]; o2_4 = img[j * width + i + 2][3]; m1 = (o1_1 + o1_2 + o1_3 + o1_4) / 4.0; m2 = (o2_1 + o2_2 + o2_3 + o2_4) / 4.0; c1 = (abs(o1_1 - o1_2) + abs(o1_1 - o1_3) + abs(o1_1 - o1_4) + abs(o1_2 - o1_3) + abs(o1_3 - o1_4) + abs(o1_2 - o1_4)) / 6.0; c2 = (abs(o2_1 - o2_2) + abs(o2_1 - o2_3) + abs(o2_1 - o2_4) + abs(o2_2 - o2_3) + abs(o2_3 - o2_4) + abs(o2_2 - o2_4)) / 6.0; if ((img[j * width + i][3] < maximum * 0.95) && (c1 < maximum * thr) && (c2 < maximum * thr)) { f = image[j * width + i][3] * m1 / m2; image[j * width + i][3] = f > 0xffff ? 0xffff : f; } } free(img); } void CLASS scale_colors() { unsigned bottom, right, size, row, col, ur, uc, i, x, y, c, sum[8]; int val, dark, sat; double dsum[8], dmin, dmax; float scale_mul[4], fr, fc; ushort *img = 0, *pix; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_SCALE_COLORS, 0, 2); #endif if (user_mul[0]) memcpy(pre_mul, user_mul, sizeof pre_mul); if (use_auto_wb || (use_camera_wb && cam_mul[0] == -1)) { memset(dsum, 0, sizeof dsum); bottom = MIN(greybox[1] + greybox[3], height); right = MIN(greybox[0] + greybox[2], width); for (row = greybox[1]; row < bottom; row += 8) for (col = greybox[0]; col < right; col += 8) { memset(sum, 0, sizeof sum); for (y = row; y < row + 8 && y < bottom; y++) for (x = col; x < col + 8 && x < right; x++) FORC4 { if (filters) { c = fcol(y, x); val = BAYER2(y, x); } else val = image[y * width + x][c]; if (val > maximum - 25) goto skip_block; if ((val -= cblack[c]) < 0) val = 0; sum[c] += val; sum[c + 4]++; if (filters) break; } FORC(8) dsum[c] += sum[c]; skip_block:; } FORC4 if (dsum[c]) pre_mul[c] = dsum[c + 4] / dsum[c]; } if (use_camera_wb && cam_mul[0] != -1) { memset(sum, 0, sizeof sum); for (row = 0; row < 8; row++) for (col = 0; col < 8; col++) { c = FC(row, col); if ((val = white[row][col] - cblack[c]) > 0) sum[c] += val; sum[c + 4]++; } #ifdef LIBRAW_LIBRARY_BUILD if (load_raw == &LibRaw::nikon_load_sraw) { // Nikon sRAW: camera WB already applied: pre_mul[0] = pre_mul[1] = pre_mul[2] = pre_mul[3] = 1.0; } else #endif if (sum[0] && sum[1] && sum[2] && sum[3]) FORC4 pre_mul[c] = (float)sum[c + 4] / sum[c]; else if (cam_mul[0] && cam_mul[2]) memcpy(pre_mul, cam_mul, sizeof pre_mul); else { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_BAD_CAMERA_WB; #endif #ifdef DCRAW_VERBOSE fprintf(stderr, _("%s: Cannot use camera white balance.\n"), ifname); #endif } } #ifdef LIBRAW_LIBRARY_BUILD // Nikon sRAW, daylight if (load_raw == &LibRaw::nikon_load_sraw && !use_camera_wb && !use_auto_wb && cam_mul[0] > 0.001f && cam_mul[1] > 0.001f && cam_mul[2] > 0.001f) { for (c = 0; c < 3; c++) pre_mul[c] /= cam_mul[c]; } #endif if (pre_mul[1] == 0) pre_mul[1] = 1; if (pre_mul[3] == 0) pre_mul[3] = colors < 4 ? pre_mul[1] : 1; dark = black; sat = maximum; if (threshold) wavelet_denoise(); maximum -= black; for (dmin = DBL_MAX, dmax = c = 0; c < 4; c++) { if (dmin > pre_mul[c]) dmin = pre_mul[c]; if (dmax < pre_mul[c]) dmax = pre_mul[c]; } if (!highlight) dmax = dmin; FORC4 scale_mul[c] = (pre_mul[c] /= dmax) * 65535.0 / maximum; #ifdef DCRAW_VERBOSE if (verbose) { fprintf(stderr, _("Scaling with darkness %d, saturation %d, and\nmultipliers"), dark, sat); FORC4 fprintf(stderr, " %f", pre_mul[c]); fputc('\n', stderr); } #endif if (filters > 1000 && (cblack[4] + 1) / 2 == 1 && (cblack[5] + 1) / 2 == 1) { FORC4 cblack[FC(c / 2, c % 2)] += cblack[6 + c / 2 % cblack[4] * cblack[5] + c % 2 % cblack[5]]; cblack[4] = cblack[5] = 0; } size = iheight * iwidth; #ifdef LIBRAW_LIBRARY_BUILD scale_colors_loop(scale_mul); #else for (i = 0; i < size * 4; i++) { if (!(val = ((ushort *)image)[i])) continue; if (cblack[4] && cblack[5]) val -= cblack[6 + i / 4 / iwidth % cblack[4] * cblack[5] + i / 4 % iwidth % cblack[5]]; val -= cblack[i & 3]; val *= scale_mul[i & 3]; ((ushort *)image)[i] = CLIP(val); } #endif if ((aber[0] != 1 || aber[2] != 1) && colors == 3) { #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Correcting chromatic aberration...\n")); #endif for (c = 0; c < 4; c += 2) { if (aber[c] == 1) continue; img = (ushort *)malloc(size * sizeof *img); merror(img, "scale_colors()"); for (i = 0; i < size; i++) img[i] = image[i][c]; for (row = 0; row < iheight; row++) { ur = fr = (row - iheight * 0.5) * aber[c] + iheight * 0.5; if (ur > iheight - 2) continue; fr -= ur; for (col = 0; col < iwidth; col++) { uc = fc = (col - iwidth * 0.5) * aber[c] + iwidth * 0.5; if (uc > iwidth - 2) continue; fc -= uc; pix = img + ur * iwidth + uc; image[row * iwidth + col][c] = (pix[0] * (1 - fc) + pix[1] * fc) * (1 - fr) + (pix[iwidth] * (1 - fc) + pix[iwidth + 1] * fc) * fr; } } free(img); } } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_SCALE_COLORS, 1, 2); #endif } void CLASS pre_interpolate() { ushort(*img)[4]; int row, col, c; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_PRE_INTERPOLATE, 0, 2); #endif if (shrink) { if (half_size) { height = iheight; width = iwidth; if (filters == 9) { for (row = 0; row < 3; row++) for (col = 1; col < 4; col++) if (!(image[row * width + col][0] | image[row * width + col][2])) goto break2; break2: for (; row < height; row += 3) for (col = (col - 1) % 3 + 1; col < width - 1; col += 3) { img = image + row * width + col; for (c = 0; c < 3; c += 2) img[0][c] = (img[-1][c] + img[1][c]) >> 1; } } } else { img = (ushort(*)[4])calloc(height, width * sizeof *img); merror(img, "pre_interpolate()"); for (row = 0; row < height; row++) for (col = 0; col < width; col++) { c = fcol(row, col); img[row * width + col][c] = image[(row >> 1) * iwidth + (col >> 1)][c]; } free(image); image = img; shrink = 0; } } if (filters > 1000 && colors == 3) { mix_green = four_color_rgb ^ half_size; if (four_color_rgb | half_size) colors++; else { for (row = FC(1, 0) >> 1; row < height; row += 2) for (col = FC(row, 1) & 1; col < width; col += 2) image[row * width + col][1] = image[row * width + col][3]; filters &= ~((filters & 0x55555555) << 1); } } if (half_size) filters = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_PRE_INTERPOLATE, 1, 2); #endif } void CLASS border_interpolate(int border) { unsigned row, col, y, x, f, c, sum[8]; for (row = 0; row < height; row++) for (col = 0; col < width; col++) { if (col == border && row >= border && row < height - border) col = width - border; memset(sum, 0, sizeof sum); for (y = row - 1; y != row + 2; y++) for (x = col - 1; x != col + 2; x++) if (y < height && x < width) { f = fcol(y, x); sum[f] += image[y * width + x][f]; sum[f + 4]++; } f = fcol(row, col); FORCC if (c != f && sum[c + 4]) image[row * width + col][c] = sum[c] / sum[c + 4]; } } void CLASS lin_interpolate_loop(int code[16][16][32], int size) { int row; for (row = 1; row < height - 1; row++) { int col, *ip; ushort *pix; for (col = 1; col < width - 1; col++) { int i; int sum[4]; pix = image[row * width + col]; ip = code[row % size][col % size]; memset(sum, 0, sizeof sum); for (i = *ip++; i--; ip += 3) sum[ip[2]] += pix[ip[0]] << ip[1]; for (i = colors; --i; ip += 2) pix[ip[0]] = sum[ip[0]] * ip[1] >> 8; } } } void CLASS lin_interpolate() { int code[16][16][32], size = 16, *ip, sum[4]; int f, c, x, y, row, col, shift, color; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Bilinear interpolation...\n")); #endif #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 0, 3); #endif if (filters == 9) size = 6; border_interpolate(1); for (row = 0; row < size; row++) for (col = 0; col < size; col++) { ip = code[row][col] + 1; f = fcol(row, col); memset(sum, 0, sizeof sum); for (y = -1; y <= 1; y++) for (x = -1; x <= 1; x++) { shift = (y == 0) + (x == 0); color = fcol(row + y, col + x); if (color == f) continue; *ip++ = (width * y + x) * 4 + color; *ip++ = shift; *ip++ = color; sum[color] += 1 << shift; } code[row][col][0] = (ip - code[row][col]) / 3; FORCC if (c != f) { *ip++ = c; *ip++ = sum[c] > 0 ? 256 / sum[c] : 0; } } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 1, 3); #endif lin_interpolate_loop(code, size); #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 2, 3); #endif } /* This algorithm is officially called: "Interpolation using a Threshold-based variable number of gradients" described in http://scien.stanford.edu/pages/labsite/1999/psych221/projects/99/tingchen/algodep/vargra.html I've extended the basic idea to work with non-Bayer filter arrays. Gradients are numbered clockwise from NW=0 to W=7. */ void CLASS vng_interpolate() { static const signed char *cp, terms[] = {-2, -2, +0, -1, 0, 0x01, -2, -2, +0, +0, 1, 0x01, -2, -1, -1, +0, 0, 0x01, -2, -1, +0, -1, 0, 0x02, -2, -1, +0, +0, 0, 0x03, -2, -1, +0, +1, 1, 0x01, -2, +0, +0, -1, 0, 0x06, -2, +0, +0, +0, 1, 0x02, -2, +0, +0, +1, 0, 0x03, -2, +1, -1, +0, 0, 0x04, -2, +1, +0, -1, 1, 0x04, -2, +1, +0, +0, 0, 0x06, -2, +1, +0, +1, 0, 0x02, -2, +2, +0, +0, 1, 0x04, -2, +2, +0, +1, 0, 0x04, -1, -2, -1, +0, 0, -128, -1, -2, +0, -1, 0, 0x01, -1, -2, +1, -1, 0, 0x01, -1, -2, +1, +0, 1, 0x01, -1, -1, -1, +1, 0, -120, -1, -1, +1, -2, 0, 0x40, -1, -1, +1, -1, 0, 0x22, -1, -1, +1, +0, 0, 0x33, -1, -1, +1, +1, 1, 0x11, -1, +0, -1, +2, 0, 0x08, -1, +0, +0, -1, 0, 0x44, -1, +0, +0, +1, 0, 0x11, -1, +0, +1, -2, 1, 0x40, -1, +0, +1, -1, 0, 0x66, -1, +0, +1, +0, 1, 0x22, -1, +0, +1, +1, 0, 0x33, -1, +0, +1, +2, 1, 0x10, -1, +1, +1, -1, 1, 0x44, -1, +1, +1, +0, 0, 0x66, -1, +1, +1, +1, 0, 0x22, -1, +1, +1, +2, 0, 0x10, -1, +2, +0, +1, 0, 0x04, -1, +2, +1, +0, 1, 0x04, -1, +2, +1, +1, 0, 0x04, +0, -2, +0, +0, 1, -128, +0, -1, +0, +1, 1, -120, +0, -1, +1, -2, 0, 0x40, +0, -1, +1, +0, 0, 0x11, +0, -1, +2, -2, 0, 0x40, +0, -1, +2, -1, 0, 0x20, +0, -1, +2, +0, 0, 0x30, +0, -1, +2, +1, 1, 0x10, +0, +0, +0, +2, 1, 0x08, +0, +0, +2, -2, 1, 0x40, +0, +0, +2, -1, 0, 0x60, +0, +0, +2, +0, 1, 0x20, +0, +0, +2, +1, 0, 0x30, +0, +0, +2, +2, 1, 0x10, +0, +1, +1, +0, 0, 0x44, +0, +1, +1, +2, 0, 0x10, +0, +1, +2, -1, 1, 0x40, +0, +1, +2, +0, 0, 0x60, +0, +1, +2, +1, 0, 0x20, +0, +1, +2, +2, 0, 0x10, +1, -2, +1, +0, 0, -128, +1, -1, +1, +1, 0, -120, +1, +0, +1, +2, 0, 0x08, +1, +0, +2, -1, 0, 0x40, +1, +0, +2, +1, 0, 0x10}, chood[] = {-1, -1, -1, 0, -1, +1, 0, +1, +1, +1, +1, 0, +1, -1, 0, -1}; ushort(*brow[5])[4], *pix; int prow = 8, pcol = 2, *ip, *code[16][16], gval[8], gmin, gmax, sum[4]; int row, col, x, y, x1, x2, y1, y2, t, weight, grads, color, diag; int g, diff, thold, num, c; lin_interpolate(); #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("VNG interpolation...\n")); #endif if (filters == 1) prow = pcol = 16; if (filters == 9) prow = pcol = 6; ip = (int *)calloc(prow * pcol, 1280); merror(ip, "vng_interpolate()"); for (row = 0; row < prow; row++) /* Precalculate for VNG */ for (col = 0; col < pcol; col++) { code[row][col] = ip; for (cp = terms, t = 0; t < 64; t++) { y1 = *cp++; x1 = *cp++; y2 = *cp++; x2 = *cp++; weight = *cp++; grads = *cp++; color = fcol(row + y1, col + x1); if (fcol(row + y2, col + x2) != color) continue; diag = (fcol(row, col + 1) == color && fcol(row + 1, col) == color) ? 2 : 1; if (abs(y1 - y2) == diag && abs(x1 - x2) == diag) continue; *ip++ = (y1 * width + x1) * 4 + color; *ip++ = (y2 * width + x2) * 4 + color; *ip++ = weight; for (g = 0; g < 8; g++) if (grads & 1 << g) *ip++ = g; *ip++ = -1; } *ip++ = INT_MAX; for (cp = chood, g = 0; g < 8; g++) { y = *cp++; x = *cp++; *ip++ = (y * width + x) * 4; color = fcol(row, col); if (fcol(row + y, col + x) != color && fcol(row + y * 2, col + x * 2) == color) *ip++ = (y * width + x) * 8 + color; else *ip++ = 0; } } brow[4] = (ushort(*)[4])calloc(width * 3, sizeof **brow); merror(brow[4], "vng_interpolate()"); for (row = 0; row < 3; row++) brow[row] = brow[4] + row * width; for (row = 2; row < height - 2; row++) { /* Do VNG interpolation */ #ifdef LIBRAW_LIBRARY_BUILD if (!((row - 2) % 256)) RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, (row - 2) / 256 + 1, ((height - 3) / 256) + 1); #endif for (col = 2; col < width - 2; col++) { pix = image[row * width + col]; ip = code[row % prow][col % pcol]; memset(gval, 0, sizeof gval); while ((g = ip[0]) != INT_MAX) { /* Calculate gradients */ diff = ABS(pix[g] - pix[ip[1]]) << ip[2]; gval[ip[3]] += diff; ip += 5; if ((g = ip[-1]) == -1) continue; gval[g] += diff; while ((g = *ip++) != -1) gval[g] += diff; } ip++; gmin = gmax = gval[0]; /* Choose a threshold */ for (g = 1; g < 8; g++) { if (gmin > gval[g]) gmin = gval[g]; if (gmax < gval[g]) gmax = gval[g]; } if (gmax == 0) { memcpy(brow[2][col], pix, sizeof *image); continue; } thold = gmin + (gmax >> 1); memset(sum, 0, sizeof sum); color = fcol(row, col); for (num = g = 0; g < 8; g++, ip += 2) { /* Average the neighbors */ if (gval[g] <= thold) { FORCC if (c == color && ip[1]) sum[c] += (pix[c] + pix[ip[1]]) >> 1; else sum[c] += pix[ip[0] + c]; num++; } } FORCC { /* Save to buffer */ t = pix[color]; if (c != color) t += (sum[c] - sum[color]) / num; brow[2][col][c] = CLIP(t); } } if (row > 3) /* Write buffer to image */ memcpy(image[(row - 2) * width + 2], brow[0] + 2, (width - 4) * sizeof *image); for (g = 0; g < 4; g++) brow[(g - 1) & 3] = brow[g]; } memcpy(image[(row - 2) * width + 2], brow[0] + 2, (width - 4) * sizeof *image); memcpy(image[(row - 1) * width + 2], brow[1] + 2, (width - 4) * sizeof *image); free(brow[4]); free(code[0][0]); } /* Patterned Pixel Grouping Interpolation by Alain Desbiolles */ void CLASS ppg_interpolate() { int dir[5] = {1, width, -1, -width, 1}; int row, col, diff[2], guess[2], c, d, i; ushort(*pix)[4]; border_interpolate(3); #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("PPG interpolation...\n")); #endif /* Fill in the green layer with gradients and pattern recognition: */ #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 0, 3); #ifdef LIBRAW_USE_OPENMP #pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static) #endif #endif for (row = 3; row < height - 3; row++) for (col = 3 + (FC(row, 3) & 1), c = FC(row, col); col < width - 3; col += 2) { pix = image + row * width + col; for (i = 0; (d = dir[i]) > 0; i++) { guess[i] = (pix[-d][1] + pix[0][c] + pix[d][1]) * 2 - pix[-2 * d][c] - pix[2 * d][c]; diff[i] = (ABS(pix[-2 * d][c] - pix[0][c]) + ABS(pix[2 * d][c] - pix[0][c]) + ABS(pix[-d][1] - pix[d][1])) * 3 + (ABS(pix[3 * d][1] - pix[d][1]) + ABS(pix[-3 * d][1] - pix[-d][1])) * 2; } d = dir[i = diff[0] > diff[1]]; pix[0][1] = ULIM(guess[i] >> 2, pix[d][1], pix[-d][1]); } /* Calculate red and blue for each green pixel: */ #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 1, 3); #ifdef LIBRAW_USE_OPENMP #pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static) #endif #endif for (row = 1; row < height - 1; row++) for (col = 1 + (FC(row, 2) & 1), c = FC(row, col + 1); col < width - 1; col += 2) { pix = image + row * width + col; for (i = 0; (d = dir[i]) > 0; c = 2 - c, i++) pix[0][c] = CLIP((pix[-d][c] + pix[d][c] + 2 * pix[0][1] - pix[-d][1] - pix[d][1]) >> 1); } /* Calculate blue for red pixels and vice versa: */ #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 2, 3); #ifdef LIBRAW_USE_OPENMP #pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static) #endif #endif for (row = 1; row < height - 1; row++) for (col = 1 + (FC(row, 1) & 1), c = 2 - FC(row, col); col < width - 1; col += 2) { pix = image + row * width + col; for (i = 0; (d = dir[i] + dir[i + 1]) > 0; i++) { diff[i] = ABS(pix[-d][c] - pix[d][c]) + ABS(pix[-d][1] - pix[0][1]) + ABS(pix[d][1] - pix[0][1]); guess[i] = pix[-d][c] + pix[d][c] + 2 * pix[0][1] - pix[-d][1] - pix[d][1]; } if (diff[0] != diff[1]) pix[0][c] = CLIP(guess[diff[0] > diff[1]] >> 1); else pix[0][c] = CLIP((guess[0] + guess[1]) >> 2); } } void CLASS cielab(ushort rgb[3], short lab[3]) { int c, i, j, k; float r, xyz[3]; #ifdef LIBRAW_NOTHREADS static float cbrt[0x10000], xyz_cam[3][4]; #else #define cbrt tls->ahd_data.cbrt #define xyz_cam tls->ahd_data.xyz_cam #endif if (!rgb) { #ifndef LIBRAW_NOTHREADS if (cbrt[0] < -1.0f) #endif for (i = 0; i < 0x10000; i++) { r = i / 65535.0; cbrt[i] = r > 0.008856 ? pow(r, 1.f / 3.0f) : 7.787f * r + 16.f / 116.0f; } for (i = 0; i < 3; i++) for (j = 0; j < colors; j++) for (xyz_cam[i][j] = k = 0; k < 3; k++) xyz_cam[i][j] += xyz_rgb[i][k] * rgb_cam[k][j] / d65_white[i]; return; } xyz[0] = xyz[1] = xyz[2] = 0.5; FORCC { xyz[0] += xyz_cam[0][c] * rgb[c]; xyz[1] += xyz_cam[1][c] * rgb[c]; xyz[2] += xyz_cam[2][c] * rgb[c]; } xyz[0] = cbrt[CLIP((int)xyz[0])]; xyz[1] = cbrt[CLIP((int)xyz[1])]; xyz[2] = cbrt[CLIP((int)xyz[2])]; lab[0] = 64 * (116 * xyz[1] - 16); lab[1] = 64 * 500 * (xyz[0] - xyz[1]); lab[2] = 64 * 200 * (xyz[1] - xyz[2]); #ifndef LIBRAW_NOTHREADS #undef cbrt #undef xyz_cam #endif } #define TS 512 /* Tile Size */ #define fcol(row, col) xtrans[(row + 6) % 6][(col + 6) % 6] /* Frank Markesteijn's algorithm for Fuji X-Trans sensors */ void CLASS xtrans_interpolate(int passes) { int c, d, f, g, h, i, v, ng, row, col, top, left, mrow, mcol; #ifdef LIBRAW_LIBRARY_BUILD int cstat[4]={0,0,0,0}; #endif int val, ndir, pass, hm[8], avg[4], color[3][8]; static const short orth[12] = {1, 0, 0, 1, -1, 0, 0, -1, 1, 0, 0, 1}, patt[2][16] = {{0, 1, 0, -1, 2, 0, -1, 0, 1, 1, 1, -1, 0, 0, 0, 0}, {0, 1, 0, -2, 1, 0, -2, 0, 1, 1, -2, -2, 1, -1, -1, 1}}, dir[4] = {1, TS, TS + 1, TS - 1}; short allhex[3][3][2][8], *hex; ushort min, max, sgrow, sgcol; ushort(*rgb)[TS][TS][3], (*rix)[3], (*pix)[4]; short(*lab)[TS][3], (*lix)[3]; float(*drv)[TS][TS], diff[6], tr; char(*homo)[TS][TS], *buffer; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("%d-pass X-Trans interpolation...\n"), passes); #endif #ifdef LIBRAW_LIBRARY_BUILD if(width < TS || height < TS) throw LIBRAW_EXCEPTION_IO_CORRUPT; // too small image /* Check against right pattern */ for (row = 0; row < 6; row++) for (col = 0; col < 6; col++) cstat[fcol(row,col)]++; if(cstat[0] < 6 || cstat[0]>10 || cstat[1]< 16 || cstat[1]>24 || cstat[2]< 6 || cstat[2]>10 || cstat[3]) throw LIBRAW_EXCEPTION_IO_CORRUPT; // Init allhex table to unreasonable values for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++) for(int k = 0; k < 2; k++) for(int l = 0; l < 8; l++) allhex[i][j][k][l]=32700; #endif cielab(0, 0); ndir = 4 << (passes > 1); buffer = (char *)malloc(TS * TS * (ndir * 11 + 6)); merror(buffer, "xtrans_interpolate()"); rgb = (ushort(*)[TS][TS][3])buffer; lab = (short(*)[TS][3])(buffer + TS * TS * (ndir * 6)); drv = (float(*)[TS][TS])(buffer + TS * TS * (ndir * 6 + 6)); homo = (char(*)[TS][TS])(buffer + TS * TS * (ndir * 10 + 6)); int minv=0,maxv=0,minh=0,maxh=0; /* Map a green hexagon around each non-green pixel and vice versa: */ for (row = 0; row < 3; row++) for (col = 0; col < 3; col++) for (ng = d = 0; d < 10; d += 2) { g = fcol(row, col) == 1; if (fcol(row + orth[d], col + orth[d + 2]) == 1) ng = 0; else ng++; if (ng == 4) { sgrow = row; sgcol = col; } if (ng == g + 1) FORC(8) { v = orth[d] * patt[g][c * 2] + orth[d + 1] * patt[g][c * 2 + 1]; h = orth[d + 2] * patt[g][c * 2] + orth[d + 3] * patt[g][c * 2 + 1]; minv=MIN(v,minv); maxv=MAX(v,maxv); minh=MIN(v,minh); maxh=MAX(v,maxh); allhex[row][col][0][c ^ (g * 2 & d)] = h + v * width; allhex[row][col][1][c ^ (g * 2 & d)] = h + v * TS; } } #ifdef LIBRAW_LIBRARY_BUILD // Check allhex table initialization for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++) for(int k = 0; k < 2; k++) for(int l = 0; l < 8; l++) if(allhex[i][j][k][l]>maxh+maxv*width+1 || allhex[i][j][k][l]<minh+minv*width-1) throw LIBRAW_EXCEPTION_IO_CORRUPT; int retrycount = 0; #endif /* Set green1 and green3 to the minimum and maximum allowed values: */ for (row = 2; row < height - 2; row++) for (min = ~(max = 0), col = 2; col < width - 2; col++) { if (fcol(row, col) == 1 && (min = ~(max = 0))) continue; pix = image + row * width + col; hex = allhex[row % 3][col % 3][0]; if (!max) FORC(6) { val = pix[hex[c]][1]; if (min > val) min = val; if (max < val) max = val; } pix[0][1] = min; pix[0][3] = max; switch ((row - sgrow) % 3) { case 1: if (row < height - 3) { row++; col--; } break; case 2: if ((min = ~(max = 0)) && (col += 2) < width - 3 && row > 2) { row--; #ifdef LIBRAW_LIBRARY_BUILD if(retrycount++ > width*height) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif } } } for (top = 3; top < height - 19; top += TS - 16) for (left = 3; left < width - 19; left += TS - 16) { mrow = MIN(top + TS, height - 3); mcol = MIN(left + TS, width - 3); for (row = top; row < mrow; row++) for (col = left; col < mcol; col++) memcpy(rgb[0][row - top][col - left], image[row * width + col], 6); FORC3 memcpy(rgb[c + 1], rgb[0], sizeof *rgb); /* Interpolate green horizontally, vertically, and along both diagonals: */ for (row = top; row < mrow; row++) for (col = left; col < mcol; col++) { if ((f = fcol(row, col)) == 1) continue; pix = image + row * width + col; hex = allhex[row % 3][col % 3][0]; color[1][0] = 174 * (pix[hex[1]][1] + pix[hex[0]][1]) - 46 * (pix[2 * hex[1]][1] + pix[2 * hex[0]][1]); color[1][1] = 223 * pix[hex[3]][1] + pix[hex[2]][1] * 33 + 92 * (pix[0][f] - pix[-hex[2]][f]); FORC(2) color[1][2 + c] = 164 * pix[hex[4 + c]][1] + 92 * pix[-2 * hex[4 + c]][1] + 33 * (2 * pix[0][f] - pix[3 * hex[4 + c]][f] - pix[-3 * hex[4 + c]][f]); FORC4 rgb[c ^ !((row - sgrow) % 3)][row - top][col - left][1] = LIM(color[1][c] >> 8, pix[0][1], pix[0][3]); } for (pass = 0; pass < passes; pass++) { if (pass == 1) memcpy(rgb += 4, buffer, 4 * sizeof *rgb); /* Recalculate green from interpolated values of closer pixels: */ if (pass) { for (row = top + 2; row < mrow - 2; row++) for (col = left + 2; col < mcol - 2; col++) { if ((f = fcol(row, col)) == 1) continue; pix = image + row * width + col; hex = allhex[row % 3][col % 3][1]; for (d = 3; d < 6; d++) { rix = &rgb[(d - 2) ^ !((row - sgrow) % 3)][row - top][col - left]; val = rix[-2 * hex[d]][1] + 2 * rix[hex[d]][1] - rix[-2 * hex[d]][f] - 2 * rix[hex[d]][f] + 3 * rix[0][f]; rix[0][1] = LIM(val / 3, pix[0][1], pix[0][3]); } } } /* Interpolate red and blue values for solitary green pixels: */ for (row = (top - sgrow + 4) / 3 * 3 + sgrow; row < mrow - 2; row += 3) for (col = (left - sgcol + 4) / 3 * 3 + sgcol; col < mcol - 2; col += 3) { rix = &rgb[0][row - top][col - left]; h = fcol(row, col + 1); memset(diff, 0, sizeof diff); for (i = 1, d = 0; d < 6; d++, i ^= TS ^ 1, h ^= 2) { for (c = 0; c < 2; c++, h ^= 2) { g = 2 * rix[0][1] - rix[i << c][1] - rix[-i << c][1]; color[h][d] = g + rix[i << c][h] + rix[-i << c][h]; if (d > 1) diff[d] += SQR(rix[i << c][1] - rix[-i << c][1] - rix[i << c][h] + rix[-i << c][h]) + SQR(g); } if (d > 1 && (d & 1)) if (diff[d - 1] < diff[d]) FORC(2) color[c * 2][d] = color[c * 2][d - 1]; if (d < 2 || (d & 1)) { FORC(2) rix[0][c * 2] = CLIP(color[c * 2][d] / 2); rix += TS * TS; } } } /* Interpolate red for blue pixels and vice versa: */ for (row = top + 3; row < mrow - 3; row++) for (col = left + 3; col < mcol - 3; col++) { if ((f = 2 - fcol(row, col)) == 1) continue; rix = &rgb[0][row - top][col - left]; c = (row - sgrow) % 3 ? TS : 1; h = 3 * (c ^ TS ^ 1); for (d = 0; d < 4; d++, rix += TS * TS) { i = d > 1 || ((d ^ c) & 1) || ((ABS(rix[0][1] - rix[c][1]) + ABS(rix[0][1] - rix[-c][1])) < 2 * (ABS(rix[0][1] - rix[h][1]) + ABS(rix[0][1] - rix[-h][1]))) ? c : h; rix[0][f] = CLIP((rix[i][f] + rix[-i][f] + 2 * rix[0][1] - rix[i][1] - rix[-i][1]) / 2); } } /* Fill in red and blue for 2x2 blocks of green: */ for (row = top + 2; row < mrow - 2; row++) if ((row - sgrow) % 3) for (col = left + 2; col < mcol - 2; col++) if ((col - sgcol) % 3) { rix = &rgb[0][row - top][col - left]; hex = allhex[row % 3][col % 3][1]; for (d = 0; d < ndir; d += 2, rix += TS * TS) if (hex[d] + hex[d + 1]) { g = 3 * rix[0][1] - 2 * rix[hex[d]][1] - rix[hex[d + 1]][1]; for (c = 0; c < 4; c += 2) rix[0][c] = CLIP((g + 2 * rix[hex[d]][c] + rix[hex[d + 1]][c]) / 3); } else { g = 2 * rix[0][1] - rix[hex[d]][1] - rix[hex[d + 1]][1]; for (c = 0; c < 4; c += 2) rix[0][c] = CLIP((g + rix[hex[d]][c] + rix[hex[d + 1]][c]) / 2); } } } rgb = (ushort(*)[TS][TS][3])buffer; mrow -= top; mcol -= left; /* Convert to CIELab and differentiate in all directions: */ for (d = 0; d < ndir; d++) { for (row = 2; row < mrow - 2; row++) for (col = 2; col < mcol - 2; col++) cielab(rgb[d][row][col], lab[row][col]); for (f = dir[d & 3], row = 3; row < mrow - 3; row++) for (col = 3; col < mcol - 3; col++) { lix = &lab[row][col]; g = 2 * lix[0][0] - lix[f][0] - lix[-f][0]; drv[d][row][col] = SQR(g) + SQR((2 * lix[0][1] - lix[f][1] - lix[-f][1] + g * 500 / 232)) + SQR((2 * lix[0][2] - lix[f][2] - lix[-f][2] - g * 500 / 580)); } } /* Build homogeneity maps from the derivatives: */ memset(homo, 0, ndir * TS * TS); for (row = 4; row < mrow - 4; row++) for (col = 4; col < mcol - 4; col++) { for (tr = FLT_MAX, d = 0; d < ndir; d++) if (tr > drv[d][row][col]) tr = drv[d][row][col]; tr *= 8; for (d = 0; d < ndir; d++) for (v = -1; v <= 1; v++) for (h = -1; h <= 1; h++) if (drv[d][row + v][col + h] <= tr) homo[d][row][col]++; } /* Average the most homogenous pixels for the final result: */ if (height - top < TS + 4) mrow = height - top + 2; if (width - left < TS + 4) mcol = width - left + 2; for (row = MIN(top, 8); row < mrow - 8; row++) for (col = MIN(left, 8); col < mcol - 8; col++) { for (d = 0; d < ndir; d++) for (hm[d] = 0, v = -2; v <= 2; v++) for (h = -2; h <= 2; h++) hm[d] += homo[d][row + v][col + h]; for (d = 0; d < ndir - 4; d++) if (hm[d] < hm[d + 4]) hm[d] = 0; else if (hm[d] > hm[d + 4]) hm[d + 4] = 0; for (max = hm[0], d = 1; d < ndir; d++) if (max < hm[d]) max = hm[d]; max -= max >> 3; memset(avg, 0, sizeof avg); for (d = 0; d < ndir; d++) if (hm[d] >= max) { FORC3 avg[c] += rgb[d][row][col][c]; avg[3]++; } FORC3 image[(row + top) * width + col + left][c] = avg[c] / avg[3]; } } free(buffer); border_interpolate(8); } #undef fcol /* Adaptive Homogeneity-Directed interpolation is based on the work of Keigo Hirakawa, Thomas Parks, and Paul Lee. */ #ifdef LIBRAW_LIBRARY_BUILD void CLASS ahd_interpolate_green_h_and_v(int top, int left, ushort (*out_rgb)[TS][TS][3]) { int row, col; int c, val; ushort(*pix)[4]; const int rowlimit = MIN(top + TS, height - 2); const int collimit = MIN(left + TS, width - 2); for (row = top; row < rowlimit; row++) { col = left + (FC(row, left) & 1); for (c = FC(row, col); col < collimit; col += 2) { pix = image + row * width + col; val = ((pix[-1][1] + pix[0][c] + pix[1][1]) * 2 - pix[-2][c] - pix[2][c]) >> 2; out_rgb[0][row - top][col - left][1] = ULIM(val, pix[-1][1], pix[1][1]); val = ((pix[-width][1] + pix[0][c] + pix[width][1]) * 2 - pix[-2 * width][c] - pix[2 * width][c]) >> 2; out_rgb[1][row - top][col - left][1] = ULIM(val, pix[-width][1], pix[width][1]); } } } void CLASS ahd_interpolate_r_and_b_in_rgb_and_convert_to_cielab(int top, int left, ushort (*inout_rgb)[TS][3], short (*out_lab)[TS][3]) { unsigned row, col; int c, val; ushort(*pix)[4]; ushort(*rix)[3]; short(*lix)[3]; float xyz[3]; const unsigned num_pix_per_row = 4 * width; const unsigned rowlimit = MIN(top + TS - 1, height - 3); const unsigned collimit = MIN(left + TS - 1, width - 3); ushort *pix_above; ushort *pix_below; int t1, t2; for (row = top + 1; row < rowlimit; row++) { pix = image + row * width + left; rix = &inout_rgb[row - top][0]; lix = &out_lab[row - top][0]; for (col = left + 1; col < collimit; col++) { pix++; pix_above = &pix[0][0] - num_pix_per_row; pix_below = &pix[0][0] + num_pix_per_row; rix++; lix++; c = 2 - FC(row, col); if (c == 1) { c = FC(row + 1, col); t1 = 2 - c; val = pix[0][1] + ((pix[-1][t1] + pix[1][t1] - rix[-1][1] - rix[1][1]) >> 1); rix[0][t1] = CLIP(val); val = pix[0][1] + ((pix_above[c] + pix_below[c] - rix[-TS][1] - rix[TS][1]) >> 1); } else { t1 = -4 + c; /* -4+c: pixel of color c to the left */ t2 = 4 + c; /* 4+c: pixel of color c to the right */ val = rix[0][1] + ((pix_above[t1] + pix_above[t2] + pix_below[t1] + pix_below[t2] - rix[-TS - 1][1] - rix[-TS + 1][1] - rix[+TS - 1][1] - rix[+TS + 1][1] + 1) >> 2); } rix[0][c] = CLIP(val); c = FC(row, col); rix[0][c] = pix[0][c]; cielab(rix[0], lix[0]); } } } void CLASS ahd_interpolate_r_and_b_and_convert_to_cielab(int top, int left, ushort (*inout_rgb)[TS][TS][3], short (*out_lab)[TS][TS][3]) { int direction; for (direction = 0; direction < 2; direction++) { ahd_interpolate_r_and_b_in_rgb_and_convert_to_cielab(top, left, inout_rgb[direction], out_lab[direction]); } } void CLASS ahd_interpolate_build_homogeneity_map(int top, int left, short (*lab)[TS][TS][3], char (*out_homogeneity_map)[TS][2]) { int row, col; int tr, tc; int direction; int i; short(*lix)[3]; short(*lixs[2])[3]; short *adjacent_lix; unsigned ldiff[2][4], abdiff[2][4], leps, abeps; static const int dir[4] = {-1, 1, -TS, TS}; const int rowlimit = MIN(top + TS - 2, height - 4); const int collimit = MIN(left + TS - 2, width - 4); int homogeneity; char(*homogeneity_map_p)[2]; memset(out_homogeneity_map, 0, 2 * TS * TS); for (row = top + 2; row < rowlimit; row++) { tr = row - top; homogeneity_map_p = &out_homogeneity_map[tr][1]; for (direction = 0; direction < 2; direction++) { lixs[direction] = &lab[direction][tr][1]; } for (col = left + 2; col < collimit; col++) { tc = col - left; homogeneity_map_p++; for (direction = 0; direction < 2; direction++) { lix = ++lixs[direction]; for (i = 0; i < 4; i++) { adjacent_lix = lix[dir[i]]; ldiff[direction][i] = ABS(lix[0][0] - adjacent_lix[0]); abdiff[direction][i] = SQR(lix[0][1] - adjacent_lix[1]) + SQR(lix[0][2] - adjacent_lix[2]); } } leps = MIN(MAX(ldiff[0][0], ldiff[0][1]), MAX(ldiff[1][2], ldiff[1][3])); abeps = MIN(MAX(abdiff[0][0], abdiff[0][1]), MAX(abdiff[1][2], abdiff[1][3])); for (direction = 0; direction < 2; direction++) { homogeneity = 0; for (i = 0; i < 4; i++) { if (ldiff[direction][i] <= leps && abdiff[direction][i] <= abeps) { homogeneity++; } } homogeneity_map_p[0][direction] = homogeneity; } } } } void CLASS ahd_interpolate_combine_homogeneous_pixels(int top, int left, ushort (*rgb)[TS][TS][3], char (*homogeneity_map)[TS][2]) { int row, col; int tr, tc; int i, j; int direction; int hm[2]; int c; const int rowlimit = MIN(top + TS - 3, height - 5); const int collimit = MIN(left + TS - 3, width - 5); ushort(*pix)[4]; ushort(*rix[2])[3]; for (row = top + 3; row < rowlimit; row++) { tr = row - top; pix = &image[row * width + left + 2]; for (direction = 0; direction < 2; direction++) { rix[direction] = &rgb[direction][tr][2]; } for (col = left + 3; col < collimit; col++) { tc = col - left; pix++; for (direction = 0; direction < 2; direction++) { rix[direction]++; } for (direction = 0; direction < 2; direction++) { hm[direction] = 0; for (i = tr - 1; i <= tr + 1; i++) { for (j = tc - 1; j <= tc + 1; j++) { hm[direction] += homogeneity_map[i][j][direction]; } } } if (hm[0] != hm[1]) { memcpy(pix[0], rix[hm[1] > hm[0]][0], 3 * sizeof(ushort)); } else { FORC3 { pix[0][c] = (rix[0][0][c] + rix[1][0][c]) >> 1; } } } } } void CLASS ahd_interpolate() { int i, j, k, top, left; float xyz_cam[3][4], r; char *buffer; ushort(*rgb)[TS][TS][3]; short(*lab)[TS][TS][3]; char(*homo)[TS][2]; int terminate_flag = 0; cielab(0, 0); border_interpolate(5); #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_USE_OPENMP #pragma omp parallel private(buffer, rgb, lab, homo, top, left, i, j, k) shared(xyz_cam, terminate_flag) #endif #endif { buffer = (char *)malloc(26 * TS * TS); /* 1664 kB */ merror(buffer, "ahd_interpolate()"); rgb = (ushort(*)[TS][TS][3])buffer; lab = (short(*)[TS][TS][3])(buffer + 12 * TS * TS); homo = (char(*)[TS][2])(buffer + 24 * TS * TS); #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_USE_OPENMP #pragma omp for schedule(dynamic) #endif #endif for (top = 2; top < height - 5; top += TS - 6) { #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_USE_OPENMP if (0 == omp_get_thread_num()) #endif if (callbacks.progress_cb) { int rr = (*callbacks.progress_cb)(callbacks.progresscb_data, LIBRAW_PROGRESS_INTERPOLATE, top - 2, height - 7); if (rr) terminate_flag = 1; } #endif for (left = 2; !terminate_flag && (left < width - 5); left += TS - 6) { ahd_interpolate_green_h_and_v(top, left, rgb); ahd_interpolate_r_and_b_and_convert_to_cielab(top, left, rgb, lab); ahd_interpolate_build_homogeneity_map(top, left, lab, homo); ahd_interpolate_combine_homogeneous_pixels(top, left, rgb, homo); } } free(buffer); } #ifdef LIBRAW_LIBRARY_BUILD if (terminate_flag) throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK; #endif } #else void CLASS ahd_interpolate() { int i, j, top, left, row, col, tr, tc, c, d, val, hm[2]; static const int dir[4] = {-1, 1, -TS, TS}; unsigned ldiff[2][4], abdiff[2][4], leps, abeps; ushort(*rgb)[TS][TS][3], (*rix)[3], (*pix)[4]; short(*lab)[TS][TS][3], (*lix)[3]; char(*homo)[TS][TS], *buffer; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("AHD interpolation...\n")); #endif cielab(0, 0); border_interpolate(5); buffer = (char *)malloc(26 * TS * TS); merror(buffer, "ahd_interpolate()"); rgb = (ushort(*)[TS][TS][3])buffer; lab = (short(*)[TS][TS][3])(buffer + 12 * TS * TS); homo = (char(*)[TS][TS])(buffer + 24 * TS * TS); for (top = 2; top < height - 5; top += TS - 6) for (left = 2; left < width - 5; left += TS - 6) { /* Interpolate green horizontally and vertically: */ for (row = top; row < top + TS && row < height - 2; row++) { col = left + (FC(row, left) & 1); for (c = FC(row, col); col < left + TS && col < width - 2; col += 2) { pix = image + row * width + col; val = ((pix[-1][1] + pix[0][c] + pix[1][1]) * 2 - pix[-2][c] - pix[2][c]) >> 2; rgb[0][row - top][col - left][1] = ULIM(val, pix[-1][1], pix[1][1]); val = ((pix[-width][1] + pix[0][c] + pix[width][1]) * 2 - pix[-2 * width][c] - pix[2 * width][c]) >> 2; rgb[1][row - top][col - left][1] = ULIM(val, pix[-width][1], pix[width][1]); } } /* Interpolate red and blue, and convert to CIELab: */ for (d = 0; d < 2; d++) for (row = top + 1; row < top + TS - 1 && row < height - 3; row++) for (col = left + 1; col < left + TS - 1 && col < width - 3; col++) { pix = image + row * width + col; rix = &rgb[d][row - top][col - left]; lix = &lab[d][row - top][col - left]; if ((c = 2 - FC(row, col)) == 1) { c = FC(row + 1, col); val = pix[0][1] + ((pix[-1][2 - c] + pix[1][2 - c] - rix[-1][1] - rix[1][1]) >> 1); rix[0][2 - c] = CLIP(val); val = pix[0][1] + ((pix[-width][c] + pix[width][c] - rix[-TS][1] - rix[TS][1]) >> 1); } else val = rix[0][1] + ((pix[-width - 1][c] + pix[-width + 1][c] + pix[+width - 1][c] + pix[+width + 1][c] - rix[-TS - 1][1] - rix[-TS + 1][1] - rix[+TS - 1][1] - rix[+TS + 1][1] + 1) >> 2); rix[0][c] = CLIP(val); c = FC(row, col); rix[0][c] = pix[0][c]; cielab(rix[0], lix[0]); } /* Build homogeneity maps from the CIELab images: */ memset(homo, 0, 2 * TS * TS); for (row = top + 2; row < top + TS - 2 && row < height - 4; row++) { tr = row - top; for (col = left + 2; col < left + TS - 2 && col < width - 4; col++) { tc = col - left; for (d = 0; d < 2; d++) { lix = &lab[d][tr][tc]; for (i = 0; i < 4; i++) { ldiff[d][i] = ABS(lix[0][0] - lix[dir[i]][0]); abdiff[d][i] = SQR(lix[0][1] - lix[dir[i]][1]) + SQR(lix[0][2] - lix[dir[i]][2]); } } leps = MIN(MAX(ldiff[0][0], ldiff[0][1]), MAX(ldiff[1][2], ldiff[1][3])); abeps = MIN(MAX(abdiff[0][0], abdiff[0][1]), MAX(abdiff[1][2], abdiff[1][3])); for (d = 0; d < 2; d++) for (i = 0; i < 4; i++) if (ldiff[d][i] <= leps && abdiff[d][i] <= abeps) homo[d][tr][tc]++; } } /* Combine the most homogenous pixels for the final result: */ for (row = top + 3; row < top + TS - 3 && row < height - 5; row++) { tr = row - top; for (col = left + 3; col < left + TS - 3 && col < width - 5; col++) { tc = col - left; for (d = 0; d < 2; d++) for (hm[d] = 0, i = tr - 1; i <= tr + 1; i++) for (j = tc - 1; j <= tc + 1; j++) hm[d] += homo[d][i][j]; if (hm[0] != hm[1]) FORC3 image[row * width + col][c] = rgb[hm[1] > hm[0]][tr][tc][c]; else FORC3 image[row * width + col][c] = (rgb[0][tr][tc][c] + rgb[1][tr][tc][c]) >> 1; } } } free(buffer); } #endif #undef TS void CLASS median_filter() { ushort(*pix)[4]; int pass, c, i, j, k, med[9]; static const uchar opt[] = /* Optimal 9-element median search */ {1, 2, 4, 5, 7, 8, 0, 1, 3, 4, 6, 7, 1, 2, 4, 5, 7, 8, 0, 3, 5, 8, 4, 7, 3, 6, 1, 4, 2, 5, 4, 7, 4, 2, 6, 4, 4, 2}; for (pass = 1; pass <= med_passes; pass++) { #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_MEDIAN_FILTER, pass - 1, med_passes); #endif #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Median filter pass %d...\n"), pass); #endif for (c = 0; c < 3; c += 2) { for (pix = image; pix < image + width * height; pix++) pix[0][3] = pix[0][c]; for (pix = image + width; pix < image + width * (height - 1); pix++) { if ((pix - image + 1) % width < 2) continue; for (k = 0, i = -width; i <= width; i += width) for (j = i - 1; j <= i + 1; j++) med[k++] = pix[j][3] - pix[j][1]; for (i = 0; i < sizeof opt; i += 2) if (med[opt[i]] > med[opt[i + 1]]) SWAP(med[opt[i]], med[opt[i + 1]]); pix[0][c] = CLIP(med[4] + pix[0][1]); } } } } void CLASS blend_highlights() { int clip = INT_MAX, row, col, c, i, j; static const float trans[2][4][4] = {{{1, 1, 1}, {1.7320508, -1.7320508, 0}, {-1, -1, 2}}, {{1, 1, 1, 1}, {1, -1, 1, -1}, {1, 1, -1, -1}, {1, -1, -1, 1}}}; static const float itrans[2][4][4] = {{{1, 0.8660254, -0.5}, {1, -0.8660254, -0.5}, {1, 0, 1}}, {{1, 1, 1, 1}, {1, -1, 1, -1}, {1, 1, -1, -1}, {1, -1, -1, 1}}}; float cam[2][4], lab[2][4], sum[2], chratio; if ((unsigned)(colors - 3) > 1) return; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Blending highlights...\n")); #endif #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS, 0, 2); #endif FORCC if (clip > (i = 65535 * pre_mul[c])) clip = i; for (row = 0; row < height; row++) for (col = 0; col < width; col++) { FORCC if (image[row * width + col][c] > clip) break; if (c == colors) continue; FORCC { cam[0][c] = image[row * width + col][c]; cam[1][c] = MIN(cam[0][c], clip); } for (i = 0; i < 2; i++) { FORCC for (lab[i][c] = j = 0; j < colors; j++) lab[i][c] += trans[colors - 3][c][j] * cam[i][j]; for (sum[i] = 0, c = 1; c < colors; c++) sum[i] += SQR(lab[i][c]); } chratio = sqrt(sum[1] / sum[0]); for (c = 1; c < colors; c++) lab[0][c] *= chratio; FORCC for (cam[0][c] = j = 0; j < colors; j++) cam[0][c] += itrans[colors - 3][c][j] * lab[0][j]; FORCC image[row * width + col][c] = cam[0][c] / colors; } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS, 1, 2); #endif } #define SCALE (4 >> shrink) void CLASS recover_highlights() { float *map, sum, wgt, grow; int hsat[4], count, spread, change, val, i; unsigned high, wide, mrow, mcol, row, col, kc, c, d, y, x; ushort *pixel; static const signed char dir[8][2] = {{-1, -1}, {-1, 0}, {-1, 1}, {0, 1}, {1, 1}, {1, 0}, {1, -1}, {0, -1}}; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Rebuilding highlights...\n")); #endif grow = pow(2.0, 4 - highlight); FORCC hsat[c] = 32000 * pre_mul[c]; for (kc = 0, c = 1; c < colors; c++) if (pre_mul[kc] < pre_mul[c]) kc = c; high = height / SCALE; wide = width / SCALE; map = (float *)calloc(high, wide * sizeof *map); merror(map, "recover_highlights()"); FORCC if (c != kc) { #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS, c - 1, colors - 1); #endif memset(map, 0, high * wide * sizeof *map); for (mrow = 0; mrow < high; mrow++) for (mcol = 0; mcol < wide; mcol++) { sum = wgt = count = 0; for (row = mrow * SCALE; row < (mrow + 1) * SCALE; row++) for (col = mcol * SCALE; col < (mcol + 1) * SCALE; col++) { pixel = image[row * width + col]; if (pixel[c] / hsat[c] == 1 && pixel[kc] > 24000) { sum += pixel[c]; wgt += pixel[kc]; count++; } } if (count == SCALE * SCALE) map[mrow * wide + mcol] = sum / wgt; } for (spread = 32 / grow; spread--;) { for (mrow = 0; mrow < high; mrow++) for (mcol = 0; mcol < wide; mcol++) { if (map[mrow * wide + mcol]) continue; sum = count = 0; for (d = 0; d < 8; d++) { y = mrow + dir[d][0]; x = mcol + dir[d][1]; if (y < high && x < wide && map[y * wide + x] > 0) { sum += (1 + (d & 1)) * map[y * wide + x]; count += 1 + (d & 1); } } if (count > 3) map[mrow * wide + mcol] = -(sum + grow) / (count + grow); } for (change = i = 0; i < high * wide; i++) if (map[i] < 0) { map[i] = -map[i]; change = 1; } if (!change) break; } for (i = 0; i < high * wide; i++) if (map[i] == 0) map[i] = 1; for (mrow = 0; mrow < high; mrow++) for (mcol = 0; mcol < wide; mcol++) { for (row = mrow * SCALE; row < (mrow + 1) * SCALE; row++) for (col = mcol * SCALE; col < (mcol + 1) * SCALE; col++) { pixel = image[row * width + col]; if (pixel[c] / hsat[c] > 1) { val = pixel[kc] * map[mrow * wide + mcol]; if (pixel[c] < val) pixel[c] = CLIP(val); } } } } free(map); } #undef SCALE void CLASS tiff_get(unsigned base, unsigned *tag, unsigned *type, unsigned *len, unsigned *save) { *tag = get2(); *type = get2(); *len = get4(); *save = ftell(ifp) + 4; if (*len * ("11124811248484"[*type < 14 ? *type : 0] - '0') > 4) fseek(ifp, get4() + base, SEEK_SET); } void CLASS parse_thumb_note(int base, unsigned toff, unsigned tlen) { unsigned entries, tag, type, len, save; entries = get2(); while (entries--) { tiff_get(base, &tag, &type, &len, &save); if (tag == toff) thumb_offset = get4() + base; if (tag == tlen) thumb_length = get4(); fseek(ifp, save, SEEK_SET); } } //@end COMMON int CLASS parse_tiff_ifd(int base); //@out COMMON static float powf_lim(float a, float b, float limup) { return (b > limup || b < -limup) ? 0.f : powf(a, b); } static float powf64(float a, float b) { return powf_lim(a, b, 64.f); } #ifdef LIBRAW_LIBRARY_BUILD static float my_roundf(float x) { float t; if (x >= 0.0) { t = ceilf(x); if (t - x > 0.5) t -= 1.0; return t; } else { t = ceilf(-x); if (t + x > 0.5) t -= 1.0; return -t; } } static float _CanonConvertAperture(ushort in) { if ((in == (ushort)0xffe0) || (in == (ushort)0x7fff)) return 0.0f; return powf64(2.0, in / 64.0); } static float _CanonConvertEV(short in) { short EV, Sign, Frac; float Frac_f; EV = in; if (EV < 0) { EV = -EV; Sign = -1; } else { Sign = 1; } Frac = EV & 0x1f; EV -= Frac; // remove fraction if (Frac == 0x0c) { // convert 1/3 and 2/3 codes Frac_f = 32.0f / 3.0f; } else if (Frac == 0x14) { Frac_f = 64.0f / 3.0f; } else Frac_f = (float)Frac; return ((float)Sign * ((float)EV + Frac_f)) / 32.0f; } void CLASS setCanonBodyFeatures(unsigned id) { imgdata.lens.makernotes.CamID = id; if ((id == 0x80000001) || // 1D (id == 0x80000174) || // 1D2 (id == 0x80000232) || // 1D2N (id == 0x80000169) || // 1D3 (id == 0x80000281) // 1D4 ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSH; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF; } else if ((id == 0x80000167) || // 1Ds (id == 0x80000188) || // 1Ds2 (id == 0x80000215) || // 1Ds3 (id == 0x80000269) || // 1DX (id == 0x80000328) || // 1DX2 (id == 0x80000324) || // 1DC (id == 0x80000213) || // 5D (id == 0x80000218) || // 5D2 (id == 0x80000285) || // 5D3 (id == 0x80000349) || // 5D4 (id == 0x80000382) || // 5DS (id == 0x80000401) || // 5DS R (id == 0x80000302) // 6D ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF; } else if ((id == 0x80000331) || // M (id == 0x80000355) || // M2 (id == 0x80000374) || // M3 (id == 0x80000384) || // M10 (id == 0x80000394) || // M5 (id == 0x80000407) // M6 ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF_M; } else if ((id == 0x01140000) || // D30 (id == 0x01668000) || // D60 (id > 0x80000000)) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Unknown; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } return; } void CLASS processCanonCameraInfo(unsigned id, uchar *CameraInfo, unsigned maxlen) { ushort iCanonLensID = 0, iCanonMaxFocal = 0, iCanonMinFocal = 0, iCanonLens = 0, iCanonCurFocal = 0, iCanonFocalType = 0; CameraInfo[0] = 0; CameraInfo[1] = 0; switch (id) { case 0x80000001: // 1D case 0x80000167: // 1DS iCanonCurFocal = 10; iCanonLensID = 13; iCanonMinFocal = 14; iCanonMaxFocal = 16; if (!imgdata.lens.makernotes.CurFocal) imgdata.lens.makernotes.CurFocal = sget2(CameraInfo + iCanonCurFocal); if (!imgdata.lens.makernotes.MinFocal) imgdata.lens.makernotes.MinFocal = sget2(CameraInfo + iCanonMinFocal); if (!imgdata.lens.makernotes.MaxFocal) imgdata.lens.makernotes.MaxFocal = sget2(CameraInfo + iCanonMaxFocal); break; case 0x80000174: // 1DMkII case 0x80000188: // 1DsMkII iCanonCurFocal = 9; iCanonLensID = 12; iCanonMinFocal = 17; iCanonMaxFocal = 19; iCanonFocalType = 45; break; case 0x80000232: // 1DMkII N iCanonCurFocal = 9; iCanonLensID = 12; iCanonMinFocal = 17; iCanonMaxFocal = 19; break; case 0x80000169: // 1DMkIII case 0x80000215: // 1DsMkIII iCanonCurFocal = 29; iCanonLensID = 273; iCanonMinFocal = 275; iCanonMaxFocal = 277; break; case 0x80000281: // 1DMkIV iCanonCurFocal = 30; iCanonLensID = 335; iCanonMinFocal = 337; iCanonMaxFocal = 339; break; case 0x80000269: // 1D X iCanonCurFocal = 35; iCanonLensID = 423; iCanonMinFocal = 425; iCanonMaxFocal = 427; break; case 0x80000213: // 5D iCanonCurFocal = 40; if (!sget2Rev(CameraInfo + 12)) iCanonLensID = 151; else iCanonLensID = 12; iCanonMinFocal = 147; iCanonMaxFocal = 149; break; case 0x80000218: // 5DMkII iCanonCurFocal = 30; iCanonLensID = 230; iCanonMinFocal = 232; iCanonMaxFocal = 234; break; case 0x80000285: // 5DMkIII iCanonCurFocal = 35; iCanonLensID = 339; iCanonMinFocal = 341; iCanonMaxFocal = 343; break; case 0x80000302: // 6D iCanonCurFocal = 35; iCanonLensID = 353; iCanonMinFocal = 355; iCanonMaxFocal = 357; break; case 0x80000250: // 7D iCanonCurFocal = 30; iCanonLensID = 274; iCanonMinFocal = 276; iCanonMaxFocal = 278; break; case 0x80000190: // 40D iCanonCurFocal = 29; iCanonLensID = 214; iCanonMinFocal = 216; iCanonMaxFocal = 218; iCanonLens = 2347; break; case 0x80000261: // 50D iCanonCurFocal = 30; iCanonLensID = 234; iCanonMinFocal = 236; iCanonMaxFocal = 238; break; case 0x80000287: // 60D iCanonCurFocal = 30; iCanonLensID = 232; iCanonMinFocal = 234; iCanonMaxFocal = 236; break; case 0x80000325: // 70D iCanonCurFocal = 35; iCanonLensID = 358; iCanonMinFocal = 360; iCanonMaxFocal = 362; break; case 0x80000176: // 450D iCanonCurFocal = 29; iCanonLensID = 222; iCanonLens = 2355; break; case 0x80000252: // 500D iCanonCurFocal = 30; iCanonLensID = 246; iCanonMinFocal = 248; iCanonMaxFocal = 250; break; case 0x80000270: // 550D iCanonCurFocal = 30; iCanonLensID = 255; iCanonMinFocal = 257; iCanonMaxFocal = 259; break; case 0x80000286: // 600D case 0x80000288: // 1100D iCanonCurFocal = 30; iCanonLensID = 234; iCanonMinFocal = 236; iCanonMaxFocal = 238; break; case 0x80000301: // 650D case 0x80000326: // 700D iCanonCurFocal = 35; iCanonLensID = 295; iCanonMinFocal = 297; iCanonMaxFocal = 299; break; case 0x80000254: // 1000D iCanonCurFocal = 29; iCanonLensID = 226; iCanonMinFocal = 228; iCanonMaxFocal = 230; iCanonLens = 2359; break; } if (iCanonFocalType) { if (iCanonFocalType >= maxlen) return; // broken; imgdata.lens.makernotes.FocalType = CameraInfo[iCanonFocalType]; if (!imgdata.lens.makernotes.FocalType) // zero means 'fixed' here, replacing with standard '1' imgdata.lens.makernotes.FocalType = 1; } if (!imgdata.lens.makernotes.CurFocal) { if (iCanonCurFocal >= maxlen) return; // broken; imgdata.lens.makernotes.CurFocal = sget2Rev(CameraInfo + iCanonCurFocal); } if (!imgdata.lens.makernotes.LensID) { if (iCanonLensID >= maxlen) return; // broken; imgdata.lens.makernotes.LensID = sget2Rev(CameraInfo + iCanonLensID); } if (!imgdata.lens.makernotes.MinFocal) { if (iCanonMinFocal >= maxlen) return; // broken; imgdata.lens.makernotes.MinFocal = sget2Rev(CameraInfo + iCanonMinFocal); } if (!imgdata.lens.makernotes.MaxFocal) { if (iCanonMaxFocal >= maxlen) return; // broken; imgdata.lens.makernotes.MaxFocal = sget2Rev(CameraInfo + iCanonMaxFocal); } if (!imgdata.lens.makernotes.Lens[0] && iCanonLens) { if (iCanonLens + 64 >= maxlen) return; // broken; if (CameraInfo[iCanonLens] < 65) // non-Canon lens { memcpy(imgdata.lens.makernotes.Lens, CameraInfo + iCanonLens, 64); } else if (!strncmp((char *)CameraInfo + iCanonLens, "EF-S", 4)) { memcpy(imgdata.lens.makernotes.Lens, "EF-S ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF-E", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_S; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else if (!strncmp((char *)CameraInfo + iCanonLens, "TS-E", 4)) { memcpy(imgdata.lens.makernotes.Lens, "TS-E ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "TS-E", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else if (!strncmp((char *)CameraInfo + iCanonLens, "MP-E", 4)) { memcpy(imgdata.lens.makernotes.Lens, "MP-E ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "MP-E", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else if (!strncmp((char *)CameraInfo + iCanonLens, "EF-M", 4)) { memcpy(imgdata.lens.makernotes.Lens, "EF-M ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF-M", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_M; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else { memcpy(imgdata.lens.makernotes.Lens, CameraInfo + iCanonLens, 2); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF", 2); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; imgdata.lens.makernotes.Lens[2] = 32; memcpy(imgdata.lens.makernotes.Lens + 3, CameraInfo + iCanonLens + 2, 62); } } return; } void CLASS Canon_CameraSettings() { fseek(ifp, 10, SEEK_CUR); imgdata.shootinginfo.DriveMode = get2(); get2(); imgdata.shootinginfo.FocusMode = get2(); fseek(ifp, 18, SEEK_CUR); imgdata.shootinginfo.MeteringMode = get2(); get2(); imgdata.shootinginfo.AFPoint = get2(); imgdata.shootinginfo.ExposureMode = get2(); get2(); imgdata.lens.makernotes.LensID = get2(); imgdata.lens.makernotes.MaxFocal = get2(); imgdata.lens.makernotes.MinFocal = get2(); imgdata.lens.makernotes.CanonFocalUnits = get2(); if (imgdata.lens.makernotes.CanonFocalUnits > 1) { imgdata.lens.makernotes.MaxFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; imgdata.lens.makernotes.MinFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; } imgdata.lens.makernotes.MaxAp = _CanonConvertAperture(get2()); imgdata.lens.makernotes.MinAp = _CanonConvertAperture(get2()); fseek(ifp, 12, SEEK_CUR); imgdata.shootinginfo.ImageStabilization = get2(); } void CLASS Canon_WBpresets(int skip1, int skip2) { int c; FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); if (skip2) fseek(ifp, skip2, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); return; } void CLASS Canon_WBCTpresets(short WBCTversion) { if (WBCTversion == 0) for (int i = 0; i < 15; i++) // tint, as shot R, as shot B, CСT { imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(get2(), 1.f); imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(get2(), 1.f); imgdata.color.WBCT_Coeffs[i][0] = get2(); } else if (WBCTversion == 1) for (int i = 0; i < 15; i++) // as shot R, as shot B, tint, CСT { imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(get2(), 1.f); imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(get2(), 1.f); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][0] = get2(); } else if ((WBCTversion == 2) && ((unique_id == 0x80000374) || // M3 (unique_id == 0x80000384) || // M10 (unique_id == 0x80000394) || // M5 (unique_id == 0x80000407) || // M6 (unique_id == 0x03970000) || // G7 X Mark II (unique_id == 0x04100000))) // G9 X Mark II for (int i = 0; i < 15; i++) // tint, offset, as shot R, as shot B, CСT { fseek(ifp, 2, SEEK_CUR); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(1.f, get2()); imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(1.f, get2()); imgdata.color.WBCT_Coeffs[i][0] = get2(); } else if ((WBCTversion == 2) && ((unique_id == 0x03950000) || (unique_id == 0x03930000))) // G5 X, G9 X for (int i = 0; i < 15; i++) // tint, offset, as shot R, as shot B, CСT { fseek(ifp, 2, SEEK_CUR); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; imgdata.color.WBCT_Coeffs[i][1] = (float)get2() / 512.0f; imgdata.color.WBCT_Coeffs[i][3] = (float)get2() / 512.0f; imgdata.color.WBCT_Coeffs[i][0] = get2(); } return; } void CLASS processNikonLensData(uchar *LensData, unsigned len) { ushort i; if (!(imgdata.lens.nikon.NikonLensType & 0x01)) { imgdata.lens.makernotes.LensFeatures_pre[0] = 'A'; imgdata.lens.makernotes.LensFeatures_pre[1] = 'F'; } else { imgdata.lens.makernotes.LensFeatures_pre[0] = 'M'; imgdata.lens.makernotes.LensFeatures_pre[1] = 'F'; } if (imgdata.lens.nikon.NikonLensType & 0x02) { if (imgdata.lens.nikon.NikonLensType & 0x04) imgdata.lens.makernotes.LensFeatures_suf[0] = 'G'; else imgdata.lens.makernotes.LensFeatures_suf[0] = 'D'; imgdata.lens.makernotes.LensFeatures_suf[1] = ' '; } if (imgdata.lens.nikon.NikonLensType & 0x08) { imgdata.lens.makernotes.LensFeatures_suf[2] = 'V'; imgdata.lens.makernotes.LensFeatures_suf[3] = 'R'; } if (imgdata.lens.nikon.NikonLensType & 0x10) { imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_CX; imgdata.lens.makernotes.CameraFormat = imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_1INCH; } else imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_F; if (imgdata.lens.nikon.NikonLensType & 0x20) { strcpy(imgdata.lens.makernotes.Adapter, "FT-1"); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Nikon_F; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_CX; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_1INCH; } imgdata.lens.nikon.NikonLensType = imgdata.lens.nikon.NikonLensType & 0xdf; if (len < 20) { switch (len) { case 9: i = 2; break; case 15: i = 7; break; case 16: i = 8; break; } imgdata.lens.nikon.NikonLensIDNumber = LensData[i]; imgdata.lens.nikon.NikonLensFStops = LensData[i + 1]; imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops / 12.0f; if (fabsf(imgdata.lens.makernotes.MinFocal) < 1.1f) { if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 2]) imgdata.lens.makernotes.MinFocal = 5.0f * powf64(2.0f, (float)LensData[i + 2] / 24.0f); if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 3]) imgdata.lens.makernotes.MaxFocal = 5.0f * powf64(2.0f, (float)LensData[i + 3] / 24.0f); if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 4]) imgdata.lens.makernotes.MaxAp4MinFocal = powf64(2.0f, (float)LensData[i + 4] / 24.0f); if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 5]) imgdata.lens.makernotes.MaxAp4MaxFocal = powf64(2.0f, (float)LensData[i + 5] / 24.0f); } imgdata.lens.nikon.NikonMCUVersion = LensData[i + 6]; if (i != 2) { if ((LensData[i - 1]) && (fabsf(imgdata.lens.makernotes.CurFocal) < 1.1f)) imgdata.lens.makernotes.CurFocal = 5.0f * powf64(2.0f, (float)LensData[i - 1] / 24.0f); if (LensData[i + 7]) imgdata.lens.nikon.NikonEffectiveMaxAp = powf64(2.0f, (float)LensData[i + 7] / 24.0f); } imgdata.lens.makernotes.LensID = (unsigned long long)LensData[i] << 56 | (unsigned long long)LensData[i + 1] << 48 | (unsigned long long)LensData[i + 2] << 40 | (unsigned long long)LensData[i + 3] << 32 | (unsigned long long)LensData[i + 4] << 24 | (unsigned long long)LensData[i + 5] << 16 | (unsigned long long)LensData[i + 6] << 8 | (unsigned long long)imgdata.lens.nikon.NikonLensType; } else if ((len == 459) || (len == 590)) { memcpy(imgdata.lens.makernotes.Lens, LensData + 390, 64); } else if (len == 509) { memcpy(imgdata.lens.makernotes.Lens, LensData + 391, 64); } else if (len == 879) { memcpy(imgdata.lens.makernotes.Lens, LensData + 680, 64); } return; } void CLASS setOlympusBodyFeatures(unsigned long long id) { imgdata.lens.makernotes.CamID = id; if ((id == 0x4434303430ULL) || // E-1 (id == 0x4434303431ULL) || // E-300 ((id & 0x00ffff0000ULL) == 0x0030300000ULL)) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FT; if ((id == 0x4434303430ULL) || // E-1 (id == 0x4434303431ULL) || // E-330 ((id >= 0x5330303033ULL) && (id <= 0x5330303138ULL)) || // E-330 to E-520 (id == 0x5330303233ULL) || // E-620 (id == 0x5330303239ULL) || // E-450 (id == 0x5330303330ULL) || // E-600 (id == 0x5330303333ULL)) // E-5 { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FT; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_mFT; } } else { imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } return; } void CLASS parseCanonMakernotes(unsigned tag, unsigned type, unsigned len) { if (tag == 0x0001) Canon_CameraSettings(); else if (tag == 0x0002) // focal length { imgdata.lens.makernotes.FocalType = get2(); imgdata.lens.makernotes.CurFocal = get2(); if (imgdata.lens.makernotes.CanonFocalUnits > 1) { imgdata.lens.makernotes.CurFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; } } else if (tag == 0x0004) // shot info { short tempAp; fseek(ifp, 30, SEEK_CUR); imgdata.other.FlashEC = _CanonConvertEV((signed short)get2()); fseek(ifp, 8 - 32, SEEK_CUR); if ((tempAp = get2()) != 0x7fff) imgdata.lens.makernotes.CurAp = _CanonConvertAperture(tempAp); if (imgdata.lens.makernotes.CurAp < 0.7f) { fseek(ifp, 32, SEEK_CUR); imgdata.lens.makernotes.CurAp = _CanonConvertAperture(get2()); } if (!aperture) aperture = imgdata.lens.makernotes.CurAp; } else if (tag == 0x0095 && // lens model tag !imgdata.lens.makernotes.Lens[0]) { fread(imgdata.lens.makernotes.Lens, 2, 1, ifp); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; if (imgdata.lens.makernotes.Lens[0] < 65) // non-Canon lens fread(imgdata.lens.makernotes.Lens + 2, 62, 1, ifp); else { char efs[2]; imgdata.lens.makernotes.LensFeatures_pre[0] = imgdata.lens.makernotes.Lens[0]; imgdata.lens.makernotes.LensFeatures_pre[1] = imgdata.lens.makernotes.Lens[1]; fread(efs, 2, 1, ifp); if (efs[0] == 45 && (efs[1] == 83 || efs[1] == 69 || efs[1] == 77)) { // "EF-S, TS-E, MP-E, EF-M" lenses imgdata.lens.makernotes.Lens[2] = imgdata.lens.makernotes.LensFeatures_pre[2] = efs[0]; imgdata.lens.makernotes.Lens[3] = imgdata.lens.makernotes.LensFeatures_pre[3] = efs[1]; imgdata.lens.makernotes.Lens[4] = 32; if (efs[1] == 83) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_S; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC; } else if (efs[1] == 77) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_M; } } else { // "EF" lenses imgdata.lens.makernotes.Lens[2] = 32; imgdata.lens.makernotes.Lens[3] = efs[0]; imgdata.lens.makernotes.Lens[4] = efs[1]; } fread(imgdata.lens.makernotes.Lens + 5, 58, 1, ifp); } } else if (tag == 0x00a9) { long int save1 = ftell(ifp); int c; fseek(ifp, (0x1 << 1), SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); Canon_WBpresets(0, 0); fseek(ifp, save1, SEEK_SET); } else if (tag == 0x00e0) // sensor info { imgdata.makernotes.canon.SensorWidth = (get2(), get2()); imgdata.makernotes.canon.SensorHeight = get2(); imgdata.makernotes.canon.SensorLeftBorder = (get2(), get2(), get2()); imgdata.makernotes.canon.SensorTopBorder = get2(); imgdata.makernotes.canon.SensorRightBorder = get2(); imgdata.makernotes.canon.SensorBottomBorder = get2(); imgdata.makernotes.canon.BlackMaskLeftBorder = get2(); imgdata.makernotes.canon.BlackMaskTopBorder = get2(); imgdata.makernotes.canon.BlackMaskRightBorder = get2(); imgdata.makernotes.canon.BlackMaskBottomBorder = get2(); } else if (tag == 0x4001 && len > 500) { int c; long int save1 = ftell(ifp); switch (len) { case 582: imgdata.makernotes.canon.CanonColorDataVer = 1; // 20D / 350D { fseek(ifp, save1 + (0x1e << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x41 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x46 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom2][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x23 << 1), SEEK_SET); Canon_WBpresets(2, 2); fseek(ifp, save1 + (0x4b << 1), SEEK_SET); Canon_WBCTpresets(1); // ABCT } break; case 653: imgdata.makernotes.canon.CanonColorDataVer = 2; // 1Dmk2 / 1DsMK2 { fseek(ifp, save1 + (0x18 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x90 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x95 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom2][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x9a << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom3][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x27 << 1), SEEK_SET); Canon_WBpresets(2, 12); fseek(ifp, save1 + (0xa4 << 1), SEEK_SET); Canon_WBCTpresets(1); // ABCT } break; case 796: imgdata.makernotes.canon.CanonColorDataVer = 3; // 1DmkIIN / 5D / 30D / 400D imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek(ifp, save1 + (0x44 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x49 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x71 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x76 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom2][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x7b << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom3][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x80 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x4e << 1), SEEK_SET); Canon_WBpresets(2, 12); fseek(ifp, save1 + (0x85 << 1), SEEK_SET); Canon_WBCTpresets(0); // BCAT fseek(ifp, save1 + (0x0c4 << 1), SEEK_SET); // offset 196 short int bls = 0; FORC4 bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2()); imgdata.makernotes.canon.AverageBlackLevel = bls / 4; } break; // 1DmkIII / 1DSmkIII / 1DmkIV / 5DmkII // 7D / 40D / 50D / 60D / 450D / 500D // 550D / 1000D / 1100D case 674: case 692: case 702: case 1227: case 1250: case 1251: case 1337: case 1338: case 1346: imgdata.makernotes.canon.CanonColorDataVer = 4; imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek(ifp, save1 + (0x44 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x49 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x53 << 1), SEEK_SET); Canon_WBpresets(2, 12); fseek(ifp, save1 + (0xa8 << 1), SEEK_SET); Canon_WBCTpresets(0); // BCAT fseek(ifp, save1 + (0x0e7 << 1), SEEK_SET); // offset 231 short int bls = 0; FORC4 bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2()); imgdata.makernotes.canon.AverageBlackLevel = bls / 4; } if ((imgdata.makernotes.canon.CanonColorDataSubVer == 4) || (imgdata.makernotes.canon.CanonColorDataSubVer == 5)) { fseek(ifp, save1 + (0x2b9 << 1), SEEK_SET); // offset 697 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else if ((imgdata.makernotes.canon.CanonColorDataSubVer == 6) || (imgdata.makernotes.canon.CanonColorDataSubVer == 7)) { fseek(ifp, save1 + (0x2d0 << 1), SEEK_SET); // offset 720 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else if (imgdata.makernotes.canon.CanonColorDataSubVer == 9) { fseek(ifp, save1 + (0x2d4 << 1), SEEK_SET); // offset 724 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } break; case 5120: imgdata.makernotes.canon.CanonColorDataVer = 5; // PowerSot G10, G12, G5 X, G7 X, G9 X, EOS M3, EOS M5, EOS M6 { if ((unique_id == 0x03970000) || // G7 X Mark II (unique_id == 0x04100000) || // G9 X Mark II (unique_id == 0x80000394) || // EOS M5 (unique_id == 0x80000407)) // EOS M6 { fseek(ifp, save1 + (0x4f << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, 8, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2(); fseek(ifp, 8, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Other][c ^ (c >> 1)] = get2(); fseek(ifp, 8, SEEK_CUR); Canon_WBpresets(8, 24); fseek(ifp, 168, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][c ^ (c >> 1)] = get2(); fseek(ifp, 24, SEEK_CUR); Canon_WBCTpresets(2); // BCADT fseek(ifp, 6, SEEK_CUR); } else { fseek(ifp, save1 + (0x4c << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); get2(); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2(); get2(); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Other][c ^ (c >> 1)] = get2(); get2(); Canon_WBpresets(2, 12); fseek(ifp, save1 + (0xba << 1), SEEK_SET); Canon_WBCTpresets(2); // BCADT fseek(ifp, save1 + (0x108 << 1), SEEK_SET); // offset 264 short } int bls = 0; FORC4 bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2()); imgdata.makernotes.canon.AverageBlackLevel = bls / 4; } break; case 1273: case 1275: imgdata.makernotes.canon.CanonColorDataVer = 6; // 600D / 1200D imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek(ifp, save1 + (0x44 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x49 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x67 << 1), SEEK_SET); Canon_WBpresets(2, 12); fseek(ifp, save1 + (0xbc << 1), SEEK_SET); Canon_WBCTpresets(0); // BCAT fseek(ifp, save1 + (0x0fb << 1), SEEK_SET); // offset 251 short int bls = 0; FORC4 bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2()); imgdata.makernotes.canon.AverageBlackLevel = bls / 4; } fseek(ifp, save1 + (0x1e4 << 1), SEEK_SET); // offset 484 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; break; // 1DX / 5DmkIII / 6D / 100D / 650D / 700D / EOS M / 7DmkII / 750D / 760D case 1312: case 1313: case 1316: case 1506: imgdata.makernotes.canon.CanonColorDataVer = 7; imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek(ifp, save1 + (0x44 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x49 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x80 << 1), SEEK_SET); Canon_WBpresets(2, 12); fseek(ifp, save1 + (0xd5 << 1), SEEK_SET); Canon_WBCTpresets(0); // BCAT fseek(ifp, save1 + (0x114 << 1), SEEK_SET); // offset 276 shorts int bls = 0; FORC4 bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2()); imgdata.makernotes.canon.AverageBlackLevel = bls / 4; } if (imgdata.makernotes.canon.CanonColorDataSubVer == 10) { fseek(ifp, save1 + (0x1fd << 1), SEEK_SET); // offset 509 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else if (imgdata.makernotes.canon.CanonColorDataSubVer == 11) { fseek(ifp, save1 + (0x2dd << 1), SEEK_SET); // offset 733 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } break; // 5DS / 5DS R / 80D / 1300D / 5D4 / 800D / 77D / 6D II / 200D case 1560: case 1592: case 1353: case 1602: imgdata.makernotes.canon.CanonColorDataVer = 8; imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek(ifp, save1 + (0x44 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x49 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x85 << 1), SEEK_SET); Canon_WBpresets(2, 12); fseek(ifp, save1 + (0x107 << 1), SEEK_SET); Canon_WBCTpresets(0); // BCAT fseek(ifp, save1 + (0x146 << 1), SEEK_SET); // offset 326 shorts int bls = 0; FORC4 bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2()); imgdata.makernotes.canon.AverageBlackLevel = bls / 4; } if (imgdata.makernotes.canon.CanonColorDataSubVer == 14) // 1300D { fseek(ifp, save1 + (0x231 << 1), SEEK_SET); imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else { fseek(ifp, save1 + (0x30f << 1), SEEK_SET); // offset 783 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } break; } fseek(ifp, save1, SEEK_SET); } } void CLASS setPentaxBodyFeatures(unsigned id) { imgdata.lens.makernotes.CamID = id; switch (id) { case 0x12994: case 0x12aa2: case 0x12b1a: case 0x12b60: case 0x12b62: case 0x12b7e: case 0x12b80: case 0x12b9c: case 0x12b9d: case 0x12ba2: case 0x12c1e: case 0x12c20: case 0x12cd2: case 0x12cd4: case 0x12cfa: case 0x12d72: case 0x12d73: case 0x12db8: case 0x12dfe: case 0x12e6c: case 0x12e76: case 0x12ef8: case 0x12f52: case 0x12f70: case 0x12f71: case 0x12fb6: case 0x12fc0: case 0x12fca: case 0x1301a: case 0x13024: case 0x1309c: case 0x13222: case 0x1322c: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; break; case 0x13092: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; break; case 0x12e08: case 0x13010: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_645; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_MF; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_645; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_MF; break; case 0x12ee4: case 0x12f66: case 0x12f7a: case 0x1302e: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_Q; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_Q; break; default: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } return; } void CLASS PentaxISO(ushort c) { int code[] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 50, 100, 200, 400, 800, 1600, 3200, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278}; double value[] = {50, 64, 80, 100, 125, 160, 200, 250, 320, 400, 500, 640, 800, 1000, 1250, 1600, 2000, 2500, 3200, 4000, 5000, 6400, 8000, 10000, 12800, 16000, 20000, 25600, 32000, 40000, 51200, 64000, 80000, 102400, 128000, 160000, 204800, 258000, 325000, 409600, 516000, 650000, 819200, 50, 100, 200, 400, 800, 1600, 3200, 50, 70, 100, 140, 200, 280, 400, 560, 800, 1100, 1600, 2200, 3200, 4500, 6400, 9000, 12800, 18000, 25600, 36000, 51200}; #define numel (sizeof(code) / sizeof(code[0])) int i; for (i = 0; i < numel; i++) { if (code[i] == c) { iso_speed = value[i]; return; } } if (i == numel) iso_speed = 65535.0f; } #undef numel void CLASS PentaxLensInfo(unsigned id, unsigned len) // tag 0x0207 { ushort iLensData = 0; uchar *table_buf; table_buf = (uchar *)malloc(MAX(len, 128)); fread(table_buf, len, 1, ifp); if ((id < 0x12b9c) || (((id == 0x12b9c) || // K100D (id == 0x12b9d) || // K110D (id == 0x12ba2)) && // K100D Super ((!table_buf[20] || (table_buf[20] == 0xff))))) { iLensData = 3; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = (((unsigned)table_buf[0]) << 8) + table_buf[1]; } else switch (len) { case 90: // LensInfo3 iLensData = 13; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[3]) << 8) + table_buf[4]; break; case 91: // LensInfo4 iLensData = 12; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[3]) << 8) + table_buf[4]; break; case 80: // LensInfo5 case 128: iLensData = 15; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[4]) << 8) + table_buf[5]; break; default: if (id >= 0x12b9c) // LensInfo2 { iLensData = 4; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[0] & 0x0f) + table_buf[2]) << 8) + table_buf[3]; } } if (iLensData) { if (table_buf[iLensData + 9] && (fabs(imgdata.lens.makernotes.CurFocal) < 0.1f)) imgdata.lens.makernotes.CurFocal = 10 * (table_buf[iLensData + 9] >> 2) * powf64(4, (table_buf[iLensData + 9] & 0x03) - 2); if (table_buf[iLensData + 10] & 0xf0) imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (float)((table_buf[iLensData + 10] & 0xf0) >> 4) / 4.0f); if (table_buf[iLensData + 10] & 0x0f) imgdata.lens.makernotes.MinAp4CurFocal = powf64(2.0f, (float)((table_buf[iLensData + 10] & 0x0f) + 10) / 4.0f); if (iLensData != 12) { switch (table_buf[iLensData] & 0x06) { case 0: imgdata.lens.makernotes.MinAp4MinFocal = 22.0f; break; case 2: imgdata.lens.makernotes.MinAp4MinFocal = 32.0f; break; case 4: imgdata.lens.makernotes.MinAp4MinFocal = 45.0f; break; case 6: imgdata.lens.makernotes.MinAp4MinFocal = 16.0f; break; } if (table_buf[iLensData] & 0x70) imgdata.lens.makernotes.LensFStops = ((float)(((table_buf[iLensData] & 0x70) >> 4) ^ 0x07)) / 2.0f + 5.0f; imgdata.lens.makernotes.MinFocusDistance = (float)(table_buf[iLensData + 3] & 0xf8); imgdata.lens.makernotes.FocusRangeIndex = (float)(table_buf[iLensData + 3] & 0x07); if ((table_buf[iLensData + 14] > 1) && (fabs(imgdata.lens.makernotes.MaxAp4CurFocal) < 0.7f)) imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (float)((table_buf[iLensData + 14] & 0x7f) - 1) / 32.0f); } else if ((id != 0x12e76) && // K-5 (table_buf[iLensData + 15] > 1) && (fabs(imgdata.lens.makernotes.MaxAp4CurFocal) < 0.7f)) { imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (float)((table_buf[iLensData + 15] & 0x7f) - 1) / 32.0f); } } free(table_buf); return; } void CLASS setPhaseOneFeatures(unsigned id) { ushort i; static const struct { ushort id; char t_model[32]; } p1_unique[] = { // Phase One section: {1, "Hasselblad V"}, {10, "PhaseOne/Mamiya"}, {12, "Contax 645"}, {16, "Hasselblad V"}, {17, "Hasselblad V"}, {18, "Contax 645"}, {19, "PhaseOne/Mamiya"}, {20, "Hasselblad V"}, {21, "Contax 645"}, {22, "PhaseOne/Mamiya"}, {23, "Hasselblad V"}, {24, "Hasselblad H"}, {25, "PhaseOne/Mamiya"}, {32, "Contax 645"}, {34, "Hasselblad V"}, {35, "Hasselblad V"}, {36, "Hasselblad H"}, {37, "Contax 645"}, {38, "PhaseOne/Mamiya"}, {39, "Hasselblad V"}, {40, "Hasselblad H"}, {41, "Contax 645"}, {42, "PhaseOne/Mamiya"}, {44, "Hasselblad V"}, {45, "Hasselblad H"}, {46, "Contax 645"}, {47, "PhaseOne/Mamiya"}, {48, "Hasselblad V"}, {49, "Hasselblad H"}, {50, "Contax 645"}, {51, "PhaseOne/Mamiya"}, {52, "Hasselblad V"}, {53, "Hasselblad H"}, {54, "Contax 645"}, {55, "PhaseOne/Mamiya"}, {67, "Hasselblad V"}, {68, "Hasselblad H"}, {69, "Contax 645"}, {70, "PhaseOne/Mamiya"}, {71, "Hasselblad V"}, {72, "Hasselblad H"}, {73, "Contax 645"}, {74, "PhaseOne/Mamiya"}, {76, "Hasselblad V"}, {77, "Hasselblad H"}, {78, "Contax 645"}, {79, "PhaseOne/Mamiya"}, {80, "Hasselblad V"}, {81, "Hasselblad H"}, {82, "Contax 645"}, {83, "PhaseOne/Mamiya"}, {84, "Hasselblad V"}, {85, "Hasselblad H"}, {86, "Contax 645"}, {87, "PhaseOne/Mamiya"}, {99, "Hasselblad V"}, {100, "Hasselblad H"}, {101, "Contax 645"}, {102, "PhaseOne/Mamiya"}, {103, "Hasselblad V"}, {104, "Hasselblad H"}, {105, "PhaseOne/Mamiya"}, {106, "Contax 645"}, {112, "Hasselblad V"}, {113, "Hasselblad H"}, {114, "Contax 645"}, {115, "PhaseOne/Mamiya"}, {131, "Hasselblad V"}, {132, "Hasselblad H"}, {133, "Contax 645"}, {134, "PhaseOne/Mamiya"}, {135, "Hasselblad V"}, {136, "Hasselblad H"}, {137, "Contax 645"}, {138, "PhaseOne/Mamiya"}, {140, "Hasselblad V"}, {141, "Hasselblad H"}, {142, "Contax 645"}, {143, "PhaseOne/Mamiya"}, {148, "Hasselblad V"}, {149, "Hasselblad H"}, {150, "Contax 645"}, {151, "PhaseOne/Mamiya"}, {160, "A-250"}, {161, "A-260"}, {162, "A-280"}, {167, "Hasselblad V"}, {168, "Hasselblad H"}, {169, "Contax 645"}, {170, "PhaseOne/Mamiya"}, {172, "Hasselblad V"}, {173, "Hasselblad H"}, {174, "Contax 645"}, {175, "PhaseOne/Mamiya"}, {176, "Hasselblad V"}, {177, "Hasselblad H"}, {178, "Contax 645"}, {179, "PhaseOne/Mamiya"}, {180, "Hasselblad V"}, {181, "Hasselblad H"}, {182, "Contax 645"}, {183, "PhaseOne/Mamiya"}, {208, "Hasselblad V"}, {211, "PhaseOne/Mamiya"}, {448, "Phase One 645AF"}, {457, "Phase One 645DF"}, {471, "Phase One 645DF+"}, {704, "Phase One iXA"}, {705, "Phase One iXA - R"}, {706, "Phase One iXU 150"}, {707, "Phase One iXU 150 - NIR"}, {708, "Phase One iXU 180"}, {721, "Phase One iXR"}, // Leaf section: {333, "Mamiya"}, {329, "Universal"}, {330, "Hasselblad H1/H2"}, {332, "Contax"}, {336, "AFi"}, {327, "Mamiya"}, {324, "Universal"}, {325, "Hasselblad H1/H2"}, {326, "Contax"}, {335, "AFi"}, {340, "Mamiya"}, {337, "Universal"}, {338, "Hasselblad H1/H2"}, {339, "Contax"}, {323, "Mamiya"}, {320, "Universal"}, {322, "Hasselblad H1/H2"}, {321, "Contax"}, {334, "AFi"}, {369, "Universal"}, {370, "Mamiya"}, {371, "Hasselblad H1/H2"}, {372, "Contax"}, {373, "Afi"}, }; imgdata.lens.makernotes.CamID = id; if (id && !imgdata.lens.makernotes.body[0]) { for (i = 0; i < sizeof p1_unique / sizeof *p1_unique; i++) if (id == p1_unique[i].id) { strcpy(imgdata.lens.makernotes.body, p1_unique[i].t_model); } } return; } void CLASS parseFujiMakernotes(unsigned tag, unsigned type) { switch (tag) { case 0x1002: imgdata.makernotes.fuji.WB_Preset = get2(); break; case 0x1011: imgdata.other.FlashEC = getreal(type); break; case 0x1020: imgdata.makernotes.fuji.Macro = get2(); break; case 0x1021: imgdata.makernotes.fuji.FocusMode = get2(); break; case 0x1022: imgdata.makernotes.fuji.AFMode = get2(); break; case 0x1023: imgdata.makernotes.fuji.FocusPixel[0] = get2(); imgdata.makernotes.fuji.FocusPixel[1] = get2(); break; case 0x1034: imgdata.makernotes.fuji.ExrMode = get2(); break; case 0x1050: imgdata.makernotes.fuji.ShutterType = get2(); break; case 0x1400: imgdata.makernotes.fuji.FujiDynamicRange = get2(); break; case 0x1401: imgdata.makernotes.fuji.FujiFilmMode = get2(); break; case 0x1402: imgdata.makernotes.fuji.FujiDynamicRangeSetting = get2(); break; case 0x1403: imgdata.makernotes.fuji.FujiDevelopmentDynamicRange = get2(); break; case 0x140b: imgdata.makernotes.fuji.FujiAutoDynamicRange = get2(); break; case 0x1404: imgdata.lens.makernotes.MinFocal = getreal(type); break; case 0x1405: imgdata.lens.makernotes.MaxFocal = getreal(type); break; case 0x1406: imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); break; case 0x1407: imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); break; case 0x1422: imgdata.makernotes.fuji.ImageStabilization[0] = get2(); imgdata.makernotes.fuji.ImageStabilization[1] = get2(); imgdata.makernotes.fuji.ImageStabilization[2] = get2(); imgdata.shootinginfo.ImageStabilization = (imgdata.makernotes.fuji.ImageStabilization[0] << 9) + imgdata.makernotes.fuji.ImageStabilization[1]; break; case 0x1431: imgdata.makernotes.fuji.Rating = get4(); break; case 0x3820: imgdata.makernotes.fuji.FrameRate = get2(); break; case 0x3821: imgdata.makernotes.fuji.FrameWidth = get2(); break; case 0x3822: imgdata.makernotes.fuji.FrameHeight = get2(); break; } return; } void CLASS setSonyBodyFeatures(unsigned id) { imgdata.lens.makernotes.CamID = id; if ( // FF cameras (id == 257) || // a900 (id == 269) || // a850 (id == 340) || // ILCE-7M2 (id == 318) || // ILCE-7S (id == 350) || // ILCE-7SM2 (id == 311) || // ILCE-7R (id == 347) || // ILCE-7RM2 (id == 306) || // ILCE-7 (id == 298) || // DSC-RX1 (id == 299) || // NEX-VG900 (id == 310) || // DSC-RX1R (id == 344) || // DSC-RX1RM2 (id == 354) || // ILCA-99M2 (id == 358) || // ILCE-9 (id == 294) // SLT-99, Hasselblad HV ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; } else if ((id == 297) || // DSC-RX100 (id == 308) || // DSC-RX100M2 (id == 309) || // DSC-RX10 (id == 317) || // DSC-RX100M3 (id == 341) || // DSC-RX100M4 (id == 342) || // DSC-RX10M2 (id == 355) || // DSC-RX10M3 (id == 356) // DSC-RX100M5 ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_1INCH; } else if (id != 002) // DSC-R1 { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; } if ( // E-mount cameras, ILCE series (id == 302) || (id == 306) || (id == 311) || (id == 312) || (id == 313) || (id == 318) || (id == 339) || (id == 340) || (id == 346) || (id == 347) || (id == 350) || (id == 360) || (id == 358)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Sony_E; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_ILCE; } else if ( // E-mount cameras, NEX series (id == 278) || (id == 279) || (id == 284) || (id == 288) || (id == 289) || (id == 290) || (id == 293) || (id == 295) || (id == 296) || (id == 299) || (id == 300) || (id == 305) || (id == 307)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Sony_E; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_NEX; } else if ( // A-mount cameras, DSLR series (id == 256) || (id == 257) || (id == 258) || (id == 259) || (id == 260) || (id == 261) || (id == 262) || (id == 263) || (id == 264) || (id == 265) || (id == 266) || (id == 269) || (id == 270) || (id == 273) || (id == 274) || (id == 275) || (id == 282) || (id == 283)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_DSLR; } else if ( // A-mount cameras, SLT series (id == 280) || (id == 281) || (id == 285) || (id == 286) || (id == 287) || (id == 291) || (id == 292) || (id == 294) || (id == 303)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_SLT; } else if ( // A-mount cameras, ILCA series (id == 319) || (id == 353) || (id == 354)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_ILCA; } else if ( // DSC (id == 002) || // DSC-R1 (id == 297) || // DSC-RX100 (id == 298) || // DSC-RX1 (id == 308) || // DSC-RX100M2 (id == 309) || // DSC-RX10 (id == 310) || // DSC-RX1R (id == 344) || // DSC-RX1RM2 (id == 317) || // DSC-RX100M3 (id == 341) || // DSC-RX100M4 (id == 342) || // DSC-RX10M2 (id == 355) || // DSC-RX10M3 (id == 356) // DSC-RX100M5 ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_DSC; } return; } void CLASS parseSonyLensType2(uchar a, uchar b) { ushort lid2; lid2 = (((ushort)a) << 8) | ((ushort)b); if (!lid2) return; if (lid2 < 0x100) { if ((imgdata.lens.makernotes.AdapterID != 0x4900) && (imgdata.lens.makernotes.AdapterID != 0xEF00)) { imgdata.lens.makernotes.AdapterID = lid2; switch (lid2) { case 1: case 2: case 3: case 6: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 44: case 78: case 239: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; break; } } } else imgdata.lens.makernotes.LensID = lid2; if ((lid2 >= 50481) && (lid2 < 50500)) { strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); imgdata.lens.makernotes.AdapterID = 0x4900; } return; } #define strnXcat(buf, string) strncat(buf, string, LIM(sizeof(buf) - strbuflen(buf) - 1, 0, sizeof(buf))) void CLASS parseSonyLensFeatures(uchar a, uchar b) { ushort features; features = (((ushort)a) << 8) | ((ushort)b); if ((imgdata.lens.makernotes.LensMount == LIBRAW_MOUNT_Canon_EF) || (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F) || !features) return; imgdata.lens.makernotes.LensFeatures_pre[0] = 0; imgdata.lens.makernotes.LensFeatures_suf[0] = 0; if ((features & 0x0200) && (features & 0x0100)) strcpy(imgdata.lens.makernotes.LensFeatures_pre, "E"); else if (features & 0x0200) strcpy(imgdata.lens.makernotes.LensFeatures_pre, "FE"); else if (features & 0x0100) strcpy(imgdata.lens.makernotes.LensFeatures_pre, "DT"); if (!imgdata.lens.makernotes.LensFormat && !imgdata.lens.makernotes.LensMount) { imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FF; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; if ((features & 0x0200) && (features & 0x0100)) { imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; } else if (features & 0x0200) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; } else if (features & 0x0100) { imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC; } } if (features & 0x4000) strnXcat(imgdata.lens.makernotes.LensFeatures_pre, " PZ"); if (features & 0x0008) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " G"); else if (features & 0x0004) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " ZA"); if ((features & 0x0020) && (features & 0x0040)) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Macro"); else if (features & 0x0020) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " STF"); else if (features & 0x0040) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Reflex"); else if (features & 0x0080) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Fisheye"); if (features & 0x0001) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " SSM"); else if (features & 0x0002) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " SAM"); if (features & 0x8000) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " OSS"); if (features & 0x2000) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " LE"); if (features & 0x0800) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " II"); if (imgdata.lens.makernotes.LensFeatures_suf[0] == ' ') memmove(imgdata.lens.makernotes.LensFeatures_suf, imgdata.lens.makernotes.LensFeatures_suf + 1, strbuflen(imgdata.lens.makernotes.LensFeatures_suf) - 1); return; } #undef strnXcat void CLASS process_Sony_0x940c(uchar *buf) { ushort lid2; if ((imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) && (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F)) { switch (SonySubstitution[buf[0x0008]]) { case 1: case 5: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 4: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; break; } } lid2 = (((ushort)SonySubstitution[buf[0x000a]]) << 8) | ((ushort)SonySubstitution[buf[0x0009]]); if ((lid2 > 0) && (lid2 < 32784)) parseSonyLensType2(SonySubstitution[buf[0x000a]], // LensType2 - Sony lens ids SonySubstitution[buf[0x0009]]); return; } void CLASS process_Sony_0x9050(uchar *buf, unsigned id) { ushort lid; if ((imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_Sony_E) && (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens)) { if (buf[0]) imgdata.lens.makernotes.MaxAp4CurFocal = my_roundf(powf64(2.0f, ((float)SonySubstitution[buf[0]] / 8.0 - 1.06f) / 2.0f) * 10.0f) / 10.0f; if (buf[1]) imgdata.lens.makernotes.MinAp4CurFocal = my_roundf(powf64(2.0f, ((float)SonySubstitution[buf[1]] / 8.0 - 1.06f) / 2.0f) * 10.0f) / 10.0f; } if (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens) { if (buf[0x3d] | buf[0x3c]) { lid = SonySubstitution[buf[0x3d]] << 8 | SonySubstitution[buf[0x3c]]; imgdata.lens.makernotes.CurAp = powf64(2.0f, ((float)lid / 256.0f - 16.0f) / 2.0f); } if (buf[0x105] && (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) && (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F)) imgdata.lens.makernotes.LensMount = SonySubstitution[buf[0x105]]; if (buf[0x106]) imgdata.lens.makernotes.LensFormat = SonySubstitution[buf[0x106]]; } if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) { parseSonyLensType2(SonySubstitution[buf[0x0108]], // LensType2 - Sony lens ids SonySubstitution[buf[0x0107]]); } if ((imgdata.lens.makernotes.LensID == -1) && (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Minolta_A) && (buf[0x010a] | buf[0x0109])) { imgdata.lens.makernotes.LensID = // LensType - Minolta/Sony lens ids SonySubstitution[buf[0x010a]] << 8 | SonySubstitution[buf[0x0109]]; if ((imgdata.lens.makernotes.LensID > 0x4900) && (imgdata.lens.makernotes.LensID <= 0x5900)) { imgdata.lens.makernotes.AdapterID = 0x4900; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sigma_X3F; strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); } else if ((imgdata.lens.makernotes.LensID > 0xEF00) && (imgdata.lens.makernotes.LensID < 0xFFFF) && (imgdata.lens.makernotes.LensID != 0xFF00)) { imgdata.lens.makernotes.AdapterID = 0xEF00; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; } } if ((id >= 286) && (id <= 293)) // "SLT-A65", "SLT-A77", "NEX-7", "NEX-VG20E", // "SLT-A37", "SLT-A57", "NEX-F3", "Lunar" parseSonyLensFeatures(SonySubstitution[buf[0x115]], SonySubstitution[buf[0x116]]); else if (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens) parseSonyLensFeatures(SonySubstitution[buf[0x116]], SonySubstitution[buf[0x117]]); if ((id == 347) || (id == 350) || (id == 357)) { unsigned long long b88 = SonySubstitution[buf[0x88]]; unsigned long long b89 = SonySubstitution[buf[0x89]]; unsigned long long b8a = SonySubstitution[buf[0x8a]]; unsigned long long b8b = SonySubstitution[buf[0x8b]]; unsigned long long b8c = SonySubstitution[buf[0x8c]]; unsigned long long b8d = SonySubstitution[buf[0x8d]]; sprintf(imgdata.shootinginfo.InternalBodySerial, "%06llx", (b88 << 40) + (b89 << 32) + (b8a << 24) + (b8b << 16) + (b8c << 8) + b8d); } else if ((imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Minolta_A) && (id > 279) && (id != 282) && (id != 283)) { unsigned long long bf0 = SonySubstitution[buf[0xf0]]; unsigned long long bf1 = SonySubstitution[buf[0xf1]]; unsigned long long bf2 = SonySubstitution[buf[0xf2]]; unsigned long long bf3 = SonySubstitution[buf[0xf3]]; unsigned long long bf4 = SonySubstitution[buf[0xf4]]; sprintf(imgdata.shootinginfo.InternalBodySerial, "%05llx", (bf0 << 32) + (bf1 << 24) + (bf2 << 16) + (bf3 << 8) + bf4); } else if ((imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) && (id != 288) && (id != 289) && (id != 290)) { unsigned b7c = SonySubstitution[buf[0x7c]]; unsigned b7d = SonySubstitution[buf[0x7d]]; unsigned b7e = SonySubstitution[buf[0x7e]]; unsigned b7f = SonySubstitution[buf[0x7f]]; sprintf(imgdata.shootinginfo.InternalBodySerial, "%04x", (b7c << 24) + (b7d << 16) + (b7e << 8) + b7f); } return; } void CLASS parseSonyMakernotes(unsigned tag, unsigned type, unsigned len, unsigned dng_writer, uchar *&table_buf_0x9050, ushort &table_buf_0x9050_present, uchar *&table_buf_0x940c, ushort &table_buf_0x940c_present) { ushort lid; uchar *table_buf; if (tag == 0xb001) // Sony ModelID { unique_id = get2(); setSonyBodyFeatures(unique_id); if (table_buf_0x9050_present) { process_Sony_0x9050(table_buf_0x9050, unique_id); free(table_buf_0x9050); table_buf_0x9050_present = 0; } if (table_buf_0x940c_present) { if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) { process_Sony_0x940c(table_buf_0x940c); } free(table_buf_0x940c); table_buf_0x940c_present = 0; } } else if ((tag == 0x0010) && // CameraInfo strncasecmp(model, "DSLR-A100", 9) && strncasecmp(model, "NEX-5C", 6) && !strncasecmp(make, "SONY", 4) && ((len == 368) || // a700 (len == 5478) || // a850, a900 (len == 5506) || // a200, a300, a350 (len == 6118) || // a230, a290, a330, a380, a390 // a450, a500, a550, a560, a580 // a33, a35, a55 // NEX3, NEX5, NEX5C, NEXC3, VG10E (len == 15360))) { table_buf = (uchar *)malloc(len); fread(table_buf, len, 1, ifp); if (memcmp(table_buf, "\xff\xff\xff\xff\xff\xff\xff\xff", 8) && memcmp(table_buf, "\x00\x00\x00\x00\x00\x00\x00\x00", 8)) { switch (len) { case 368: case 5478: // a700, a850, a900: CameraInfo if ((!dng_writer) || (saneSonyCameraInfo(table_buf[0], table_buf[3], table_buf[2], table_buf[5], table_buf[4], table_buf[7]))) { if (table_buf[0] | table_buf[3]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[0]) * 100 + bcd2dec(table_buf[3]); if (table_buf[2] | table_buf[5]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[2]) * 100 + bcd2dec(table_buf[5]); if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[4]) / 10.0f; if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[7]) / 10.0f; parseSonyLensFeatures(table_buf[1], table_buf[6]); } break; default: // CameraInfo2 & 3 if ((!dng_writer) || (saneSonyCameraInfo(table_buf[1], table_buf[2], table_buf[3], table_buf[4], table_buf[5], table_buf[6]))) { if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); } } } free(table_buf); } else if ((!dng_writer) && (tag == 0x0020) && // WBInfoA100, needs 0xb028 processing !strncasecmp(model, "DSLR-A100", 9)) { fseek(ifp, 0x49dc, SEEK_CUR); stmread(imgdata.shootinginfo.InternalBodySerial, 12, ifp); } else if (tag == 0x0104) { imgdata.other.FlashEC = getreal(type); } else if (tag == 0x0105) // Teleconverter { imgdata.lens.makernotes.TeleconverterID = get2(); } else if (tag == 0x0114 && len < 256000) // CameraSettings { table_buf = (uchar *)malloc(len); fread(table_buf, len, 1, ifp); switch (len) { case 280: case 364: case 332: // CameraSettings and CameraSettings2 are big endian if (table_buf[2] | table_buf[3]) { lid = (((ushort)table_buf[2]) << 8) | ((ushort)table_buf[3]); imgdata.lens.makernotes.CurAp = powf64(2.0f, ((float)lid / 8.0f - 1.0f) / 2.0f); } break; case 1536: case 2048: // CameraSettings3 are little endian parseSonyLensType2(table_buf[1016], table_buf[1015]); if (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) { switch (table_buf[153]) { case 16: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 17: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; break; } } break; } free(table_buf); } else if (tag == 0x9050 && len < 256000) // little endian { table_buf_0x9050 = (uchar *)malloc(len); table_buf_0x9050_present = 1; fread(table_buf_0x9050, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x9050(table_buf_0x9050, imgdata.lens.makernotes.CamID); free(table_buf_0x9050); table_buf_0x9050_present = 0; } } else if (tag == 0x940c && len < 256000) { table_buf_0x940c = (uchar *)malloc(len); table_buf_0x940c_present = 1; fread(table_buf_0x940c, len, 1, ifp); if ((imgdata.lens.makernotes.CamID) && (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E)) { process_Sony_0x940c(table_buf_0x940c); free(table_buf_0x940c); table_buf_0x940c_present = 0; } } else if (((tag == 0xb027) || (tag == 0x010c)) && (imgdata.lens.makernotes.LensID == -1)) { imgdata.lens.makernotes.LensID = get4(); if ((imgdata.lens.makernotes.LensID > 0x4900) && (imgdata.lens.makernotes.LensID <= 0x5900)) { imgdata.lens.makernotes.AdapterID = 0x4900; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sigma_X3F; strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); } else if ((imgdata.lens.makernotes.LensID > 0xEF00) && (imgdata.lens.makernotes.LensID < 0xFFFF) && (imgdata.lens.makernotes.LensID != 0xFF00)) { imgdata.lens.makernotes.AdapterID = 0xEF00; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; } if (tag == 0x010c) imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; } else if (tag == 0xb02a && len < 256000) // Sony LensSpec { table_buf = (uchar *)malloc(len); fread(table_buf, len, 1, ifp); if ((!dng_writer) || (saneSonyCameraInfo(table_buf[1], table_buf[2], table_buf[3], table_buf[4], table_buf[5], table_buf[6]))) { if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); } free(table_buf); } } void CLASS parse_makernote_0xc634(int base, int uptag, unsigned dng_writer) { unsigned ver97 = 0, offset = 0, entries, tag, type, len, save, c; unsigned i; uchar NikonKey, ci, cj, ck; unsigned serial = 0; unsigned custom_serial = 0; unsigned NikonLensDataVersion = 0; unsigned lenNikonLensData = 0; unsigned NikonFlashInfoVersion = 0; uchar *CanonCameraInfo; unsigned lenCanonCameraInfo = 0; uchar *table_buf; uchar *table_buf_0x9050; ushort table_buf_0x9050_present = 0; uchar *table_buf_0x940c; ushort table_buf_0x940c_present = 0; short morder, sorder = order; char buf[10]; INT64 fsize = ifp->size(); fread(buf, 1, 10, ifp); if (!strcmp(buf, "Nikon")) { base = ftell(ifp); order = get2(); if (get2() != 42) goto quit; offset = get4(); fseek(ifp, offset - 8, SEEK_CUR); } else if (!strcmp(buf, "OLYMPUS") || !strcmp(buf, "PENTAX ") || (!strncmp(make, "SAMSUNG", 7) && (dng_writer == CameraDNG))) { base = ftell(ifp) - 10; fseek(ifp, -2, SEEK_CUR); order = get2(); if (buf[0] == 'O') get2(); } else if (!strncmp(buf, "SONY", 4) || !strcmp(buf, "Panasonic")) { goto nf; } else if (!strncmp(buf, "FUJIFILM", 8)) { base = ftell(ifp) - 10; nf: order = 0x4949; fseek(ifp, 2, SEEK_CUR); } else if (!strcmp(buf, "OLYMP") || !strcmp(buf, "LEICA") || !strcmp(buf, "Ricoh") || !strcmp(buf, "EPSON")) fseek(ifp, -2, SEEK_CUR); else if (!strcmp(buf, "AOC") || !strcmp(buf, "QVC")) fseek(ifp, -4, SEEK_CUR); else { fseek(ifp, -10, SEEK_CUR); if ((!strncmp(make, "SAMSUNG", 7) && (dng_writer == AdobeDNG))) base = ftell(ifp); } entries = get2(); if (entries > 1000) return; morder = order; while (entries--) { order = morder; tiff_get(base, &tag, &type, &len, &save); INT64 pos = ifp->tell(); if (len > 8 && pos + len > 2 * fsize) continue; tag |= uptag << 16; if (len > 100 * 1024 * 1024) goto next; // 100Mb tag? No! if (!strncmp(make, "Canon", 5)) { if (tag == 0x000d && len < 256000) // camera info { CanonCameraInfo = (uchar *)malloc(len); fread(CanonCameraInfo, len, 1, ifp); lenCanonCameraInfo = len; } else if (tag == 0x10) // Canon ModelID { unique_id = get4(); if (unique_id == 0x03740000) // EOS M3 unique_id = 0x80000374; else if (unique_id == 0x03840000) // EOS M10 unique_id = 0x80000384; else if (unique_id == 0x03940000) // EOS M5 unique_id = 0x80000394; else if (unique_id == 0x04070000) // EOS M6 unique_id = 0x80000407; setCanonBodyFeatures(unique_id); if (lenCanonCameraInfo) { processCanonCameraInfo(unique_id, CanonCameraInfo, lenCanonCameraInfo); free(CanonCameraInfo); CanonCameraInfo = 0; lenCanonCameraInfo = 0; } } else parseCanonMakernotes(tag, type, len); } else if (!strncmp(make, "FUJI", 4)) parseFujiMakernotes(tag, type); else if (!strncasecmp(make, "LEICA", 5)) { if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9)) { int ind = tag == 0x035e ? 0 : 1; for (int j = 0; j < 3; j++) FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c] = getreal(type); imgdata.color.dng_color[ind].parsedfields |= LIBRAW_DNGFM_FORWARDMATRIX; } if ((tag == 0x0303) && (type != 4)) { stmread(imgdata.lens.makernotes.Lens, len, ifp); } if ((tag == 0x3405) || (tag == 0x0310) || (tag == 0x34003405)) { imgdata.lens.makernotes.LensID = get4(); imgdata.lens.makernotes.LensID = ((imgdata.lens.makernotes.LensID >> 2) << 8) | (imgdata.lens.makernotes.LensID & 0x3); if (imgdata.lens.makernotes.LensID != -1) { if ((model[0] == 'M') || !strncasecmp(model, "LEICA M", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M; } else if ((model[0] == 'S') || !strncasecmp(model, "LEICA S", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S; } } } else if (((tag == 0x0313) || (tag == 0x34003406)) && (fabs(imgdata.lens.makernotes.CurAp) < 0.17f) && ((type == 10) || (type == 5))) { imgdata.lens.makernotes.CurAp = getreal(type); if (imgdata.lens.makernotes.CurAp > 126.3) imgdata.lens.makernotes.CurAp = 0.0f; } else if (tag == 0x3400) { parse_makernote(base, 0x3400); } } else if (!strncmp(make, "NIKON", 5)) { if (tag == 0x1d) // serial number while ((c = fgetc(ifp)) && c != EOF) { if ((!custom_serial) && (!isdigit(c))) { if ((strbuflen(model) == 3) && (!strcmp(model, "D50"))) { custom_serial = 34; } else { custom_serial = 96; } } serial = serial * 10 + (isdigit(c) ? c - '0' : c % 10); } else if (tag == 0x000a) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } else if (tag == 0x0082) // lens attachment { stmread(imgdata.lens.makernotes.Attachment, len, ifp); } else if (tag == 0x0083) // lens type { imgdata.lens.nikon.NikonLensType = fgetc(ifp); } else if (tag == 0x0084) // lens { imgdata.lens.makernotes.MinFocal = getreal(type); imgdata.lens.makernotes.MaxFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); } else if (tag == 0x008b) // lens f-stops { uchar a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) { imgdata.lens.nikon.NikonLensFStops = a * b * (12 / c); imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops / 12.0f; } } else if (tag == 0x0093) { imgdata.makernotes.nikon.NEFCompression = i = get2(); if ((i == 7) || (i == 9)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0097) { for (i = 0; i < 4; i++) ver97 = ver97 * 10 + fgetc(ifp) - '0'; if (ver97 == 601) // Coolpix A { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0098) // contains lens data { for (i = 0; i < 4; i++) { NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0'; } switch (NikonLensDataVersion) { case 100: lenNikonLensData = 9; break; case 101: case 201: // encrypted, starting from v.201 case 202: case 203: lenNikonLensData = 15; break; case 204: lenNikonLensData = 16; break; case 400: lenNikonLensData = 459; break; case 401: lenNikonLensData = 590; break; case 402: lenNikonLensData = 509; break; case 403: lenNikonLensData = 879; break; } if (lenNikonLensData) { table_buf = (uchar *)malloc(lenNikonLensData); fread(table_buf, lenNikonLensData, 1, ifp); if ((NikonLensDataVersion < 201) && lenNikonLensData) { processNikonLensData(table_buf, lenNikonLensData); free(table_buf); lenNikonLensData = 0; } } } else if (tag == 0xa7) // shutter count { NikonKey = fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp); if ((NikonLensDataVersion > 200) && lenNikonLensData) { if (custom_serial) { ci = xlat[0][custom_serial]; } else { ci = xlat[0][serial & 0xff]; } cj = xlat[1][NikonKey]; ck = 0x60; for (i = 0; i < lenNikonLensData; i++) table_buf[i] ^= (cj += ci * ck++); processNikonLensData(table_buf, lenNikonLensData); lenNikonLensData = 0; free(table_buf); } } else if (tag == 0x00a8) // contains flash data { for (i = 0; i < 4; i++) { NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0'; } } else if (tag == 37 && (!iso_speed || iso_speed == 65535)) { unsigned char cc; fread(&cc, 1, 1, ifp); iso_speed = (int)(100.0 * powf64(2.0, (double)(cc) / 12.0 - 5.0)); break; } } else if (!strncmp(make, "OLYMPUS", 7)) { int SubDirOffsetValid = strncmp(model, "E-300", 5) && strncmp(model, "E-330", 5) && strncmp(model, "E-400", 5) && strncmp(model, "E-500", 5) && strncmp(model, "E-1", 3); if ((tag == 0x2010) || (tag == 0x2020)) { fseek(ifp, save - 4, SEEK_SET); fseek(ifp, base + get4(), SEEK_SET); parse_makernote_0xc634(base, tag, dng_writer); } if (!SubDirOffsetValid && ((len > 4) || (((type == 3) || (type == 8)) && (len > 2)) || (((type == 4) || (type == 9)) && (len > 1)) || (type == 5) || (type > 9))) goto skip_Oly_broken_tags; switch (tag) { case 0x0207: case 0x20100100: { uchar sOlyID[8]; unsigned long long OlyID; fread(sOlyID, MIN(len, 7), 1, ifp); sOlyID[7] = 0; OlyID = sOlyID[0]; i = 1; while (i < 7 && sOlyID[i]) { OlyID = OlyID << 8 | sOlyID[i]; i++; } setOlympusBodyFeatures(OlyID); } break; case 0x1002: imgdata.lens.makernotes.CurAp = powf64(2.0f, getreal(type) / 2); break; case 0x20100102: stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp); break; case 0x20100201: imgdata.lens.makernotes.LensID = (unsigned long long)fgetc(ifp) << 16 | (unsigned long long)(fgetc(ifp), fgetc(ifp)) << 8 | (unsigned long long)fgetc(ifp); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FT; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FT; if (((imgdata.lens.makernotes.LensID < 0x20000) || (imgdata.lens.makernotes.LensID > 0x4ffff)) && (imgdata.lens.makernotes.LensID & 0x10)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_mFT; } break; case 0x20100202: if ((!imgdata.lens.LensSerial[0])) stmread(imgdata.lens.LensSerial, len, ifp); break; case 0x20100203: stmread(imgdata.lens.makernotes.Lens, len, ifp); break; case 0x20100205: imgdata.lens.makernotes.MaxAp4MinFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100206: imgdata.lens.makernotes.MaxAp4MaxFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100207: imgdata.lens.makernotes.MinFocal = (float)get2(); break; case 0x20100208: imgdata.lens.makernotes.MaxFocal = (float)get2(); if (imgdata.lens.makernotes.MaxFocal > 1000.0f) imgdata.lens.makernotes.MaxFocal = imgdata.lens.makernotes.MinFocal; break; case 0x2010020a: imgdata.lens.makernotes.MaxAp4CurFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100301: imgdata.lens.makernotes.TeleconverterID = fgetc(ifp) << 8; fgetc(ifp); imgdata.lens.makernotes.TeleconverterID = imgdata.lens.makernotes.TeleconverterID | fgetc(ifp); break; case 0x20100303: stmread(imgdata.lens.makernotes.Teleconverter, len, ifp); break; case 0x20100403: stmread(imgdata.lens.makernotes.Attachment, len, ifp); break; case 0x20200401: imgdata.other.FlashEC = getreal(type); break; } skip_Oly_broken_tags:; } else if (!strncmp(make, "PENTAX", 6) || !strncmp(model, "PENTAX", 6) || (!strncmp(make, "SAMSUNG", 7) && (dng_writer == CameraDNG))) { if (tag == 0x0005) { unique_id = get4(); setPentaxBodyFeatures(unique_id); } else if (tag == 0x0013) { imgdata.lens.makernotes.CurAp = (float)get2() / 10.0f; } else if (tag == 0x0014) { PentaxISO(get2()); } else if (tag == 0x001d) { imgdata.lens.makernotes.CurFocal = (float)get4() / 100.0f; } else if (tag == 0x003f) { imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp); } else if (tag == 0x004d) { if (type == 9) imgdata.other.FlashEC = getreal(type) / 256.0f; else imgdata.other.FlashEC = (float)((signed short)fgetc(ifp)) / 6.0f; } else if (tag == 0x007e) { imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = (long)(-1) * get4(); } else if (tag == 0x0207) { if (len < 65535) // Safety belt PentaxLensInfo(imgdata.lens.makernotes.CamID, len); } else if ((tag >= 0x020d) && (tag <= 0x0214)) { FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list1[tag - 0x020d]][c ^ (c >> 1)] = get2(); } else if (tag == 0x0221) { int nWB = get2(); if (nWB <= sizeof(imgdata.color.WBCT_Coeffs) / sizeof(imgdata.color.WBCT_Coeffs[0])) for (int i = 0; i < nWB; i++) { imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2(); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = get2(); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000; imgdata.color.WBCT_Coeffs[i][3] = get2(); } } else if (tag == 0x0215) { fseek(ifp, 16, SEEK_CUR); sprintf(imgdata.shootinginfo.InternalBodySerial, "%d", get4()); } else if (tag == 0x0229) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x022d) { int wb_ind; getc(ifp); for (int wb_cnt = 0; wb_cnt < nPentax_wb_list2; wb_cnt++) { wb_ind = getc(ifp); if (wb_ind < nPentax_wb_list2) FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list2[wb_ind]][c ^ (c >> 1)] = get2(); } } else if (tag == 0x0239) // Q-series lens info (LensInfoQ) { char LensInfo[20]; fseek(ifp, 12, SEEK_CUR); stread(imgdata.lens.makernotes.Lens, 30, ifp); strcat(imgdata.lens.makernotes.Lens, " "); stread(LensInfo, 20, ifp); strcat(imgdata.lens.makernotes.Lens, LensInfo); } } else if (!strncmp(make, "SAMSUNG", 7) && (dng_writer == AdobeDNG)) { if (tag == 0x0002) { if (get4() == 0x2000) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX; } else if (!strncmp(model, "NX mini", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0003) { imgdata.lens.makernotes.CamID = unique_id = get4(); } else if (tag == 0xa003) { imgdata.lens.makernotes.LensID = get2(); if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX; } else if (tag == 0xa005) { stmread(imgdata.lens.InternalLensSerial, len, ifp); } else if (tag == 0xa019) { imgdata.lens.makernotes.CurAp = getreal(type); } else if (tag == 0xa01a) { imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() / 10.0f; if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f) imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f; } } else if (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "Konica", 6) || !strncasecmp(make, "Minolta", 7) || (!strncasecmp(make, "Hasselblad", 10) && (!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) || !strncasecmp(model, "Lusso", 5) || !strncasecmp(model, "HV", 2)))) { parseSonyMakernotes(tag, type, len, AdobeDNG, table_buf_0x9050, table_buf_0x9050_present, table_buf_0x940c, table_buf_0x940c_present); } next: fseek(ifp, save, SEEK_SET); } quit: order = sorder; } #else void CLASS parse_makernote_0xc634(int base, int uptag, unsigned dng_writer) { /*placeholder */} #endif void CLASS parse_makernote(int base, int uptag) { unsigned offset = 0, entries, tag, type, len, save, c; unsigned ver97 = 0, serial = 0, i, wbi = 0, wb[4] = {0, 0, 0, 0}; uchar buf97[324], ci, cj, ck; short morder, sorder = order; char buf[10]; unsigned SamsungKey[11]; uchar NikonKey; #ifdef LIBRAW_LIBRARY_BUILD unsigned custom_serial = 0; unsigned NikonLensDataVersion = 0; unsigned lenNikonLensData = 0; unsigned NikonFlashInfoVersion = 0; uchar *CanonCameraInfo; unsigned lenCanonCameraInfo = 0; uchar *table_buf; uchar *table_buf_0x9050; ushort table_buf_0x9050_present = 0; uchar *table_buf_0x940c; ushort table_buf_0x940c_present = 0; INT64 fsize = ifp->size(); #endif /* The MakerNote might have its own TIFF header (possibly with its own byte-order!), or it might just be a table. */ if (!strncmp(make, "Nokia", 5)) return; fread(buf, 1, 10, ifp); if (!strncmp(buf, "KDK", 3) || /* these aren't TIFF tables */ !strncmp(buf, "VER", 3) || !strncmp(buf, "IIII", 4) || !strncmp(buf, "MMMM", 4)) return; if (!strncmp(buf, "KC", 2) || /* Konica KD-400Z, KD-510Z */ !strncmp(buf, "MLY", 3)) { /* Minolta DiMAGE G series */ order = 0x4d4d; while ((i = ftell(ifp)) < data_offset && i < 16384) { wb[0] = wb[2]; wb[2] = wb[1]; wb[1] = wb[3]; wb[3] = get2(); if (wb[1] == 256 && wb[3] == 256 && wb[0] > 256 && wb[0] < 640 && wb[2] > 256 && wb[2] < 640) FORC4 cam_mul[c] = wb[c]; } goto quit; } if (!strcmp(buf, "Nikon")) { base = ftell(ifp); order = get2(); if (get2() != 42) goto quit; offset = get4(); fseek(ifp, offset - 8, SEEK_CUR); } else if (!strcmp(buf, "OLYMPUS") || !strcmp(buf, "PENTAX ")) { base = ftell(ifp) - 10; fseek(ifp, -2, SEEK_CUR); order = get2(); if (buf[0] == 'O') get2(); } else if (!strncmp(buf, "SONY", 4) || !strcmp(buf, "Panasonic")) { goto nf; } else if (!strncmp(buf, "FUJIFILM", 8)) { base = ftell(ifp) - 10; nf: order = 0x4949; fseek(ifp, 2, SEEK_CUR); } else if (!strcmp(buf, "OLYMP") || !strcmp(buf, "LEICA") || !strcmp(buf, "Ricoh") || !strcmp(buf, "EPSON")) fseek(ifp, -2, SEEK_CUR); else if (!strcmp(buf, "AOC") || !strcmp(buf, "QVC")) fseek(ifp, -4, SEEK_CUR); else { fseek(ifp, -10, SEEK_CUR); if (!strncmp(make, "SAMSUNG", 7)) base = ftell(ifp); } // adjust pos & base for Leica M8/M9/M Mono tags and dir in tag 0x3400 if (!strncasecmp(make, "LEICA", 5)) { if (!strncmp(model, "M8", 2) || !strncasecmp(model, "Leica M8", 8) || !strncasecmp(model, "LEICA X", 7)) { base = ftell(ifp) - 8; } else if (!strncasecmp(model, "LEICA M (Typ 240)", 17)) { base = 0; } else if (!strncmp(model, "M9", 2) || !strncasecmp(model, "Leica M9", 8) || !strncasecmp(model, "M Monochrom", 11) || !strncasecmp(model, "Leica M Monochrom", 11)) { if (!uptag) { base = ftell(ifp) - 10; fseek(ifp, 8, SEEK_CUR); } else if (uptag == 0x3400) { fseek(ifp, 10, SEEK_CUR); base += 10; } } else if (!strncasecmp(model, "LEICA T", 7)) { base = ftell(ifp) - 8; #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_T; #endif } #ifdef LIBRAW_LIBRARY_BUILD else if (!strncasecmp(model, "LEICA SL", 8)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_SL; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; } #endif } entries = get2(); if (entries > 1000) return; morder = order; while (entries--) { order = morder; tiff_get(base, &tag, &type, &len, &save); tag |= uptag << 16; #ifdef LIBRAW_LIBRARY_BUILD INT64 _pos = ftell(ifp); if (len > 8 && _pos + len > 2 * fsize) continue; if (!strncmp(make, "Canon", 5)) { if (tag == 0x000d && len < 256000) // camera info { CanonCameraInfo = (uchar *)malloc(len); fread(CanonCameraInfo, len, 1, ifp); lenCanonCameraInfo = len; } else if (tag == 0x10) // Canon ModelID { unique_id = get4(); if (unique_id == 0x03740000) // EOS M3 unique_id = 0x80000374; else if (unique_id == 0x03840000) // EOS M10 unique_id = 0x80000384; else if (unique_id == 0x03940000) // EOS M5 unique_id = 0x80000394; else if (unique_id == 0x04070000) // EOS M6 unique_id = 0x80000407; setCanonBodyFeatures(unique_id); if (lenCanonCameraInfo) { processCanonCameraInfo(unique_id, CanonCameraInfo, lenCanonCameraInfo); free(CanonCameraInfo); CanonCameraInfo = 0; lenCanonCameraInfo = 0; } } else parseCanonMakernotes(tag, type, len); } else if (!strncmp(make, "FUJI", 4)) { if (tag == 0x0010) { char FujiSerial[sizeof(imgdata.shootinginfo.InternalBodySerial)]; char *words[4]; char yy[2], mm[3], dd[3], ystr[16], ynum[16]; int year, nwords, ynum_len; unsigned c; stmread(FujiSerial, len, ifp); nwords = getwords(FujiSerial, words, 4, sizeof(imgdata.shootinginfo.InternalBodySerial)); for (int i = 0; i < nwords; i++) { mm[2] = dd[2] = 0; if (strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) < 18) if (i == 0) strncpy(imgdata.shootinginfo.InternalBodySerial, words[0], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1); else { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; snprintf(tbuf, sizeof(tbuf), "%s %s", imgdata.shootinginfo.InternalBodySerial, words[i]); strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial) - 1); } else { strncpy(dd, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 14, 2); strncpy(mm, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 16, 2); strncpy(yy, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 18, 2); year = (yy[0] - '0') * 10 + (yy[1] - '0'); if (year < 70) year += 2000; else year += 1900; ynum_len = (int)strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 18; strncpy(ynum, words[i], ynum_len); ynum[ynum_len] = 0; for (int j = 0; ynum[j] && ynum[j + 1] && sscanf(ynum + j, "%2x", &c); j += 2) ystr[j / 2] = c; ystr[ynum_len / 2 + 1] = 0; strcpy(model2, ystr); if (i == 0) { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; if (nwords == 1) snprintf(tbuf, sizeof(tbuf), "%s %s %d:%s:%s", words[0] + strnlen(words[0], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12, ystr, year, mm, dd); else snprintf(tbuf, sizeof(tbuf), "%s %d:%s:%s %s", ystr, year, mm, dd, words[0] + strnlen(words[0], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12); strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial) - 1); } else { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; snprintf(tbuf, sizeof(tbuf), "%s %s %d:%s:%s %s", imgdata.shootinginfo.InternalBodySerial, ystr, year, mm, dd, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12); strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial) - 1); } } } } else parseFujiMakernotes(tag, type); } else if (!strncasecmp(model, "Hasselblad X1D", 14) || !strncasecmp(model, "Hasselblad H6D", 14)) { if (tag == 0x0045) { imgdata.makernotes.hasselblad.BaseISO = get4(); } else if (tag == 0x0046) { imgdata.makernotes.hasselblad.Gain = getreal(type); } } else if (!strncasecmp(make, "LEICA", 5)) { if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9)) { int ind = tag == 0x035e ? 0 : 1; for (int j = 0; j < 3; j++) FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c] = getreal(type); imgdata.color.dng_color[ind].parsedfields |= LIBRAW_DNGFM_FORWARDMATRIX; } if ((tag == 0x0303) && (type != 4)) { stmread(imgdata.lens.makernotes.Lens, len, ifp); } if ((tag == 0x3405) || (tag == 0x0310) || (tag == 0x34003405)) { imgdata.lens.makernotes.LensID = get4(); imgdata.lens.makernotes.LensID = ((imgdata.lens.makernotes.LensID >> 2) << 8) | (imgdata.lens.makernotes.LensID & 0x3); if (imgdata.lens.makernotes.LensID != -1) { if ((model[0] == 'M') || !strncasecmp(model, "LEICA M", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M; } else if ((model[0] == 'S') || !strncasecmp(model, "LEICA S", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S; } } } else if (((tag == 0x0313) || (tag == 0x34003406)) && (fabs(imgdata.lens.makernotes.CurAp) < 0.17f) && ((type == 10) || (type == 5))) { imgdata.lens.makernotes.CurAp = getreal(type); if (imgdata.lens.makernotes.CurAp > 126.3) imgdata.lens.makernotes.CurAp = 0.0f; } else if (tag == 0x3400) { parse_makernote(base, 0x3400); } } else if (!strncmp(make, "NIKON", 5)) { if (tag == 0x000a) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } else if (tag == 0x0012) { char a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) imgdata.other.FlashEC = (float)(a * b) / (float)c; } else if (tag == 0x0082) // lens attachment { stmread(imgdata.lens.makernotes.Attachment, len, ifp); } else if (tag == 0x0083) // lens type { imgdata.lens.nikon.NikonLensType = fgetc(ifp); } else if (tag == 0x0084) // lens { imgdata.lens.makernotes.MinFocal = getreal(type); imgdata.lens.makernotes.MaxFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); } else if (tag == 0x008b) // lens f-stops { uchar a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) { imgdata.lens.nikon.NikonLensFStops = a * b * (12 / c); imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops / 12.0f; } } else if (tag == 0x0093) // Nikon compression { imgdata.makernotes.nikon.NEFCompression = i = get2(); if ((i == 7) || (i == 9)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0098) // contains lens data { for (i = 0; i < 4; i++) { NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0'; } switch (NikonLensDataVersion) { case 100: lenNikonLensData = 9; break; case 101: case 201: // encrypted, starting from v.201 case 202: case 203: lenNikonLensData = 15; break; case 204: lenNikonLensData = 16; break; case 400: lenNikonLensData = 459; break; case 401: lenNikonLensData = 590; break; case 402: lenNikonLensData = 509; break; case 403: lenNikonLensData = 879; break; } if (lenNikonLensData > 0) { table_buf = (uchar *)malloc(lenNikonLensData); fread(table_buf, lenNikonLensData, 1, ifp); if ((NikonLensDataVersion < 201) && lenNikonLensData) { processNikonLensData(table_buf, lenNikonLensData); free(table_buf); lenNikonLensData = 0; } } } else if (tag == 0x00a0) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x00a8) // contains flash data { for (i = 0; i < 4; i++) { NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0'; } } } else if (!strncmp(make, "OLYMPUS", 7)) { switch (tag) { case 0x0404: case 0x101a: case 0x20100101: if (!imgdata.shootinginfo.BodySerial[0]) stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0x20100102: if (!imgdata.shootinginfo.InternalBodySerial[0]) stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp); break; case 0x0207: case 0x20100100: { uchar sOlyID[8]; unsigned long long OlyID; fread(sOlyID, MIN(len, 7), 1, ifp); sOlyID[7] = 0; OlyID = sOlyID[0]; i = 1; while (i < 7 && sOlyID[i]) { OlyID = OlyID << 8 | sOlyID[i]; i++; } setOlympusBodyFeatures(OlyID); } break; case 0x1002: imgdata.lens.makernotes.CurAp = powf64(2.0f, getreal(type) / 2); break; case 0x20401112: imgdata.makernotes.olympus.OlympusCropID = get2(); break; case 0x20401113: FORC4 imgdata.makernotes.olympus.OlympusFrame[c] = get2(); break; case 0x20100201: { unsigned long long oly_lensid[3]; oly_lensid[0] = fgetc(ifp); fgetc(ifp); oly_lensid[1] = fgetc(ifp); oly_lensid[2] = fgetc(ifp); imgdata.lens.makernotes.LensID = (oly_lensid[0] << 16) | (oly_lensid[1] << 8) | oly_lensid[2]; } imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FT; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FT; if (((imgdata.lens.makernotes.LensID < 0x20000) || (imgdata.lens.makernotes.LensID > 0x4ffff)) && (imgdata.lens.makernotes.LensID & 0x10)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_mFT; } break; case 0x20100202: stmread(imgdata.lens.LensSerial, len, ifp); break; case 0x20100203: stmread(imgdata.lens.makernotes.Lens, len, ifp); break; case 0x20100205: imgdata.lens.makernotes.MaxAp4MinFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100206: imgdata.lens.makernotes.MaxAp4MaxFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100207: imgdata.lens.makernotes.MinFocal = (float)get2(); break; case 0x20100208: imgdata.lens.makernotes.MaxFocal = (float)get2(); if (imgdata.lens.makernotes.MaxFocal > 1000.0f) imgdata.lens.makernotes.MaxFocal = imgdata.lens.makernotes.MinFocal; break; case 0x2010020a: imgdata.lens.makernotes.MaxAp4CurFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100301: imgdata.lens.makernotes.TeleconverterID = fgetc(ifp) << 8; fgetc(ifp); imgdata.lens.makernotes.TeleconverterID = imgdata.lens.makernotes.TeleconverterID | fgetc(ifp); break; case 0x20100303: stmread(imgdata.lens.makernotes.Teleconverter, len, ifp); break; case 0x20100403: stmread(imgdata.lens.makernotes.Attachment, len, ifp); break; } } else if ((!strncmp(make, "PENTAX", 6) || !strncmp(make, "RICOH", 5)) && !strncmp(model, "GR", 2)) { if (tag == 0x0005) { char buffer[17]; int count = 0; fread(buffer, 16, 1, ifp); buffer[16] = 0; for (int i = 0; i < 16; i++) { // sprintf(imgdata.shootinginfo.InternalBodySerial+2*i, "%02x", buffer[i]); if ((isspace(buffer[i])) || (buffer[i] == 0x2D) || (isalnum(buffer[i]))) count++; } if (count == 16) { sprintf(imgdata.shootinginfo.BodySerial, "%8s", buffer + 8); buffer[8] = 0; sprintf(imgdata.shootinginfo.InternalBodySerial, "%8s", buffer); } else { sprintf(imgdata.shootinginfo.BodySerial, "%02x%02x%02x%02x", buffer[4], buffer[5], buffer[6], buffer[7]); sprintf(imgdata.shootinginfo.InternalBodySerial, "%02x%02x%02x%02x", buffer[8], buffer[9], buffer[10], buffer[11]); } } else if ((tag == 0x1001) && (type == 3)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensID = -1; imgdata.lens.makernotes.FocalType = 1; } else if ((tag == 0x100b) && (type == 10)) { imgdata.other.FlashEC = getreal(type); } else if ((tag == 0x1017) && (get2() == 2)) { strcpy(imgdata.lens.makernotes.Attachment, "Wide-Angle Adapter"); } else if (tag == 0x1500) { imgdata.lens.makernotes.CurFocal = getreal(type); } } else if (!strncmp(make, "RICOH", 5) && strncmp(model, "PENTAX", 6)) { if ((tag == 0x0005) && !strncmp(model, "GXR", 3)) { char buffer[9]; buffer[8] = 0; fread(buffer, 8, 1, ifp); sprintf(imgdata.shootinginfo.InternalBodySerial, "%8s", buffer); } else if ((tag == 0x100b) && (type == 10)) { imgdata.other.FlashEC = getreal(type); } else if ((tag == 0x1017) && (get2() == 2)) { strcpy(imgdata.lens.makernotes.Attachment, "Wide-Angle Adapter"); } else if (tag == 0x1500) { imgdata.lens.makernotes.CurFocal = getreal(type); } else if ((tag == 0x2001) && !strncmp(model, "GXR", 3)) { short ntags, cur_tag; fseek(ifp, 20, SEEK_CUR); ntags = get2(); cur_tag = get2(); while (cur_tag != 0x002c) { fseek(ifp, 10, SEEK_CUR); cur_tag = get2(); } fseek(ifp, 6, SEEK_CUR); fseek(ifp, get4() + 20, SEEK_SET); stread(imgdata.shootinginfo.BodySerial, 12, ifp); get2(); imgdata.lens.makernotes.LensID = getc(ifp) - '0'; switch (imgdata.lens.makernotes.LensID) { case 1: case 2: case 3: case 5: case 6: imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_RicohModule; break; case 8: imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensID = -1; break; default: imgdata.lens.makernotes.LensID = -1; } fseek(ifp, 17, SEEK_CUR); stread(imgdata.lens.LensSerial, 12, ifp); } } else if ((!strncmp(make, "PENTAX", 6) || !strncmp(model, "PENTAX", 6) || (!strncmp(make, "SAMSUNG", 7) && dng_version)) && strncmp(model, "GR", 2)) { if (tag == 0x0005) { unique_id = get4(); setPentaxBodyFeatures(unique_id); } else if (tag == 0x0013) { imgdata.lens.makernotes.CurAp = (float)get2() / 10.0f; } else if (tag == 0x0014) { PentaxISO(get2()); } else if (tag == 0x001d) { imgdata.lens.makernotes.CurFocal = (float)get4() / 100.0f; } else if (tag == 0x003f) { imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp); } else if (tag == 0x004d) { if (type == 9) imgdata.other.FlashEC = getreal(type) / 256.0f; else imgdata.other.FlashEC = (float)((signed short)fgetc(ifp)) / 6.0f; } else if (tag == 0x007e) { imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = (long)(-1) * get4(); } else if (tag == 0x0207) { if (len < 65535) // Safety belt PentaxLensInfo(imgdata.lens.makernotes.CamID, len); } else if ((tag >= 0x020d) && (tag <= 0x0214)) { FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list1[tag - 0x020d]][c ^ (c >> 1)] = get2(); } else if (tag == 0x0221) { int nWB = get2(); if (nWB <= sizeof(imgdata.color.WBCT_Coeffs) / sizeof(imgdata.color.WBCT_Coeffs[0])) for (int i = 0; i < nWB; i++) { imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2(); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = get2(); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000; imgdata.color.WBCT_Coeffs[i][3] = get2(); } } else if (tag == 0x0215) { fseek(ifp, 16, SEEK_CUR); sprintf(imgdata.shootinginfo.InternalBodySerial, "%d", get4()); } else if (tag == 0x0229) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x022d) { int wb_ind; getc(ifp); for (int wb_cnt = 0; wb_cnt < nPentax_wb_list2; wb_cnt++) { wb_ind = getc(ifp); if (wb_ind < nPentax_wb_list2) FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list2[wb_ind]][c ^ (c >> 1)] = get2(); } } else if (tag == 0x0239) // Q-series lens info (LensInfoQ) { char LensInfo[20]; fseek(ifp, 2, SEEK_CUR); stread(imgdata.lens.makernotes.Lens, 30, ifp); strcat(imgdata.lens.makernotes.Lens, " "); stread(LensInfo, 20, ifp); strcat(imgdata.lens.makernotes.Lens, LensInfo); } } else if (!strncmp(make, "SAMSUNG", 7)) { if (tag == 0x0002) { if (get4() == 0x2000) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX; } else if (!strncmp(model, "NX mini", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0003) { unique_id = imgdata.lens.makernotes.CamID = get4(); } else if (tag == 0xa002) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0xa003) { imgdata.lens.makernotes.LensID = get2(); if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX; } else if (tag == 0xa005) { stmread(imgdata.lens.InternalLensSerial, len, ifp); } else if (tag == 0xa019) { imgdata.lens.makernotes.CurAp = getreal(type); } else if (tag == 0xa01a) { imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() / 10.0f; if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f) imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f; } } else if (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "Konica", 6) || !strncasecmp(make, "Minolta", 7) || (!strncasecmp(make, "Hasselblad", 10) && (!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) || !strncasecmp(model, "Lusso", 5) || !strncasecmp(model, "HV", 2)))) { parseSonyMakernotes(tag, type, len, nonDNG, table_buf_0x9050, table_buf_0x9050_present, table_buf_0x940c, table_buf_0x940c_present); } fseek(ifp, _pos, SEEK_SET); #endif if (tag == 2 && strstr(make, "NIKON") && !iso_speed) iso_speed = (get2(), get2()); if (tag == 37 && strstr(make, "NIKON") && (!iso_speed || iso_speed == 65535)) { unsigned char cc; fread(&cc, 1, 1, ifp); iso_speed = int(100.0 * powf64(2.0f, float(cc) / 12.0 - 5.0)); } if (tag == 4 && len > 26 && len < 35) { if ((i = (get4(), get2())) != 0x7fff && (!iso_speed || iso_speed == 65535)) iso_speed = 50 * powf64(2.0, i / 32.0 - 4); #ifdef LIBRAW_LIBRARY_BUILD get4(); #else if ((i = (get2(), get2())) != 0x7fff && !aperture) aperture = powf64(2.0, i / 64.0); #endif if ((i = get2()) != 0xffff && !shutter) shutter = powf64(2.0, (short)i / -32.0); wbi = (get2(), get2()); shot_order = (get2(), get2()); } if ((tag == 4 || tag == 0x114) && !strncmp(make, "KONICA", 6)) { fseek(ifp, tag == 4 ? 140 : 160, SEEK_CUR); switch (get2()) { case 72: flip = 0; break; case 76: flip = 6; break; case 82: flip = 5; break; } } if (tag == 7 && type == 2 && len > 20) fgets(model2, 64, ifp); if (tag == 8 && type == 4) shot_order = get4(); if (tag == 9 && !strncmp(make, "Canon", 5)) fread(artist, 64, 1, ifp); if (tag == 0xc && len == 4) FORC3 cam_mul[(c << 1 | c >> 1) & 3] = getreal(type); if (tag == 0xd && type == 7 && get2() == 0xaaaa) { #if 0 /* Canon rotation data is handled by EXIF.Orientation */ for (c = i = 2; (ushort)c != 0xbbbb && i < len; i++) c = c << 8 | fgetc(ifp); while ((i += 4) < len - 5) if (get4() == 257 && (i = len) && (c = (get4(), fgetc(ifp))) < 3) flip = "065"[c] - '0'; #endif } #ifndef LIBRAW_LIBRARY_BUILD if (tag == 0x10 && type == 4) unique_id = get4(); #endif #ifdef LIBRAW_LIBRARY_BUILD INT64 _pos2 = ftell(ifp); if (!strncasecmp(make, "Olympus", 7)) { short nWB, tWB; if ((tag == 0x20300108) || (tag == 0x20310109)) imgdata.makernotes.olympus.ColorSpace = get2(); if ((tag == 0x20400101) && (len == 2) && (!strncasecmp(model, "E-410", 5) || !strncasecmp(model, "E-510", 5))) { int i; for (i = 0; i < 64; i++) imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; for (i = 64; i < 256; i++) imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; } if ((tag >= 0x20400101) && (tag <= 0x20400111)) { nWB = tag - 0x20400101; tWB = Oly_wb_list2[nWB << 1]; ushort CT = Oly_wb_list2[(nWB << 1) | 1]; int wb[4]; wb[0] = get2(); wb[2] = get2(); if (tWB != 0x100) { imgdata.color.WB_Coeffs[tWB][0] = wb[0]; imgdata.color.WB_Coeffs[tWB][2] = wb[2]; } if (CT) { imgdata.color.WBCT_Coeffs[nWB - 1][0] = CT; imgdata.color.WBCT_Coeffs[nWB - 1][1] = wb[0]; imgdata.color.WBCT_Coeffs[nWB - 1][3] = wb[2]; } if (len == 4) { wb[1] = get2(); wb[3] = get2(); if (tWB != 0x100) { imgdata.color.WB_Coeffs[tWB][1] = wb[1]; imgdata.color.WB_Coeffs[tWB][3] = wb[3]; } if (CT) { imgdata.color.WBCT_Coeffs[nWB - 1][2] = wb[1]; imgdata.color.WBCT_Coeffs[nWB - 1][4] = wb[3]; } } } if ((tag >= 0x20400112) && (tag <= 0x2040011e)) { nWB = tag - 0x20400112; int wbG = get2(); tWB = Oly_wb_list2[nWB << 1]; if (nWB) imgdata.color.WBCT_Coeffs[nWB - 1][2] = imgdata.color.WBCT_Coeffs[nWB - 1][4] = wbG; if (tWB != 0x100) imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = wbG; } if (tag == 0x20400121) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][2] = get2(); if (len == 4) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = get2(); } } if (tag == 0x2040011f) { int wbG = get2(); if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0]) imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = wbG; FORC4 if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + c][0]) imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + c][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + c][3] = wbG; } if ((tag == 0x30000110) && strcmp(software, "v757-71")) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][2] = get2(); if (len == 2) { for (int i = 0; i < 256; i++) imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; } } if ((((tag >= 0x30000120) && (tag <= 0x30000124)) || ((tag >= 0x30000130) && (tag <= 0x30000133))) && strcmp(software, "v757-71")) { int wb_ind; if (tag <= 0x30000124) wb_ind = tag - 0x30000120; else wb_ind = tag - 0x30000130 + 5; imgdata.color.WB_Coeffs[Oly_wb_list1[wb_ind]][0] = get2(); imgdata.color.WB_Coeffs[Oly_wb_list1[wb_ind]][2] = get2(); } if ((tag == 0x20400805) && (len == 2)) { imgdata.makernotes.olympus.OlympusSensorCalibration[0] = getreal(type); imgdata.makernotes.olympus.OlympusSensorCalibration[1] = getreal(type); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.olympus.OlympusSensorCalibration[0]; } if (tag == 0x20200401) { imgdata.other.FlashEC = getreal(type); } } fseek(ifp, _pos2, SEEK_SET); #endif if (tag == 0x11 && is_raw && !strncmp(make, "NIKON", 5)) { fseek(ifp, get4() + base, SEEK_SET); parse_tiff_ifd(base); } if (tag == 0x14 && type == 7) { if (len == 2560) { fseek(ifp, 1248, SEEK_CUR); goto get2_256; } fread(buf, 1, 10, ifp); if (!strncmp(buf, "NRW ", 4)) { fseek(ifp, strcmp(buf + 4, "0100") ? 46 : 1546, SEEK_CUR); cam_mul[0] = get4() << 2; cam_mul[1] = get4() + get4(); cam_mul[2] = get4() << 2; } } if (tag == 0x15 && type == 2 && is_raw) fread(model, 64, 1, ifp); if (strstr(make, "PENTAX")) { if (tag == 0x1b) tag = 0x1018; if (tag == 0x1c) tag = 0x1017; } if (tag == 0x1d) { while ((c = fgetc(ifp)) && c != EOF) #ifdef LIBRAW_LIBRARY_BUILD { if ((!custom_serial) && (!isdigit(c))) { if ((strbuflen(model) == 3) && (!strcmp(model, "D50"))) { custom_serial = 34; } else { custom_serial = 96; } } #endif serial = serial * 10 + (isdigit(c) ? c - '0' : c % 10); #ifdef LIBRAW_LIBRARY_BUILD } if (!imgdata.shootinginfo.BodySerial[0]) sprintf(imgdata.shootinginfo.BodySerial, "%d", serial); #endif } if (tag == 0x29 && type == 1) { // Canon PowerShot G9 c = wbi < 18 ? "012347800000005896"[wbi] - '0' : 0; fseek(ifp, 8 + c * 32, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get4(); } #ifndef LIBRAW_LIBRARY_BUILD if (tag == 0x3d && type == 3 && len == 4) FORC4 cblack[c ^ c >> 1] = get2() >> (14 - tiff_bps); #endif if (tag == 0x81 && type == 4) { data_offset = get4(); fseek(ifp, data_offset + 41, SEEK_SET); raw_height = get2() * 2; raw_width = get2(); filters = 0x61616161; } if ((tag == 0x81 && type == 7) || (tag == 0x100 && type == 7) || (tag == 0x280 && type == 1)) { thumb_offset = ftell(ifp); thumb_length = len; } if (tag == 0x88 && type == 4 && (thumb_offset = get4())) thumb_offset += base; if (tag == 0x89 && type == 4) thumb_length = get4(); if (tag == 0x8c || tag == 0x96) meta_offset = ftell(ifp); if (tag == 0x97) { for (i = 0; i < 4; i++) ver97 = ver97 * 10 + fgetc(ifp) - '0'; switch (ver97) { case 100: fseek(ifp, 68, SEEK_CUR); FORC4 cam_mul[(c >> 1) | ((c & 1) << 1)] = get2(); break; case 102: fseek(ifp, 6, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); break; case 103: fseek(ifp, 16, SEEK_CUR); FORC4 cam_mul[c] = get2(); } if (ver97 >= 200) { if (ver97 != 205) fseek(ifp, 280, SEEK_CUR); fread(buf97, 324, 1, ifp); } } if ((tag == 0xa1) && (type == 7) && strncasecmp(make, "Samsung", 7)) { order = 0x4949; fseek(ifp, 140, SEEK_CUR); FORC3 cam_mul[c] = get4(); } if (tag == 0xa4 && type == 3) { fseek(ifp, wbi * 48, SEEK_CUR); FORC3 cam_mul[c] = get2(); } if (tag == 0xa7) { // shutter count NikonKey = fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp); if ((unsigned)(ver97 - 200) < 17) { ci = xlat[0][serial & 0xff]; cj = xlat[1][NikonKey]; ck = 0x60; for (i = 0; i < 324; i++) buf97[i] ^= (cj += ci * ck++); i = "66666>666;6A;:;55"[ver97 - 200] - '0'; FORC4 cam_mul[c ^ (c >> 1) ^ (i & 1)] = sget2(buf97 + (i & -2) + c * 2); } #ifdef LIBRAW_LIBRARY_BUILD if ((NikonLensDataVersion > 200) && lenNikonLensData) { if (custom_serial) { ci = xlat[0][custom_serial]; } else { ci = xlat[0][serial & 0xff]; } cj = xlat[1][NikonKey]; ck = 0x60; for (i = 0; i < lenNikonLensData; i++) table_buf[i] ^= (cj += ci * ck++); processNikonLensData(table_buf, lenNikonLensData); lenNikonLensData = 0; free(table_buf); } if (ver97 == 601) // Coolpix A { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } #endif } if (tag == 0xb001 && type == 3) // Sony ModelID { unique_id = get2(); } if (tag == 0x200 && len == 3) shot_order = (get4(), get4()); if (tag == 0x200 && len == 4) // Pentax black level FORC4 cblack[c ^ c >> 1] = get2(); if (tag == 0x201 && len == 4) // Pentax As Shot WB FORC4 cam_mul[c ^ (c >> 1)] = get2(); if (tag == 0x220 && type == 7) meta_offset = ftell(ifp); if (tag == 0x401 && type == 4 && len == 4) FORC4 cblack[c ^ c >> 1] = get4(); #ifdef LIBRAW_LIBRARY_BUILD // not corrected for file bitcount, to be patched in open_datastream if (tag == 0x03d && strstr(make, "NIKON") && len == 4) { FORC4 cblack[c ^ c >> 1] = get2(); i = cblack[3]; FORC3 if (i > cblack[c]) i = cblack[c]; FORC4 cblack[c] -= i; black += i; } #endif if (tag == 0xe01) { /* Nikon Capture Note */ #ifdef LIBRAW_LIBRARY_BUILD int loopc = 0; #endif order = 0x4949; fseek(ifp, 22, SEEK_CUR); for (offset = 22; offset + 22 < len; offset += 22 + i) { #ifdef LIBRAW_LIBRARY_BUILD if (loopc++ > 1024) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif tag = get4(); fseek(ifp, 14, SEEK_CUR); i = get4() - 4; if (tag == 0x76a43207) flip = get2(); else fseek(ifp, i, SEEK_CUR); } } if (tag == 0xe80 && len == 256 && type == 7) { fseek(ifp, 48, SEEK_CUR); cam_mul[0] = get2() * 508 * 1.078 / 0x10000; cam_mul[2] = get2() * 382 * 1.173 / 0x10000; } if (tag == 0xf00 && type == 7) { if (len == 614) fseek(ifp, 176, SEEK_CUR); else if (len == 734 || len == 1502) fseek(ifp, 148, SEEK_CUR); else goto next; goto get2_256; } if (((tag == 0x1011 && len == 9) || tag == 0x20400200) && strcmp(software, "v757-71")) for (i = 0; i < 3; i++) { #ifdef LIBRAW_LIBRARY_BUILD if (!imgdata.makernotes.olympus.ColorSpace) { FORC3 cmatrix[i][c] = ((short)get2()) / 256.0; } else { FORC3 imgdata.color.ccm[i][c] = ((short)get2()) / 256.0; } #else FORC3 cmatrix[i][c] = ((short)get2()) / 256.0; #endif } if ((tag == 0x1012 || tag == 0x20400600) && len == 4) FORC4 cblack[c ^ c >> 1] = get2(); if (tag == 0x1017 || tag == 0x20400100) cam_mul[0] = get2() / 256.0; if (tag == 0x1018 || tag == 0x20400100) cam_mul[2] = get2() / 256.0; if (tag == 0x2011 && len == 2) { get2_256: order = 0x4d4d; cam_mul[0] = get2() / 256.0; cam_mul[2] = get2() / 256.0; } if ((tag | 0x70) == 0x2070 && (type == 4 || type == 13)) fseek(ifp, get4() + base, SEEK_SET); #ifdef LIBRAW_LIBRARY_BUILD // IB start if (tag == 0x2010) { INT64 _pos3 = ftell(ifp); parse_makernote(base, 0x2010); fseek(ifp, _pos3, SEEK_SET); } if (((tag == 0x2020) || (tag == 0x3000) || (tag == 0x2030) || (tag == 0x2031)) && ((type == 7) || (type == 13)) && !strncasecmp(make, "Olympus", 7)) { INT64 _pos3 = ftell(ifp); parse_makernote(base, tag); fseek(ifp, _pos3, SEEK_SET); } // IB end #endif if ((tag == 0x2020) && ((type == 7) || (type == 13)) && !strncmp(buf, "OLYMP", 5)) parse_thumb_note(base, 257, 258); if (tag == 0x2040) parse_makernote(base, 0x2040); if (tag == 0xb028) { fseek(ifp, get4() + base, SEEK_SET); parse_thumb_note(base, 136, 137); } if (tag == 0x4001 && len > 500 && len < 100000) { i = len == 582 ? 50 : len == 653 ? 68 : len == 5120 ? 142 : 126; fseek(ifp, i, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); for (i += 18; i <= len; i += 10) { get2(); FORC4 sraw_mul[c ^ (c >> 1)] = get2(); if (sraw_mul[1] == 1170) break; } } if (!strncasecmp(make, "Samsung", 7)) { if (tag == 0xa020) // get the full Samsung encryption key for (i = 0; i < 11; i++) SamsungKey[i] = get4(); if (tag == 0xa021) // get and decode Samsung cam_mul array FORC4 cam_mul[c ^ (c >> 1)] = get4() - SamsungKey[c]; #ifdef LIBRAW_LIBRARY_BUILD if (tag == 0xa022) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get4() - SamsungKey[c + 4]; if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] >> 1)) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] >> 4; imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][3] >> 4; } } if (tag == 0xa023) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] = get4() - SamsungKey[8]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = get4() - SamsungKey[9]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = get4() - SamsungKey[10]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][2] = get4() - SamsungKey[0]; if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] >> 1)) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] >> 4; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] >> 4; } } if (tag == 0xa024) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][c ^ (c >> 1)] = get4() - SamsungKey[c + 1]; if (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] >> 1)) { imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] >> 4; imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] >> 4; } } /* if (tag == 0xa025) { i = get4(); imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = i - SamsungKey[0]; printf ("Samsung 0xa025 %d\n", i); } */ if (tag == 0xa030 && len == 9) for (i = 0; i < 3; i++) FORC3 imgdata.color.ccm[i][c] = (float)((short)((get4() + SamsungKey[i * 3 + c]))) / 256.0; #endif if (tag == 0xa031 && len == 9) // get and decode Samsung color matrix for (i = 0; i < 3; i++) FORC3 cmatrix[i][c] = (float)((short)((get4() + SamsungKey[i * 3 + c]))) / 256.0; if (tag == 0xa028) FORC4 cblack[c ^ (c >> 1)] = get4() - SamsungKey[c]; } else { // Somebody else use 0xa021 and 0xa028? if (tag == 0xa021) FORC4 cam_mul[c ^ (c >> 1)] = get4(); if (tag == 0xa028) FORC4 cam_mul[c ^ (c >> 1)] -= get4(); } #ifdef LIBRAW_LIBRARY_BUILD if (tag == 0x4021 && (imgdata.makernotes.canon.multishot[0] = get4()) && (imgdata.makernotes.canon.multishot[1] = get4())) { if (len >= 4) { imgdata.makernotes.canon.multishot[2] = get4(); imgdata.makernotes.canon.multishot[3] = get4(); } FORC4 cam_mul[c] = 1024; } #else if (tag == 0x4021 && get4() && get4()) FORC4 cam_mul[c] = 1024; #endif next: fseek(ifp, save, SEEK_SET); } quit: order = sorder; } /* Since the TIFF DateTime string has no timezone information, assume that the camera's clock was set to Universal Time. */ void CLASS get_timestamp(int reversed) { struct tm t; char str[20]; int i; str[19] = 0; if (reversed) for (i = 19; i--;) str[i] = fgetc(ifp); else fread(str, 19, 1, ifp); memset(&t, 0, sizeof t); if (sscanf(str, "%d:%d:%d %d:%d:%d", &t.tm_year, &t.tm_mon, &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec) != 6) return; t.tm_year -= 1900; t.tm_mon -= 1; t.tm_isdst = -1; if (mktime(&t) > 0) timestamp = mktime(&t); } void CLASS parse_exif(int base) { unsigned kodak, entries, tag, type, len, save, c; double expo, ape; kodak = !strncmp(make, "EASTMAN", 7) && tiff_nifds < 3; entries = get2(); if (!strncmp(make, "Hasselblad", 10) && (tiff_nifds > 3) && (entries > 512)) return; #ifdef LIBRAW_LIBRARY_BUILD INT64 fsize = ifp->size(); #endif while (entries--) { tiff_get(base, &tag, &type, &len, &save); #ifdef LIBRAW_LIBRARY_BUILD INT64 savepos = ftell(ifp); if (len > 8 && savepos + len > fsize * 2) continue; if (callbacks.exif_cb) { callbacks.exif_cb(callbacks.exifparser_data, tag, type, len, order, ifp); fseek(ifp, savepos, SEEK_SET); } #endif switch (tag) { #ifdef LIBRAW_LIBRARY_BUILD case 0xa405: // FocalLengthIn35mmFormat imgdata.lens.FocalLengthIn35mmFormat = get2(); break; case 0xa431: // BodySerialNumber stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa435: // LensSerialNumber stmread(imgdata.lens.LensSerial, len, ifp); break; case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard imgdata.lens.dng.MinFocal = getreal(type); imgdata.lens.dng.MaxFocal = getreal(type); imgdata.lens.dng.MaxAp4MinFocal = getreal(type); imgdata.lens.dng.MaxAp4MaxFocal = getreal(type); break; case 0xa433: // LensMake stmread(imgdata.lens.LensMake, len, ifp); break; case 0xa434: // LensModel stmread(imgdata.lens.Lens, len, ifp); if (!strncmp(imgdata.lens.Lens, "----", 4)) imgdata.lens.Lens[0] = 0; break; case 0x9205: imgdata.lens.EXIF_MaxAp = powf64(2.0f, (getreal(type) / 2.0f)); break; #endif case 33434: tiff_ifd[tiff_nifds - 1].t_shutter = shutter = getreal(type); break; case 33437: aperture = getreal(type); break; // 0x829d FNumber case 34855: iso_speed = get2(); break; case 34865: if (iso_speed == 0xffff && !strncasecmp(make, "FUJI", 4)) iso_speed = getreal(type); break; case 34866: if (iso_speed == 0xffff && (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "CANON", 5))) iso_speed = getreal(type); break; case 36867: case 36868: get_timestamp(0); break; case 37377: if ((expo = -getreal(type)) < 128 && shutter == 0.) tiff_ifd[tiff_nifds - 1].t_shutter = shutter = powf64(2.0, expo); break; case 37378: // 0x9202 ApertureValue if ((fabs(ape = getreal(type)) < 256.0) && (!aperture)) aperture = powf64(2.0, ape / 2); break; case 37385: flash_used = getreal(type); break; case 37386: focal_len = getreal(type); break; case 37500: // tag 0x927c #ifdef LIBRAW_LIBRARY_BUILD if (((make[0] == '\0') && (!strncmp(model, "ov5647", 6))) || ((!strncmp(make, "RaspberryPi", 11)) && (!strncmp(model, "RP_OV5647", 9))) || ((!strncmp(make, "RaspberryPi", 11)) && (!strncmp(model, "RP_imx219", 9)))) { char mn_text[512]; char *pos; char ccms[512]; ushort l; float num; fgets(mn_text, len, ifp); pos = strstr(mn_text, "gain_r="); if (pos) cam_mul[0] = atof(pos + 7); pos = strstr(mn_text, "gain_b="); if (pos) cam_mul[2] = atof(pos + 7); if ((cam_mul[0] > 0.001f) && (cam_mul[2] > 0.001f)) cam_mul[1] = cam_mul[3] = 1.0f; else cam_mul[0] = cam_mul[2] = 0.0f; pos = strstr(mn_text, "ccm=") + 4; l = strstr(pos, " ") - pos; memcpy(ccms, pos, l); ccms[l] = '\0'; pos = strtok(ccms, ","); for (l = 0; l < 4; l++) { num = 0.0; for (c = 0; c < 3; c++) { imgdata.color.ccm[l][c] = (float)atoi(pos); num += imgdata.color.ccm[l][c]; pos = strtok(NULL, ","); } if (num > 0.01) FORC3 imgdata.color.ccm[l][c] = imgdata.color.ccm[l][c] / num; } } else #endif parse_makernote(base, 0); break; case 40962: if (kodak) raw_width = get4(); break; case 40963: if (kodak) raw_height = get4(); break; case 41730: if (get4() == 0x20002) for (exif_cfa = c = 0; c < 8; c += 2) exif_cfa |= fgetc(ifp) * 0x01010101 << c; } fseek(ifp, save, SEEK_SET); } } #ifdef LIBRAW_LIBRARY_BUILD void CLASS parse_gps_libraw(int base) { unsigned entries, tag, type, len, save, c; entries = get2(); if (entries > 200) return; if (entries > 0) imgdata.other.parsed_gps.gpsparsed = 1; while (entries--) { tiff_get(base, &tag, &type, &len, &save); if (len > 1024) continue; // no GPS tags are 1k or larger switch (tag) { case 1: imgdata.other.parsed_gps.latref = getc(ifp); break; case 3: imgdata.other.parsed_gps.longref = getc(ifp); break; case 5: imgdata.other.parsed_gps.altref = getc(ifp); break; case 2: if (len == 3) FORC(3) imgdata.other.parsed_gps.latitude[c] = getreal(type); break; case 4: if (len == 3) FORC(3) imgdata.other.parsed_gps.longtitude[c] = getreal(type); break; case 7: if (len == 3) FORC(3) imgdata.other.parsed_gps.gpstimestamp[c] = getreal(type); break; case 6: imgdata.other.parsed_gps.altitude = getreal(type); break; case 9: imgdata.other.parsed_gps.gpsstatus = getc(ifp); break; } fseek(ifp, save, SEEK_SET); } } #endif void CLASS parse_gps(int base) { unsigned entries, tag, type, len, save, c; entries = get2(); while (entries--) { tiff_get(base, &tag, &type, &len, &save); if (len > 1024) continue; // no GPS tags are 1k or larger switch (tag) { case 1: case 3: case 5: gpsdata[29 + tag / 2] = getc(ifp); break; case 2: case 4: case 7: FORC(6) gpsdata[tag / 3 * 6 + c] = get4(); break; case 6: FORC(2) gpsdata[18 + c] = get4(); break; case 18: case 29: fgets((char *)(gpsdata + 14 + tag / 3), MIN(len, 12), ifp); } fseek(ifp, save, SEEK_SET); } } void CLASS romm_coeff(float romm_cam[3][3]) { static const float rgb_romm[3][3] = /* ROMM == Kodak ProPhoto */ {{2.034193, -0.727420, -0.306766}, {-0.228811, 1.231729, -0.002922}, {-0.008565, -0.153273, 1.161839}}; int i, j, k; for (i = 0; i < 3; i++) for (j = 0; j < 3; j++) for (cmatrix[i][j] = k = 0; k < 3; k++) cmatrix[i][j] += rgb_romm[i][k] * romm_cam[k][j]; } void CLASS parse_mos(int offset) { char data[40]; int skip, from, i, c, neut[4], planes = 0, frot = 0; static const char *mod[] = {"", "DCB2", "Volare", "Cantare", "CMost", "Valeo 6", "Valeo 11", "Valeo 22", "Valeo 11p", "Valeo 17", "", "Aptus 17", "Aptus 22", "Aptus 75", "Aptus 65", "Aptus 54S", "Aptus 65S", "Aptus 75S", "AFi 5", "AFi 6", "AFi 7", "AFi-II 7", "Aptus-II 7", "", "Aptus-II 6", "", "", "Aptus-II 10", "Aptus-II 5", "", "", "", "", "Aptus-II 10R", "Aptus-II 8", "", "Aptus-II 12", "", "AFi-II 12"}; float romm_cam[3][3]; fseek(ifp, offset, SEEK_SET); while (1) { if (get4() != 0x504b5453) break; get4(); fread(data, 1, 40, ifp); skip = get4(); from = ftell(ifp); // IB start #ifdef LIBRAW_LIBRARY_BUILD if (!strcmp(data, "CameraObj_camera_type")) { stmread(imgdata.lens.makernotes.body, skip, ifp); } if (!strcmp(data, "back_serial_number")) { char buffer[sizeof(imgdata.shootinginfo.BodySerial)]; char *words[4]; int nwords; stmread(buffer, skip, ifp); nwords = getwords(buffer, words, 4, sizeof(imgdata.shootinginfo.BodySerial)); strcpy(imgdata.shootinginfo.BodySerial, words[0]); } if (!strcmp(data, "CaptProf_serial_number")) { char buffer[sizeof(imgdata.shootinginfo.InternalBodySerial)]; char *words[4]; int nwords; stmread(buffer, skip, ifp); nwords = getwords(buffer, words, 4, sizeof(imgdata.shootinginfo.InternalBodySerial)); strcpy(imgdata.shootinginfo.InternalBodySerial, words[0]); } #endif // IB end if (!strcmp(data, "JPEG_preview_data")) { thumb_offset = from; thumb_length = skip; } if (!strcmp(data, "icc_camera_profile")) { profile_offset = from; profile_length = skip; } if (!strcmp(data, "ShootObj_back_type")) { fscanf(ifp, "%d", &i); if ((unsigned)i < sizeof mod / sizeof(*mod)) strcpy(model, mod[i]); } if (!strcmp(data, "icc_camera_to_tone_matrix")) { for (i = 0; i < 9; i++) ((float *)romm_cam)[i] = int_to_float(get4()); romm_coeff(romm_cam); } if (!strcmp(data, "CaptProf_color_matrix")) { for (i = 0; i < 9; i++) fscanf(ifp, "%f", (float *)romm_cam + i); romm_coeff(romm_cam); } if (!strcmp(data, "CaptProf_number_of_planes")) fscanf(ifp, "%d", &planes); if (!strcmp(data, "CaptProf_raw_data_rotation")) fscanf(ifp, "%d", &flip); if (!strcmp(data, "CaptProf_mosaic_pattern")) FORC4 { fscanf(ifp, "%d", &i); if (i == 1) frot = c ^ (c >> 1); } if (!strcmp(data, "ImgProf_rotation_angle")) { fscanf(ifp, "%d", &i); flip = i - flip; } if (!strcmp(data, "NeutObj_neutrals") && !cam_mul[0]) { FORC4 fscanf(ifp, "%d", neut + c); FORC3 cam_mul[c] = (float)neut[0] / neut[c + 1]; } if (!strcmp(data, "Rows_data")) load_flags = get4(); parse_mos(from); fseek(ifp, skip + from, SEEK_SET); } if (planes) filters = (planes == 1) * 0x01010101 * (uchar) "\x94\x61\x16\x49"[(flip / 90 + frot) & 3]; } void CLASS linear_table(unsigned len) { int i; if (len > 0x10000) len = 0x10000; read_shorts(curve, len); for (i = len; i < 0x10000; i++) curve[i] = curve[i - 1]; maximum = curve[len < 0x1000 ? 0xfff : len - 1]; } #ifdef LIBRAW_LIBRARY_BUILD void CLASS Kodak_WB_0x08tags(int wb, unsigned type) { float mul[3] = {1, 1, 1}, num, mul2; int c; FORC3 mul[c] = (num = getreal(type)) == 0 ? 1 : num; imgdata.color.WB_Coeffs[wb][1] = imgdata.color.WB_Coeffs[wb][3] = mul[1]; mul2 = mul[1] * mul[1]; imgdata.color.WB_Coeffs[wb][0] = mul2 / mul[0]; imgdata.color.WB_Coeffs[wb][2] = mul2 / mul[2]; return; } /* Thanks to Alexey Danilchenko for wb as-shot parsing code */ void CLASS parse_kodak_ifd(int base) { unsigned entries, tag, type, len, save; int i, c, wbi = -2; float mul[3] = {1, 1, 1}, num; static const int wbtag[] = {64037, 64040, 64039, 64041, -1, -1, 64042}; // int a_blck = 0; entries = get2(); if (entries > 1024) return; INT64 fsize = ifp->size(); while (entries--) { tiff_get(base, &tag, &type, &len, &save); INT64 savepos = ftell(ifp); if (len > 8 && len + savepos > 2 * fsize) continue; if (callbacks.exif_cb) { callbacks.exif_cb(callbacks.exifparser_data, tag | 0x20000, type, len, order, ifp); fseek(ifp, savepos, SEEK_SET); } if (tag == 1011) imgdata.other.FlashEC = getreal(type); if (tag == 1020) wbi = getint(type); if (tag == 1021 && len == 72) { /* WB set in software */ fseek(ifp, 40, SEEK_CUR); FORC3 cam_mul[c] = 2048.0 / fMAX(1.0f, get2()); wbi = -2; } if ((tag == 0x03ef) && (!strcmp(model, "EOS D2000C"))) black = get2(); if ((tag == 0x03f0) && (!strcmp(model, "EOS D2000C"))) { if (black) // already set by tag 0x03ef black = (black + get2()) / 2; else black = get2(); } INT64 _pos2 = ftell(ifp); if (tag == 0x0848) Kodak_WB_0x08tags(LIBRAW_WBI_Daylight, type); if (tag == 0x0849) Kodak_WB_0x08tags(LIBRAW_WBI_Tungsten, type); if (tag == 0x084a) Kodak_WB_0x08tags(LIBRAW_WBI_Fluorescent, type); if (tag == 0x084b) Kodak_WB_0x08tags(LIBRAW_WBI_Flash, type); if (tag == 0x084c) Kodak_WB_0x08tags(LIBRAW_WBI_Custom, type); if (tag == 0x084d) Kodak_WB_0x08tags(LIBRAW_WBI_Auto, type); if (tag == 0x0e93) imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = get2(); if (tag == 0x09ce) stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp); if (tag == 0xfa00) stmread(imgdata.shootinginfo.BodySerial, len, ifp); if (tag == 0xfa27) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1]; } if (tag == 0xfa28) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][1]; } if (tag == 0xfa29) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1]; } if (tag == 0xfa2a) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1]; } fseek(ifp, _pos2, SEEK_SET); if (tag == 2120 + wbi || (wbi < 0 && tag == 2125)) /* use Auto WB if illuminant index is not set */ { FORC3 mul[c] = (num = getreal(type)) == 0 ? 1 : num; FORC3 cam_mul[c] = mul[1] / mul[c]; /* normalise against green */ } if (tag == 2317) linear_table(len); if (tag == 0x903) iso_speed = getreal(type); // if (tag == 6020) iso_speed = getint(type); if (tag == 64013) wbi = fgetc(ifp); if ((unsigned)wbi < 7 && tag == wbtag[wbi]) FORC3 cam_mul[c] = get4(); if (tag == 64019) width = getint(type); if (tag == 64020) height = (getint(type) + 1) & -2; fseek(ifp, save, SEEK_SET); } } #else void CLASS parse_kodak_ifd(int base) { unsigned entries, tag, type, len, save; int i, c, wbi = -2, wbtemp = 6500; float mul[3] = {1, 1, 1}, num; static const int wbtag[] = {64037, 64040, 64039, 64041, -1, -1, 64042}; entries = get2(); if (entries > 1024) return; while (entries--) { tiff_get(base, &tag, &type, &len, &save); if (tag == 1020) wbi = getint(type); if (tag == 1021 && len == 72) { /* WB set in software */ fseek(ifp, 40, SEEK_CUR); FORC3 cam_mul[c] = 2048.0 / fMAX(1.0, get2()); wbi = -2; } if (tag == 2118) wbtemp = getint(type); if (tag == 2120 + wbi && wbi >= 0) FORC3 cam_mul[c] = 2048.0 / fMAX(1.0, getreal(type)); if (tag == 2130 + wbi) FORC3 mul[c] = getreal(type); if (tag == 2140 + wbi && wbi >= 0) FORC3 { for (num = i = 0; i < 4; i++) num += getreal(type) * pow(wbtemp / 100.0, i); cam_mul[c] = 2048 / fMAX(1.0, (num * mul[c])); } if (tag == 2317) linear_table(len); if (tag == 6020) iso_speed = getint(type); if (tag == 64013) wbi = fgetc(ifp); if ((unsigned)wbi < 7 && tag == wbtag[wbi]) FORC3 cam_mul[c] = get4(); if (tag == 64019) width = getint(type); if (tag == 64020) height = (getint(type) + 1) & -2; fseek(ifp, save, SEEK_SET); } } #endif //@end COMMON void CLASS parse_minolta(int base); int CLASS parse_tiff(int base); //@out COMMON int CLASS parse_tiff_ifd(int base) { unsigned entries, tag, type, len, plen = 16, save; int ifd, use_cm = 0, cfa, i, j, c, ima_len = 0; char *cbuf, *cp; uchar cfa_pat[16], cfa_pc[] = {0, 1, 2, 3}, tab[256]; double fm[3][4], cc[4][4], cm[4][3], cam_xyz[4][3], num; double ab[] = {1, 1, 1, 1}, asn[] = {0, 0, 0, 0}, xyz[] = {1, 1, 1}; unsigned sony_curve[] = {0, 0, 0, 0, 0, 4095}; unsigned *buf, sony_offset = 0, sony_length = 0, sony_key = 0; struct jhead jh; int pana_raw = 0; #ifndef LIBRAW_LIBRARY_BUILD FILE *sfp; #endif if (tiff_nifds >= sizeof tiff_ifd / sizeof tiff_ifd[0]) return 1; ifd = tiff_nifds++; for (j = 0; j < 4; j++) for (i = 0; i < 4; i++) cc[j][i] = i == j; entries = get2(); if (entries > 512) return 1; #ifdef LIBRAW_LIBRARY_BUILD INT64 fsize = ifp->size(); #endif while (entries--) { tiff_get(base, &tag, &type, &len, &save); #ifdef LIBRAW_LIBRARY_BUILD INT64 savepos = ftell(ifp); if (len > 8 && len + savepos > fsize * 2) continue; // skip tag pointing out of 2xfile if (callbacks.exif_cb) { callbacks.exif_cb(callbacks.exifparser_data, tag | (pana_raw ? 0x30000 : 0), type, len, order, ifp); fseek(ifp, savepos, SEEK_SET); } #endif #ifdef LIBRAW_LIBRARY_BUILD if (!strncasecmp(make, "SONY", 4) || (!strncasecmp(make, "Hasselblad", 10) && (!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) || !strncasecmp(model, "HV", 2)))) { switch (tag) { case 0x7300: // SR2 black level for (int i = 0; i < 4 && i < len; i++) cblack[i] = get2(); break; case 0x7302: FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c < 2)] = get2(); break; case 0x7312: { int i, lc[4]; FORC4 lc[c] = get2(); i = (lc[1] == 1024 && lc[2] == 1024) << 1; SWAP(lc[i], lc[i + 1]); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c] = lc[c]; } break; case 0x7480: case 0x7820: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1]; break; case 0x7481: case 0x7821: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][1]; break; case 0x7482: case 0x7822: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1]; break; case 0x7483: case 0x7823: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1]; break; case 0x7484: case 0x7824: imgdata.color.WBCT_Coeffs[0][0] = 4500; FORC3 imgdata.color.WBCT_Coeffs[0][c + 1] = get2(); imgdata.color.WBCT_Coeffs[0][4] = imgdata.color.WBCT_Coeffs[0][2]; break; case 0x7486: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][1]; break; case 0x7825: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1]; break; case 0x7826: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1]; break; case 0x7827: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][1]; break; case 0x7828: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1]; break; case 0x7829: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][1]; break; case 0x782a: imgdata.color.WBCT_Coeffs[1][0] = 8500; FORC3 imgdata.color.WBCT_Coeffs[1][c + 1] = get2(); imgdata.color.WBCT_Coeffs[1][4] = imgdata.color.WBCT_Coeffs[1][2]; break; case 0x782b: imgdata.color.WBCT_Coeffs[2][0] = 6000; FORC3 imgdata.color.WBCT_Coeffs[2][c + 1] = get2(); imgdata.color.WBCT_Coeffs[2][4] = imgdata.color.WBCT_Coeffs[2][2]; break; case 0x782c: imgdata.color.WBCT_Coeffs[3][0] = 3200; FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][c] = imgdata.color.WBCT_Coeffs[3][c + 1] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][3] = imgdata.color.WBCT_Coeffs[3][4] = imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][1]; break; case 0x782d: imgdata.color.WBCT_Coeffs[4][0] = 2500; FORC3 imgdata.color.WBCT_Coeffs[4][c + 1] = get2(); imgdata.color.WBCT_Coeffs[4][4] = imgdata.color.WBCT_Coeffs[4][2]; break; case 0x787f: FORC3 imgdata.color.linear_max[c] = get2(); imgdata.color.linear_max[3] = imgdata.color.linear_max[1]; break; } } #endif switch (tag) { case 1: if (len == 4) pana_raw = get4(); break; case 5: width = get2(); break; case 6: height = get2(); break; case 7: width += get2(); break; case 9: if ((i = get2())) filters = i; #ifdef LIBRAW_LIBRARY_BUILD if (pana_raw && len == 1 && type == 3) pana_black[3] += i; #endif break; case 8: case 10: #ifdef LIBRAW_LIBRARY_BUILD if (pana_raw && len == 1 && type == 3) pana_black[3] += get2(); #endif break; case 14: case 15: case 16: #ifdef LIBRAW_LIBRARY_BUILD if (pana_raw) { imgdata.color.linear_max[tag - 14] = get2(); if (tag == 15) imgdata.color.linear_max[3] = imgdata.color.linear_max[1]; } #endif break; case 17: case 18: if (type == 3 && len == 1) cam_mul[(tag - 17) * 2] = get2() / 256.0; break; #ifdef LIBRAW_LIBRARY_BUILD case 19: if (pana_raw) { ushort nWB, cnt, tWB; nWB = get2(); if (nWB > 0x100) break; for (cnt = 0; cnt < nWB; cnt++) { tWB = get2(); if (tWB < 0x100) { imgdata.color.WB_Coeffs[tWB][0] = get2(); imgdata.color.WB_Coeffs[tWB][2] = get2(); imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = 0x100; } else get4(); } } break; #endif case 23: if (type == 3) iso_speed = get2(); break; case 28: case 29: case 30: #ifdef LIBRAW_LIBRARY_BUILD if (pana_raw && len == 1 && type == 3) { pana_black[tag - 28] = get2(); } else #endif { cblack[tag - 28] = get2(); cblack[3] = cblack[1]; } break; case 36: case 37: case 38: cam_mul[tag - 36] = get2(); break; case 39: #ifdef LIBRAW_LIBRARY_BUILD if (pana_raw) { ushort nWB, cnt, tWB; nWB = get2(); if (nWB > 0x100) break; for (cnt = 0; cnt < nWB; cnt++) { tWB = get2(); if (tWB < 0x100) { imgdata.color.WB_Coeffs[tWB][0] = get2(); imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = get2(); imgdata.color.WB_Coeffs[tWB][2] = get2(); } else fseek(ifp, 6, SEEK_CUR); } } break; #endif if (len < 50 || cam_mul[0]) break; fseek(ifp, 12, SEEK_CUR); FORC3 cam_mul[c] = get2(); break; case 46: if (type != 7 || fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8) break; thumb_offset = ftell(ifp) - 2; thumb_length = len; break; case 61440: /* Fuji HS10 table */ fseek(ifp, get4() + base, SEEK_SET); parse_tiff_ifd(base); break; case 2: case 256: case 61441: /* ImageWidth */ tiff_ifd[ifd].t_width = getint(type); break; case 3: case 257: case 61442: /* ImageHeight */ tiff_ifd[ifd].t_height = getint(type); break; case 258: /* BitsPerSample */ case 61443: tiff_ifd[ifd].samples = len & 7; tiff_ifd[ifd].bps = getint(type); if (tiff_bps < tiff_ifd[ifd].bps) tiff_bps = tiff_ifd[ifd].bps; break; case 61446: raw_height = 0; if (tiff_ifd[ifd].bps > 12) break; load_raw = &CLASS packed_load_raw; load_flags = get4() ? 24 : 80; break; case 259: /* Compression */ tiff_ifd[ifd].comp = getint(type); break; case 262: /* PhotometricInterpretation */ tiff_ifd[ifd].phint = get2(); break; case 270: /* ImageDescription */ fread(desc, 512, 1, ifp); break; case 271: /* Make */ fgets(make, 64, ifp); break; case 272: /* Model */ fgets(model, 64, ifp); break; #ifdef LIBRAW_LIBRARY_BUILD case 278: tiff_ifd[ifd].rows_per_strip = getint(type); break; #endif case 280: /* Panasonic RW2 offset */ if (type != 4) break; load_raw = &CLASS panasonic_load_raw; load_flags = 0x2008; case 273: /* StripOffset */ #ifdef LIBRAW_LIBRARY_BUILD if (len > 1 && len < 16384) { off_t sav = ftell(ifp); tiff_ifd[ifd].strip_offsets = (int *)calloc(len, sizeof(int)); tiff_ifd[ifd].strip_offsets_count = len; for (int i = 0; i < len; i++) tiff_ifd[ifd].strip_offsets[i] = get4() + base; fseek(ifp, sav, SEEK_SET); // restore position } /* fallback */ #endif case 513: /* JpegIFOffset */ case 61447: tiff_ifd[ifd].offset = get4() + base; if (!tiff_ifd[ifd].bps && tiff_ifd[ifd].offset > 0) { fseek(ifp, tiff_ifd[ifd].offset, SEEK_SET); if (ljpeg_start(&jh, 1)) { tiff_ifd[ifd].comp = 6; tiff_ifd[ifd].t_width = jh.wide; tiff_ifd[ifd].t_height = jh.high; tiff_ifd[ifd].bps = jh.bits; tiff_ifd[ifd].samples = jh.clrs; if (!(jh.sraw || (jh.clrs & 1))) tiff_ifd[ifd].t_width *= jh.clrs; if ((tiff_ifd[ifd].t_width > 4 * tiff_ifd[ifd].t_height) & ~jh.clrs) { tiff_ifd[ifd].t_width /= 2; tiff_ifd[ifd].t_height *= 2; } i = order; parse_tiff(tiff_ifd[ifd].offset + 12); order = i; } } break; case 274: /* Orientation */ tiff_ifd[ifd].t_flip = "50132467"[get2() & 7] - '0'; break; case 277: /* SamplesPerPixel */ tiff_ifd[ifd].samples = getint(type) & 7; break; case 279: /* StripByteCounts */ #ifdef LIBRAW_LIBRARY_BUILD if (len > 1 && len < 16384) { off_t sav = ftell(ifp); tiff_ifd[ifd].strip_byte_counts = (int *)calloc(len, sizeof(int)); tiff_ifd[ifd].strip_byte_counts_count = len; for (int i = 0; i < len; i++) tiff_ifd[ifd].strip_byte_counts[i] = get4(); fseek(ifp, sav, SEEK_SET); // restore position } /* fallback */ #endif case 514: case 61448: tiff_ifd[ifd].bytes = get4(); break; case 61454: // FujiFilm "As Shot" FORC3 cam_mul[(4 - c) % 3] = getint(type); break; case 305: case 11: /* Software */ fgets(software, 64, ifp); if (!strncmp(software, "Adobe", 5) || !strncmp(software, "dcraw", 5) || !strncmp(software, "UFRaw", 5) || !strncmp(software, "Bibble", 6) || !strcmp(software, "Digital Photo Professional")) is_raw = 0; break; case 306: /* DateTime */ get_timestamp(0); break; case 315: /* Artist */ fread(artist, 64, 1, ifp); break; case 317: tiff_ifd[ifd].predictor = getint(type); break; case 322: /* TileWidth */ tiff_ifd[ifd].t_tile_width = getint(type); break; case 323: /* TileLength */ tiff_ifd[ifd].t_tile_length = getint(type); break; case 324: /* TileOffsets */ tiff_ifd[ifd].offset = len > 1 ? ftell(ifp) : get4(); if (len == 1) tiff_ifd[ifd].t_tile_width = tiff_ifd[ifd].t_tile_length = 0; if (len == 4) { load_raw = &CLASS sinar_4shot_load_raw; is_raw = 5; } break; case 325: tiff_ifd[ifd].bytes = len > 1 ? ftell(ifp) : get4(); break; case 330: /* SubIFDs */ if (!strcmp(model, "DSLR-A100") && tiff_ifd[ifd].t_width == 3872) { load_raw = &CLASS sony_arw_load_raw; data_offset = get4() + base; ifd++; #ifdef LIBRAW_LIBRARY_BUILD if (ifd >= sizeof tiff_ifd / sizeof tiff_ifd[0]) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif break; } #ifdef LIBRAW_LIBRARY_BUILD if (!strncmp(make, "Hasselblad", 10) && libraw_internal_data.unpacker_data.hasselblad_parser_flag) { fseek(ifp, ftell(ifp) + 4, SEEK_SET); fseek(ifp, get4() + base, SEEK_SET); parse_tiff_ifd(base); break; } #endif if (len > 1000) len = 1000; /* 1000 SubIFDs is enough */ while (len--) { i = ftell(ifp); fseek(ifp, get4() + base, SEEK_SET); if (parse_tiff_ifd(base)) break; fseek(ifp, i + 4, SEEK_SET); } break; case 339: tiff_ifd[ifd].sample_format = getint(type); break; case 400: strcpy(make, "Sarnoff"); maximum = 0xfff; break; #ifdef LIBRAW_LIBRARY_BUILD case 700: if ((type == 1 || type == 2 || type == 6 || type == 7) && len > 1 && len < 5100000) { xmpdata = (char *)malloc(xmplen = len + 1); fread(xmpdata, len, 1, ifp); xmpdata[len] = 0; } break; #endif case 28688: FORC4 sony_curve[c + 1] = get2() >> 2 & 0xfff; for (i = 0; i < 5; i++) for (j = sony_curve[i] + 1; j <= sony_curve[i + 1]; j++) curve[j] = curve[j - 1] + (1 << i); break; case 29184: sony_offset = get4(); break; case 29185: sony_length = get4(); break; case 29217: sony_key = get4(); break; case 29264: parse_minolta(ftell(ifp)); raw_width = 0; break; case 29443: FORC4 cam_mul[c ^ (c < 2)] = get2(); break; case 29459: FORC4 cam_mul[c] = get2(); i = (cam_mul[1] == 1024 && cam_mul[2] == 1024) << 1; SWAP(cam_mul[i], cam_mul[i + 1]) break; #ifdef LIBRAW_LIBRARY_BUILD case 30720: // Sony matrix, Sony_SR2SubIFD_0x7800 for (i = 0; i < 3; i++) { float num = 0.0; for (c = 0; c < 3; c++) { imgdata.color.ccm[i][c] = (float)((short)get2()); num += imgdata.color.ccm[i][c]; } if (num > 0.01) FORC3 imgdata.color.ccm[i][c] = imgdata.color.ccm[i][c] / num; } break; #endif case 29456: // Sony black level, Sony_SR2SubIFD_0x7310, no more needs to be divided by 4 FORC4 cblack[c ^ c >> 1] = get2(); i = cblack[3]; FORC3 if (i > cblack[c]) i = cblack[c]; FORC4 cblack[c] -= i; black = i; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("...Sony black: %u cblack: %u %u %u %u\n"), black, cblack[0], cblack[1], cblack[2], cblack[3]); #endif break; case 33405: /* Model2 */ fgets(model2, 64, ifp); break; case 33421: /* CFARepeatPatternDim */ if (get2() == 6 && get2() == 6) filters = 9; break; case 33422: /* CFAPattern */ if (filters == 9) { FORC(36)((char *)xtrans)[c] = fgetc(ifp) & 3; break; } case 64777: /* Kodak P-series */ if (len == 36) { filters = 9; colors = 3; FORC(36) xtrans[0][c] = fgetc(ifp) & 3; } else if (len > 0) { if ((plen = len) > 16) plen = 16; fread(cfa_pat, 1, plen, ifp); for (colors = cfa = i = 0; i < plen && colors < 4; i++) { colors += !(cfa & (1 << cfa_pat[i])); cfa |= 1 << cfa_pat[i]; } if (cfa == 070) memcpy(cfa_pc, "\003\004\005", 3); /* CMY */ if (cfa == 072) memcpy(cfa_pc, "\005\003\004\001", 4); /* GMCY */ goto guess_cfa_pc; } break; case 33424: case 65024: fseek(ifp, get4() + base, SEEK_SET); parse_kodak_ifd(base); break; case 33434: /* ExposureTime */ tiff_ifd[ifd].t_shutter = shutter = getreal(type); break; case 33437: /* FNumber */ aperture = getreal(type); break; #ifdef LIBRAW_LIBRARY_BUILD // IB start case 0xa405: // FocalLengthIn35mmFormat imgdata.lens.FocalLengthIn35mmFormat = get2(); break; case 0xa431: // BodySerialNumber case 0xc62f: stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa435: // LensSerialNumber stmread(imgdata.lens.LensSerial, len, ifp); break; case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa433: // LensMake stmread(imgdata.lens.LensMake, len, ifp); break; case 0xa434: // LensModel stmread(imgdata.lens.Lens, len, ifp); if (!strncmp(imgdata.lens.Lens, "----", 4)) imgdata.lens.Lens[0] = 0; break; case 0x9205: imgdata.lens.EXIF_MaxAp = powf64(2.0f, (getreal(type) / 2.0f)); break; // IB end #endif case 34306: /* Leaf white balance */ FORC4 cam_mul[c ^ 1] = 4096.0 / get2(); break; case 34307: /* Leaf CatchLight color matrix */ fread(software, 1, 7, ifp); if (strncmp(software, "MATRIX", 6)) break; colors = 4; for (raw_color = i = 0; i < 3; i++) { FORC4 fscanf(ifp, "%f", &rgb_cam[i][c ^ 1]); if (!use_camera_wb) continue; num = 0; FORC4 num += rgb_cam[i][c]; FORC4 rgb_cam[i][c] /= MAX(1, num); } break; case 34310: /* Leaf metadata */ parse_mos(ftell(ifp)); case 34303: strcpy(make, "Leaf"); break; case 34665: /* EXIF tag */ fseek(ifp, get4() + base, SEEK_SET); parse_exif(base); break; case 34853: /* GPSInfo tag */ { unsigned pos; fseek(ifp, pos = (get4() + base), SEEK_SET); parse_gps(base); #ifdef LIBRAW_LIBRARY_BUILD fseek(ifp, pos, SEEK_SET); parse_gps_libraw(base); #endif } break; case 34675: /* InterColorProfile */ case 50831: /* AsShotICCProfile */ profile_offset = ftell(ifp); profile_length = len; break; case 37122: /* CompressedBitsPerPixel */ kodak_cbpp = get4(); break; case 37386: /* FocalLength */ focal_len = getreal(type); break; case 37393: /* ImageNumber */ shot_order = getint(type); break; case 37400: /* old Kodak KDC tag */ for (raw_color = i = 0; i < 3; i++) { getreal(type); FORC3 rgb_cam[i][c] = getreal(type); } break; case 40976: strip_offset = get4(); switch (tiff_ifd[ifd].comp) { case 32770: load_raw = &CLASS samsung_load_raw; break; case 32772: load_raw = &CLASS samsung2_load_raw; break; case 32773: load_raw = &CLASS samsung3_load_raw; break; } break; case 46275: /* Imacon tags */ strcpy(make, "Imacon"); data_offset = ftell(ifp); ima_len = len; break; case 46279: if (!ima_len) break; fseek(ifp, 38, SEEK_CUR); case 46274: fseek(ifp, 40, SEEK_CUR); raw_width = get4(); raw_height = get4(); left_margin = get4() & 7; width = raw_width - left_margin - (get4() & 7); top_margin = get4() & 7; height = raw_height - top_margin - (get4() & 7); if (raw_width == 7262 && ima_len == 234317952) { height = 5412; width = 7216; left_margin = 7; filters = 0; } else if (raw_width == 7262) { height = 5444; width = 7244; left_margin = 7; } fseek(ifp, 52, SEEK_CUR); FORC3 cam_mul[c] = getreal(11); fseek(ifp, 114, SEEK_CUR); flip = (get2() >> 7) * 90; if (width * height * 6 == ima_len) { if (flip % 180 == 90) SWAP(width, height); raw_width = width; raw_height = height; left_margin = top_margin = filters = flip = 0; } sprintf(model, "Ixpress %d-Mp", height * width / 1000000); load_raw = &CLASS imacon_full_load_raw; if (filters) { if (left_margin & 1) filters = 0x61616161; load_raw = &CLASS unpacked_load_raw; } maximum = 0xffff; break; case 50454: /* Sinar tag */ case 50455: if (len < 1 || len > 2560000 || !(cbuf = (char *)malloc(len))) break; #ifndef LIBRAW_LIBRARY_BUILD fread(cbuf, 1, len, ifp); #else if (fread(cbuf, 1, len, ifp) != len) throw LIBRAW_EXCEPTION_IO_CORRUPT; // cbuf to be free'ed in recycle #endif cbuf[len - 1] = 0; for (cp = cbuf - 1; cp && cp < cbuf + len; cp = strchr(cp, '\n')) if (!strncmp(++cp, "Neutral ", 8)) sscanf(cp + 8, "%f %f %f", cam_mul, cam_mul + 1, cam_mul + 2); free(cbuf); break; case 50458: if (!make[0]) strcpy(make, "Hasselblad"); break; case 50459: /* Hasselblad tag */ #ifdef LIBRAW_LIBRARY_BUILD libraw_internal_data.unpacker_data.hasselblad_parser_flag = 1; #endif i = order; j = ftell(ifp); c = tiff_nifds; order = get2(); fseek(ifp, j + (get2(), get4()), SEEK_SET); parse_tiff_ifd(j); maximum = 0xffff; tiff_nifds = c; order = i; break; case 50706: /* DNGVersion */ FORC4 dng_version = (dng_version << 8) + fgetc(ifp); if (!make[0]) strcpy(make, "DNG"); is_raw = 1; break; case 50708: /* UniqueCameraModel */ #ifdef LIBRAW_LIBRARY_BUILD stmread(imgdata.color.UniqueCameraModel, len, ifp); imgdata.color.UniqueCameraModel[sizeof(imgdata.color.UniqueCameraModel) - 1] = 0; #endif if (model[0]) break; #ifndef LIBRAW_LIBRARY_BUILD fgets(make, 64, ifp); #else strncpy(make, imgdata.color.UniqueCameraModel, MIN(len, sizeof(imgdata.color.UniqueCameraModel))); #endif if ((cp = strchr(make, ' '))) { strcpy(model, cp + 1); *cp = 0; } break; case 50710: /* CFAPlaneColor */ if (filters == 9) break; if (len > 4) len = 4; colors = len; fread(cfa_pc, 1, colors, ifp); guess_cfa_pc: FORCC tab[cfa_pc[c]] = c; cdesc[c] = 0; for (i = 16; i--;) filters = filters << 2 | tab[cfa_pat[i % plen]]; filters -= !filters; break; case 50711: /* CFALayout */ if (get2() == 2) fuji_width = 1; break; case 291: case 50712: /* LinearizationTable */ #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_LINTABLE; tiff_ifd[ifd].lineartable_offset = ftell(ifp); tiff_ifd[ifd].lineartable_len = len; #endif linear_table(len); break; case 50713: /* BlackLevelRepeatDim */ #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK; tiff_ifd[ifd].dng_levels.dng_cblack[4] = #endif cblack[4] = get2(); #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.dng_cblack[5] = #endif cblack[5] = get2(); if (cblack[4] * cblack[5] > (sizeof(cblack) / sizeof(cblack[0]) - 6)) #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.dng_cblack[4] = tiff_ifd[ifd].dng_levels.dng_cblack[5] = #endif cblack[4] = cblack[5] = 1; break; #ifdef LIBRAW_LIBRARY_BUILD case 0xf00d: if (strcmp(model, "X-A3") && strcmp(model, "X-A10")) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][(4 - c) % 3] = getint(type); imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1]; } break; case 0xf00c: if (strcmp(model, "X-A3") && strcmp(model, "X-A10")) { unsigned fwb[4]; FORC4 fwb[c] = get4(); if (fwb[3] < 0x100) { imgdata.color.WB_Coeffs[fwb[3]][0] = fwb[1]; imgdata.color.WB_Coeffs[fwb[3]][1] = imgdata.color.WB_Coeffs[fwb[3]][3] = fwb[0]; imgdata.color.WB_Coeffs[fwb[3]][2] = fwb[2]; if ((fwb[3] == 17) && (libraw_internal_data.unpacker_data.lenRAFData > 3) && (libraw_internal_data.unpacker_data.lenRAFData < 10240000)) { INT64 f_save = ftell(ifp); ushort *rafdata = (ushort *)malloc(sizeof(ushort) * libraw_internal_data.unpacker_data.lenRAFData); fseek(ifp, libraw_internal_data.unpacker_data.posRAFData, SEEK_SET); fread(rafdata, sizeof(ushort), libraw_internal_data.unpacker_data.lenRAFData, ifp); fseek(ifp, f_save, SEEK_SET); int fj, found = 0; for (int fi = 0; fi < (libraw_internal_data.unpacker_data.lenRAFData - 3); fi++) { if ((fwb[0] == rafdata[fi]) && (fwb[1] == rafdata[fi + 1]) && (fwb[2] == rafdata[fi + 2])) { if (rafdata[fi - 15] != fwb[0]) continue; for (int wb_ind = 0, ofst = fi - 15; wb_ind < nFuji_wb_list1; wb_ind++, ofst += 3) { imgdata.color.WB_Coeffs[Fuji_wb_list1[wb_ind]][1] = imgdata.color.WB_Coeffs[Fuji_wb_list1[wb_ind]][3] = rafdata[ofst]; imgdata.color.WB_Coeffs[Fuji_wb_list1[wb_ind]][0] = rafdata[ofst + 1]; imgdata.color.WB_Coeffs[Fuji_wb_list1[wb_ind]][2] = rafdata[ofst + 2]; } fi += 0x60; for (fj = fi; fj < (fi + 15); fj += 3) if (rafdata[fj] != rafdata[fi]) { found = 1; break; } if (found) { fj = fj - 93; for (int iCCT = 0; iCCT < 31; iCCT++) { imgdata.color.WBCT_Coeffs[iCCT][0] = FujiCCT_K[iCCT]; imgdata.color.WBCT_Coeffs[iCCT][1] = rafdata[iCCT * 3 + 1 + fj]; imgdata.color.WBCT_Coeffs[iCCT][2] = imgdata.color.WBCT_Coeffs[iCCT][4] = rafdata[iCCT * 3 + fj]; imgdata.color.WBCT_Coeffs[iCCT][3] = rafdata[iCCT * 3 + 2 + fj]; } } free(rafdata); break; } } } } FORC4 fwb[c] = get4(); if (fwb[3] < 0x100) { imgdata.color.WB_Coeffs[fwb[3]][0] = fwb[1]; imgdata.color.WB_Coeffs[fwb[3]][1] = imgdata.color.WB_Coeffs[fwb[3]][3] = fwb[0]; imgdata.color.WB_Coeffs[fwb[3]][2] = fwb[2]; } } break; #endif #ifdef LIBRAW_LIBRARY_BUILD case 50709: stmread(imgdata.color.LocalizedCameraModel, len, ifp); break; #endif case 61450: cblack[4] = cblack[5] = MIN(sqrt((double)len), 64); case 50714: /* BlackLevel */ #ifdef LIBRAW_LIBRARY_BUILD if (tiff_ifd[ifd].samples > 1 && tiff_ifd[ifd].samples == len) // LinearDNG, per-channel black { tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK; for (i = 0; i < colors && i < 4 && i < len; i++) tiff_ifd[ifd].dng_levels.dng_cblack[i] = cblack[i] = getreal(type) + 0.5; tiff_ifd[ifd].dng_levels.dng_black = black = 0; } else #endif if ((cblack[4] * cblack[5] < 2) && len == 1) { #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK; tiff_ifd[ifd].dng_levels.dng_black = #endif black = getreal(type); } else if (cblack[4] * cblack[5] <= len) { FORC(cblack[4] * cblack[5]) cblack[6 + c] = getreal(type); black = 0; FORC4 cblack[c] = 0; #ifdef LIBRAW_LIBRARY_BUILD if (tag == 50714) { tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK; FORC(cblack[4] * cblack[5]) tiff_ifd[ifd].dng_levels.dng_cblack[6 + c] = cblack[6 + c]; tiff_ifd[ifd].dng_levels.dng_black = 0; FORC4 tiff_ifd[ifd].dng_levels.dng_cblack[c] = 0; } #endif } break; case 50715: /* BlackLevelDeltaH */ case 50716: /* BlackLevelDeltaV */ for (num = i = 0; i < len && i < 65536; i++) num += getreal(type); black += num / len + 0.5; #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.dng_black += num / len + 0.5; tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK; #endif break; case 50717: /* WhiteLevel */ #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_WHITE; tiff_ifd[ifd].dng_levels.dng_whitelevel[0] = #endif maximum = getint(type); #ifdef LIBRAW_LIBRARY_BUILD if (tiff_ifd[ifd].samples > 1) // Linear DNG case for (i = 1; i < colors && i < 4 && i < len; i++) tiff_ifd[ifd].dng_levels.dng_whitelevel[i] = getint(type); #endif break; case 50718: /* DefaultScale */ pixel_aspect = getreal(type); pixel_aspect /= getreal(type); if (pixel_aspect > 0.995 && pixel_aspect < 1.005) pixel_aspect = 1.0; break; #ifdef LIBRAW_LIBRARY_BUILD case 50719: /* DefaultCropOrigin */ if (len == 2) { tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_CROPORIGIN; tiff_ifd[ifd].dng_levels.default_crop[0] = getreal(type); tiff_ifd[ifd].dng_levels.default_crop[1] = getreal(type); } break; case 50720: /* DefaultCropSize */ if (len == 2) { tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_CROPSIZE; tiff_ifd[ifd].dng_levels.default_crop[2] = getreal(type); tiff_ifd[ifd].dng_levels.default_crop[3] = getreal(type); } break; #endif #ifdef LIBRAW_LIBRARY_BUILD case 50778: tiff_ifd[ifd].dng_color[0].illuminant = get2(); tiff_ifd[ifd].dng_color[0].parsedfields |= LIBRAW_DNGFM_ILLUMINANT; break; case 50779: tiff_ifd[ifd].dng_color[1].illuminant = get2(); tiff_ifd[ifd].dng_color[1].parsedfields |= LIBRAW_DNGFM_ILLUMINANT; break; #endif case 50721: /* ColorMatrix1 */ case 50722: /* ColorMatrix2 */ #ifdef LIBRAW_LIBRARY_BUILD i = tag == 50721 ? 0 : 1; tiff_ifd[ifd].dng_color[i].parsedfields |= LIBRAW_DNGFM_COLORMATRIX; #endif FORCC for (j = 0; j < 3; j++) { #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_color[i].colormatrix[c][j] = #endif cm[c][j] = getreal(type); } use_cm = 1; break; case 0xc714: /* ForwardMatrix1 */ case 0xc715: /* ForwardMatrix2 */ #ifdef LIBRAW_LIBRARY_BUILD i = tag == 0xc714 ? 0 : 1; tiff_ifd[ifd].dng_color[i].parsedfields |= LIBRAW_DNGFM_FORWARDMATRIX; #endif for (j = 0; j < 3; j++) FORCC { #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_color[i].forwardmatrix[j][c] = #endif fm[j][c] = getreal(type); } break; case 50723: /* CameraCalibration1 */ case 50724: /* CameraCalibration2 */ #ifdef LIBRAW_LIBRARY_BUILD j = tag == 50723 ? 0 : 1; tiff_ifd[ifd].dng_color[j].parsedfields |= LIBRAW_DNGFM_CALIBRATION; #endif for (i = 0; i < colors; i++) FORCC { #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_color[j].calibration[i][c] = #endif cc[i][c] = getreal(type); } break; case 50727: /* AnalogBalance */ #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_ANALOGBALANCE; #endif FORCC { #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.analogbalance[c] = #endif ab[c] = getreal(type); } break; case 50728: /* AsShotNeutral */ FORCC asn[c] = getreal(type); break; case 50729: /* AsShotWhiteXY */ xyz[0] = getreal(type); xyz[1] = getreal(type); xyz[2] = 1 - xyz[0] - xyz[1]; FORC3 xyz[c] /= d65_white[c]; break; #ifdef LIBRAW_LIBRARY_BUILD case 50730: /* DNG: Baseline Exposure */ baseline_exposure = getreal(type); break; #endif // IB start case 50740: /* tag 0xc634 : DNG Adobe, DNG Pentax, Sony SR2, DNG Private */ #ifdef LIBRAW_LIBRARY_BUILD { char mbuf[64]; unsigned short makernote_found = 0; INT64 curr_pos, start_pos = ftell(ifp); unsigned MakN_order, m_sorder = order; unsigned MakN_length; unsigned pos_in_original_raw; fread(mbuf, 1, 6, ifp); if (!strcmp(mbuf, "Adobe")) { order = 0x4d4d; // Adobe header is always in "MM" / big endian curr_pos = start_pos + 6; while (curr_pos + 8 - start_pos <= len) { fread(mbuf, 1, 4, ifp); curr_pos += 8; if (!strncmp(mbuf, "MakN", 4)) { makernote_found = 1; MakN_length = get4(); MakN_order = get2(); pos_in_original_raw = get4(); order = MakN_order; parse_makernote_0xc634(curr_pos + 6 - pos_in_original_raw, 0, AdobeDNG); break; } } } else { fread(mbuf + 6, 1, 2, ifp); if (!strcmp(mbuf, "PENTAX ") || !strcmp(mbuf, "SAMSUNG")) { makernote_found = 1; fseek(ifp, start_pos, SEEK_SET); parse_makernote_0xc634(base, 0, CameraDNG); } } fseek(ifp, start_pos, SEEK_SET); order = m_sorder; } // IB end #endif if (dng_version) break; parse_minolta(j = get4() + base); fseek(ifp, j, SEEK_SET); parse_tiff_ifd(base); break; case 50752: read_shorts(cr2_slice, 3); break; case 50829: /* ActiveArea */ top_margin = getint(type); left_margin = getint(type); height = getint(type) - top_margin; width = getint(type) - left_margin; break; case 50830: /* MaskedAreas */ for (i = 0; i < len && i < 32; i++) ((int *)mask)[i] = getint(type); black = 0; break; #ifdef LIBRAW_LIBRARY_BUILD case 50970: /* PreviewColorSpace */ tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_PREVIEWCS; tiff_ifd[ifd].dng_levels.preview_colorspace = getint(type); break; #endif case 51009: /* OpcodeList2 */ #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_OPCODE2; tiff_ifd[ifd].opcode2_offset = #endif meta_offset = ftell(ifp); break; case 64772: /* Kodak P-series */ if (len < 13) break; fseek(ifp, 16, SEEK_CUR); data_offset = get4(); fseek(ifp, 28, SEEK_CUR); data_offset += get4(); load_raw = &CLASS packed_load_raw; break; case 65026: if (type == 2) fgets(model2, 64, ifp); } fseek(ifp, save, SEEK_SET); } if (sony_length && sony_length < 10240000 && (buf = (unsigned *)malloc(sony_length))) { fseek(ifp, sony_offset, SEEK_SET); fread(buf, sony_length, 1, ifp); sony_decrypt(buf, sony_length / 4, 1, sony_key); #ifndef LIBRAW_LIBRARY_BUILD sfp = ifp; if ((ifp = tmpfile())) { fwrite(buf, sony_length, 1, ifp); fseek(ifp, 0, SEEK_SET); parse_tiff_ifd(-sony_offset); fclose(ifp); } ifp = sfp; #else if (!ifp->tempbuffer_open(buf, sony_length)) { parse_tiff_ifd(-sony_offset); ifp->tempbuffer_close(); } #endif free(buf); } for (i = 0; i < colors; i++) FORCC cc[i][c] *= ab[i]; if (use_cm) { FORCC for (i = 0; i < 3; i++) for (cam_xyz[c][i] = j = 0; j < colors; j++) cam_xyz[c][i] += cc[c][j] * cm[j][i] * xyz[i]; cam_xyz_coeff(cmatrix, cam_xyz); } if (asn[0]) { cam_mul[3] = 0; FORCC cam_mul[c] = 1 / asn[c]; } if (!use_cm) FORCC pre_mul[c] /= cc[c][c]; return 0; } int CLASS parse_tiff(int base) { int doff; fseek(ifp, base, SEEK_SET); order = get2(); if (order != 0x4949 && order != 0x4d4d) return 0; get2(); while ((doff = get4())) { fseek(ifp, doff + base, SEEK_SET); if (parse_tiff_ifd(base)) break; } return 1; } void CLASS apply_tiff() { int max_samp = 0, ties = 0, raw = -1, thm = -1, i; unsigned long long ns, os; struct jhead jh; thumb_misc = 16; if (thumb_offset) { fseek(ifp, thumb_offset, SEEK_SET); if (ljpeg_start(&jh, 1)) { if ((unsigned)jh.bits < 17 && (unsigned)jh.wide < 0x10000 && (unsigned)jh.high < 0x10000) { thumb_misc = jh.bits; thumb_width = jh.wide; thumb_height = jh.high; } } } for (i = tiff_nifds; i--;) { if (tiff_ifd[i].t_shutter) shutter = tiff_ifd[i].t_shutter; tiff_ifd[i].t_shutter = shutter; } for (i = 0; i < tiff_nifds; i++) { if (max_samp < tiff_ifd[i].samples) max_samp = tiff_ifd[i].samples; if (max_samp > 3) max_samp = 3; os = raw_width * raw_height; ns = tiff_ifd[i].t_width * tiff_ifd[i].t_height; if (tiff_bps) { os *= tiff_bps; ns *= tiff_ifd[i].bps; } if ((tiff_ifd[i].comp != 6 || tiff_ifd[i].samples != 3) && unsigned(tiff_ifd[i].t_width | tiff_ifd[i].t_height) < 0x10000 && (unsigned)tiff_ifd[i].bps < 33 && (unsigned)tiff_ifd[i].samples < 13 && ns && ((ns > os && (ties = 1)) || (ns == os && shot_select == ties++))) { raw_width = tiff_ifd[i].t_width; raw_height = tiff_ifd[i].t_height; tiff_bps = tiff_ifd[i].bps; tiff_compress = tiff_ifd[i].comp; data_offset = tiff_ifd[i].offset; #ifdef LIBRAW_LIBRARY_BUILD data_size = tiff_ifd[i].bytes; #endif tiff_flip = tiff_ifd[i].t_flip; tiff_samples = tiff_ifd[i].samples; tile_width = tiff_ifd[i].t_tile_width; tile_length = tiff_ifd[i].t_tile_length; shutter = tiff_ifd[i].t_shutter; raw = i; } } if (is_raw == 1 && ties) is_raw = ties; if (!tile_width) tile_width = INT_MAX; if (!tile_length) tile_length = INT_MAX; for (i = tiff_nifds; i--;) if (tiff_ifd[i].t_flip) tiff_flip = tiff_ifd[i].t_flip; if (raw >= 0 && !load_raw) switch (tiff_compress) { case 32767: if (tiff_ifd[raw].bytes == raw_width * raw_height) { tiff_bps = 12; load_raw = &CLASS sony_arw2_load_raw; break; } if (!strncasecmp(make, "Sony", 4) && tiff_ifd[raw].bytes == raw_width * raw_height * 2) { tiff_bps = 14; load_raw = &CLASS unpacked_load_raw; break; } if (tiff_ifd[raw].bytes * 8 != raw_width * raw_height * tiff_bps) { raw_height += 8; load_raw = &CLASS sony_arw_load_raw; break; } load_flags = 79; case 32769: load_flags++; case 32770: case 32773: goto slr; case 0: case 1: #ifdef LIBRAW_LIBRARY_BUILD // Sony 14-bit uncompressed if (!strncasecmp(make, "Sony", 4) && tiff_ifd[raw].bytes == raw_width * raw_height * 2) { tiff_bps = 14; load_raw = &CLASS unpacked_load_raw; break; } if (!strncasecmp(make, "Nikon", 5) && !strncmp(software, "Nikon Scan", 10)) { load_raw = &CLASS nikon_coolscan_load_raw; raw_color = 1; filters = 0; break; } #endif if (!strncmp(make, "OLYMPUS", 7) && tiff_ifd[raw].bytes * 2 == raw_width * raw_height * 3) load_flags = 24; if (tiff_ifd[raw].bytes * 5 == raw_width * raw_height * 8) { load_flags = 81; tiff_bps = 12; } slr: switch (tiff_bps) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 12: if (tiff_ifd[raw].phint == 2) load_flags = 6; load_raw = &CLASS packed_load_raw; break; case 14: load_flags = 0; case 16: load_raw = &CLASS unpacked_load_raw; if (!strncmp(make, "OLYMPUS", 7) && tiff_ifd[raw].bytes * 7 > raw_width * raw_height) load_raw = &CLASS olympus_load_raw; } break; case 6: case 7: case 99: load_raw = &CLASS lossless_jpeg_load_raw; break; case 262: load_raw = &CLASS kodak_262_load_raw; break; case 34713: if ((raw_width + 9) / 10 * 16 * raw_height == tiff_ifd[raw].bytes) { load_raw = &CLASS packed_load_raw; load_flags = 1; } else if (raw_width * raw_height * 3 == tiff_ifd[raw].bytes * 2) { load_raw = &CLASS packed_load_raw; if (model[0] == 'N') load_flags = 80; } else if (raw_width * raw_height * 3 == tiff_ifd[raw].bytes) { load_raw = &CLASS nikon_yuv_load_raw; gamma_curve(1 / 2.4, 12.92, 1, 4095); memset(cblack, 0, sizeof cblack); filters = 0; } else if (raw_width * raw_height * 2 == tiff_ifd[raw].bytes) { load_raw = &CLASS unpacked_load_raw; load_flags = 4; order = 0x4d4d; } else #ifdef LIBRAW_LIBRARY_BUILD if (raw_width * raw_height * 3 == tiff_ifd[raw].bytes * 2) { load_raw = &CLASS packed_load_raw; load_flags = 80; } else if (tiff_ifd[raw].rows_per_strip && tiff_ifd[raw].strip_offsets_count && tiff_ifd[raw].strip_offsets_count == tiff_ifd[raw].strip_byte_counts_count) { int fit = 1; for (int i = 0; i < tiff_ifd[raw].strip_byte_counts_count - 1; i++) // all but last if (tiff_ifd[raw].strip_byte_counts[i] * 2 != tiff_ifd[raw].rows_per_strip * raw_width * 3) { fit = 0; break; } if (fit) load_raw = &CLASS nikon_load_striped_packed_raw; else load_raw = &CLASS nikon_load_raw; // fallback } else #endif load_raw = &CLASS nikon_load_raw; break; case 65535: load_raw = &CLASS pentax_load_raw; break; case 65000: switch (tiff_ifd[raw].phint) { case 2: load_raw = &CLASS kodak_rgb_load_raw; filters = 0; break; case 6: load_raw = &CLASS kodak_ycbcr_load_raw; filters = 0; break; case 32803: load_raw = &CLASS kodak_65000_load_raw; } case 32867: case 34892: break; #ifdef LIBRAW_LIBRARY_BUILD case 8: break; #endif default: is_raw = 0; } if (!dng_version) if (((tiff_samples == 3 && tiff_ifd[raw].bytes && tiff_bps != 14 && (tiff_compress & -16) != 32768) || (tiff_bps == 8 && strncmp(make, "Phase", 5) && strncmp(make, "Leaf", 4) && !strcasestr(make, "Kodak") && !strstr(model2, "DEBUG RAW"))) && strncmp(software, "Nikon Scan", 10)) is_raw = 0; for (i = 0; i < tiff_nifds; i++) if (i != raw && (tiff_ifd[i].samples == max_samp || (tiff_ifd[i].comp == 7 && tiff_ifd[i].samples == 1)) /* Allow 1-bps JPEGs */ && tiff_ifd[i].bps > 0 && tiff_ifd[i].bps < 33 && tiff_ifd[i].phint != 32803 && tiff_ifd[i].phint != 34892 && unsigned(tiff_ifd[i].t_width | tiff_ifd[i].t_height) < 0x10000 && tiff_ifd[i].t_width * tiff_ifd[i].t_height / (SQR(tiff_ifd[i].bps) + 1) > thumb_width * thumb_height / (SQR(thumb_misc) + 1) && tiff_ifd[i].comp != 34892) { thumb_width = tiff_ifd[i].t_width; thumb_height = tiff_ifd[i].t_height; thumb_offset = tiff_ifd[i].offset; thumb_length = tiff_ifd[i].bytes; thumb_misc = tiff_ifd[i].bps; thm = i; } if (thm >= 0) { thumb_misc |= tiff_ifd[thm].samples << 5; switch (tiff_ifd[thm].comp) { case 0: write_thumb = &CLASS layer_thumb; break; case 1: if (tiff_ifd[thm].bps <= 8) write_thumb = &CLASS ppm_thumb; else if (!strncmp(make, "Imacon", 6)) write_thumb = &CLASS ppm16_thumb; else thumb_load_raw = &CLASS kodak_thumb_load_raw; break; case 65000: thumb_load_raw = tiff_ifd[thm].phint == 6 ? &CLASS kodak_ycbcr_load_raw : &CLASS kodak_rgb_load_raw; } } } void CLASS parse_minolta(int base) { int save, tag, len, offset, high = 0, wide = 0, i, c; short sorder = order; fseek(ifp, base, SEEK_SET); if (fgetc(ifp) || fgetc(ifp) - 'M' || fgetc(ifp) - 'R') return; order = fgetc(ifp) * 0x101; offset = base + get4() + 8; while ((save = ftell(ifp)) < offset) { for (tag = i = 0; i < 4; i++) tag = tag << 8 | fgetc(ifp); len = get4(); switch (tag) { case 0x505244: /* PRD */ fseek(ifp, 8, SEEK_CUR); high = get2(); wide = get2(); break; #ifdef LIBRAW_LIBRARY_BUILD case 0x524946: /* RIF */ if (!strncasecmp(model, "DSLR-A100", 9)) { fseek(ifp, 8, SEEK_CUR); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][2] = get2(); get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][3] = 0x100; } break; #endif case 0x574247: /* WBG */ get4(); i = strcmp(model, "DiMAGE A200") ? 0 : 3; FORC4 cam_mul[c ^ (c >> 1) ^ i] = get2(); break; case 0x545457: /* TTW */ parse_tiff(ftell(ifp)); data_offset = offset; } fseek(ifp, save + len + 8, SEEK_SET); } raw_height = high; raw_width = wide; order = sorder; } /* Many cameras have a "debug mode" that writes JPEG and raw at the same time. The raw file has no header, so try to to open the matching JPEG file and read its metadata. */ void CLASS parse_external_jpeg() { const char *file, *ext; char *jname, *jfile, *jext; #ifndef LIBRAW_LIBRARY_BUILD FILE *save = ifp; #else #if defined(_WIN32) && !defined(__MINGW32__) && defined(_MSC_VER) && (_MSC_VER > 1310) if (ifp->wfname()) { std::wstring rawfile(ifp->wfname()); rawfile.replace(rawfile.length() - 3, 3, L"JPG"); if (!ifp->subfile_open(rawfile.c_str())) { parse_tiff(12); thumb_offset = 0; is_raw = 1; ifp->subfile_close(); } else imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA; return; } #endif if (!ifp->fname()) { imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA; return; } #endif ext = strrchr(ifname, '.'); file = strrchr(ifname, '/'); if (!file) file = strrchr(ifname, '\\'); #ifndef LIBRAW_LIBRARY_BUILD if (!file) file = ifname - 1; #else if (!file) file = (char *)ifname - 1; #endif file++; if (!ext || strlen(ext) != 4 || ext - file != 8) return; jname = (char *)malloc(strlen(ifname) + 1); merror(jname, "parse_external_jpeg()"); strcpy(jname, ifname); jfile = file - ifname + jname; jext = ext - ifname + jname; if (strcasecmp(ext, ".jpg")) { strcpy(jext, isupper(ext[1]) ? ".JPG" : ".jpg"); if (isdigit(*file)) { memcpy(jfile, file + 4, 4); memcpy(jfile + 4, file, 4); } } else while (isdigit(*--jext)) { if (*jext != '9') { (*jext)++; break; } *jext = '0'; } #ifndef LIBRAW_LIBRARY_BUILD if (strcmp(jname, ifname)) { if ((ifp = fopen(jname, "rb"))) { #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Reading metadata from %s ...\n"), jname); #endif parse_tiff(12); thumb_offset = 0; is_raw = 1; fclose(ifp); } } #else if (strcmp(jname, ifname)) { if (!ifp->subfile_open(jname)) { parse_tiff(12); thumb_offset = 0; is_raw = 1; ifp->subfile_close(); } else imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA; } #endif if (!timestamp) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA; #endif #ifdef DCRAW_VERBOSE fprintf(stderr, _("Failed to read metadata from %s\n"), jname); #endif } free(jname); #ifndef LIBRAW_LIBRARY_BUILD ifp = save; #endif } /* CIFF block 0x1030 contains an 8x8 white sample. Load this into white[][] for use in scale_colors(). */ void CLASS ciff_block_1030() { static const ushort key[] = {0x410, 0x45f3}; int i, bpp, row, col, vbits = 0; unsigned long bitbuf = 0; if ((get2(), get4()) != 0x80008 || !get4()) return; bpp = get2(); if (bpp != 10 && bpp != 12) return; for (i = row = 0; row < 8; row++) for (col = 0; col < 8; col++) { if (vbits < bpp) { bitbuf = bitbuf << 16 | (get2() ^ key[i++ & 1]); vbits += 16; } white[row][col] = bitbuf >> (vbits -= bpp) & ~(-1 << bpp); } } /* Parse a CIFF file, better known as Canon CRW format. */ void CLASS parse_ciff(int offset, int length, int depth) { int tboff, nrecs, c, type, len, save, wbi = -1; ushort key[] = {0x410, 0x45f3}; fseek(ifp, offset + length - 4, SEEK_SET); tboff = get4() + offset; fseek(ifp, tboff, SEEK_SET); nrecs = get2(); if ((nrecs | depth) > 127) return; while (nrecs--) { type = get2(); len = get4(); save = ftell(ifp) + 4; fseek(ifp, offset + get4(), SEEK_SET); if ((((type >> 8) + 8) | 8) == 0x38) { parse_ciff(ftell(ifp), len, depth + 1); /* Parse a sub-table */ } #ifdef LIBRAW_LIBRARY_BUILD if (type == 0x3004) parse_ciff(ftell(ifp), len, depth + 1); #endif if (type == 0x0810) fread(artist, 64, 1, ifp); if (type == 0x080a) { fread(make, 64, 1, ifp); fseek(ifp, strbuflen(make) - 63, SEEK_CUR); fread(model, 64, 1, ifp); } if (type == 0x1810) { width = get4(); height = get4(); pixel_aspect = int_to_float(get4()); flip = get4(); } if (type == 0x1835) /* Get the decoder table */ tiff_compress = get4(); if (type == 0x2007) { thumb_offset = ftell(ifp); thumb_length = len; } if (type == 0x1818) { shutter = powf64(2.0f, -int_to_float((get4(), get4()))); aperture = powf64(2.0f, int_to_float(get4()) / 2); #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CurAp = aperture; #endif } if (type == 0x102a) { // iso_speed = pow (2.0, (get4(),get2())/32.0 - 4) * 50; iso_speed = powf64(2.0f, ((get2(), get2()) + get2()) / 32.0f - 5.0f) * 100.0f; #ifdef LIBRAW_LIBRARY_BUILD aperture = _CanonConvertAperture((get2(), get2())); imgdata.lens.makernotes.CurAp = aperture; #else aperture = powf64(2.0, (get2(), (short)get2()) / 64.0); #endif shutter = powf64(2.0, -((short)get2()) / 32.0); wbi = (get2(), get2()); if (wbi > 17) wbi = 0; fseek(ifp, 32, SEEK_CUR); if (shutter > 1e6) shutter = get2() / 10.0; } if (type == 0x102c) { if (get2() > 512) { /* Pro90, G1 */ fseek(ifp, 118, SEEK_CUR); FORC4 cam_mul[c ^ 2] = get2(); } else { /* G2, S30, S40 */ fseek(ifp, 98, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get2(); } } #ifdef LIBRAW_LIBRARY_BUILD if (type == 0x10a9) { INT64 o = ftell(ifp); fseek(ifp, (0x1 << 1), SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); Canon_WBpresets(0, 0); fseek(ifp, o, SEEK_SET); } if (type == 0x102d) { INT64 o = ftell(ifp); Canon_CameraSettings(); fseek(ifp, o, SEEK_SET); } if (type == 0x580b) { if (strcmp(model, "Canon EOS D30")) sprintf(imgdata.shootinginfo.BodySerial, "%d", len); else sprintf(imgdata.shootinginfo.BodySerial, "%0x-%05d", len >> 16, len & 0xffff); } #endif if (type == 0x0032) { if (len == 768) { /* EOS D30 */ fseek(ifp, 72, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = 1024.0 / get2(); if (!wbi) cam_mul[0] = -1; /* use my auto white balance */ } else if (!cam_mul[0]) { if (get2() == key[0]) /* Pro1, G6, S60, S70 */ c = (strstr(model, "Pro1") ? "012346000000000000" : "01345:000000006008")[LIM(0, wbi, 17)] - '0' + 2; else { /* G3, G5, S45, S50 */ c = "023457000000006000"[LIM(0, wbi, 17)] - '0'; key[0] = key[1] = 0; } fseek(ifp, 78 + c * 8, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get2() ^ key[c & 1]; if (!wbi) cam_mul[0] = -1; } } if (type == 0x10a9) { /* D60, 10D, 300D, and clones */ if (len > 66) wbi = "0134567028"[LIM(0, wbi, 9)] - '0'; fseek(ifp, 2 + wbi * 8, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); } if (type == 0x1030 && wbi >= 0 && (0x18040 >> wbi & 1)) ciff_block_1030(); /* all that don't have 0x10a9 */ if (type == 0x1031) { raw_width = (get2(), get2()); raw_height = get2(); } if (type == 0x501c) { iso_speed = len & 0xffff; } if (type == 0x5029) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CurFocal = len >> 16; imgdata.lens.makernotes.FocalType = len & 0xffff; if (imgdata.lens.makernotes.FocalType == 2) { imgdata.lens.makernotes.CanonFocalUnits = 32; if (imgdata.lens.makernotes.CanonFocalUnits > 1) imgdata.lens.makernotes.CurFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; } focal_len = imgdata.lens.makernotes.CurFocal; #else focal_len = len >> 16; if ((len & 0xffff) == 2) focal_len /= 32; #endif } if (type == 0x5813) flash_used = int_to_float(len); if (type == 0x5814) canon_ev = int_to_float(len); if (type == 0x5817) shot_order = len; if (type == 0x5834) { unique_id = len; #ifdef LIBRAW_LIBRARY_BUILD setCanonBodyFeatures(unique_id); #endif } if (type == 0x580e) timestamp = len; if (type == 0x180e) timestamp = get4(); #ifdef LOCALTIME if ((type | 0x4000) == 0x580e) timestamp = mktime(gmtime(&timestamp)); #endif fseek(ifp, save, SEEK_SET); } } void CLASS parse_rollei() { char line[128], *val; struct tm t; fseek(ifp, 0, SEEK_SET); memset(&t, 0, sizeof t); do { fgets(line, 128, ifp); if ((val = strchr(line, '='))) *val++ = 0; else val = line + strbuflen(line); if (!strcmp(line, "DAT")) sscanf(val, "%d.%d.%d", &t.tm_mday, &t.tm_mon, &t.tm_year); if (!strcmp(line, "TIM")) sscanf(val, "%d:%d:%d", &t.tm_hour, &t.tm_min, &t.tm_sec); if (!strcmp(line, "HDR")) thumb_offset = atoi(val); if (!strcmp(line, "X ")) raw_width = atoi(val); if (!strcmp(line, "Y ")) raw_height = atoi(val); if (!strcmp(line, "TX ")) thumb_width = atoi(val); if (!strcmp(line, "TY ")) thumb_height = atoi(val); } while (strncmp(line, "EOHD", 4)); data_offset = thumb_offset + thumb_width * thumb_height * 2; t.tm_year -= 1900; t.tm_mon -= 1; if (mktime(&t) > 0) timestamp = mktime(&t); strcpy(make, "Rollei"); strcpy(model, "d530flex"); write_thumb = &CLASS rollei_thumb; } void CLASS parse_sinar_ia() { int entries, off; char str[8], *cp; order = 0x4949; fseek(ifp, 4, SEEK_SET); entries = get4(); fseek(ifp, get4(), SEEK_SET); while (entries--) { off = get4(); get4(); fread(str, 8, 1, ifp); if (!strcmp(str, "META")) meta_offset = off; if (!strcmp(str, "THUMB")) thumb_offset = off; if (!strcmp(str, "RAW0")) data_offset = off; } fseek(ifp, meta_offset + 20, SEEK_SET); fread(make, 64, 1, ifp); make[63] = 0; if ((cp = strchr(make, ' '))) { strcpy(model, cp + 1); *cp = 0; } raw_width = get2(); raw_height = get2(); load_raw = &CLASS unpacked_load_raw; thumb_width = (get4(), get2()); thumb_height = get2(); write_thumb = &CLASS ppm_thumb; maximum = 0x3fff; } void CLASS parse_phase_one(int base) { unsigned entries, tag, type, len, data, save, i, c; float romm_cam[3][3]; char *cp; memset(&ph1, 0, sizeof ph1); fseek(ifp, base, SEEK_SET); order = get4() & 0xffff; if (get4() >> 8 != 0x526177) return; /* "Raw" */ fseek(ifp, get4() + base, SEEK_SET); entries = get4(); get4(); while (entries--) { tag = get4(); type = get4(); len = get4(); data = get4(); save = ftell(ifp); fseek(ifp, base + data, SEEK_SET); switch (tag) { #ifdef LIBRAW_LIBRARY_BUILD case 0x0102: stmread(imgdata.shootinginfo.BodySerial, len, ifp); if ((imgdata.shootinginfo.BodySerial[0] == 0x4c) && (imgdata.shootinginfo.BodySerial[1] == 0x49)) { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[2] & 0x3f)) - 0x41; } else { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[1] & 0x3f)) - 0x41; } setPhaseOneFeatures(unique_id); break; case 0x0401: if (type == 4) imgdata.lens.makernotes.CurAp = powf64(2.0f, (int_to_float(data) / 2.0f)); else imgdata.lens.makernotes.CurAp = powf64(2.0f, (getreal(type) / 2.0f)); break; case 0x0403: if (type == 4) imgdata.lens.makernotes.CurFocal = int_to_float(data); else imgdata.lens.makernotes.CurFocal = getreal(type); break; case 0x0410: stmread(imgdata.lens.makernotes.body, len, ifp); break; case 0x0412: stmread(imgdata.lens.makernotes.Lens, len, ifp); break; case 0x0414: if (type == 4) { imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (int_to_float(data) / 2.0f)); } else { imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (getreal(type) / 2.0f)); } break; case 0x0415: if (type == 4) { imgdata.lens.makernotes.MinAp4CurFocal = powf64(2.0f, (int_to_float(data) / 2.0f)); } else { imgdata.lens.makernotes.MinAp4CurFocal = powf64(2.0f, (getreal(type) / 2.0f)); } break; case 0x0416: if (type == 4) { imgdata.lens.makernotes.MinFocal = int_to_float(data); } else { imgdata.lens.makernotes.MinFocal = getreal(type); } if (imgdata.lens.makernotes.MinFocal > 1000.0f) { imgdata.lens.makernotes.MinFocal = 0.0f; } break; case 0x0417: if (type == 4) { imgdata.lens.makernotes.MaxFocal = int_to_float(data); } else { imgdata.lens.makernotes.MaxFocal = getreal(type); } break; #endif case 0x100: flip = "0653"[data & 3] - '0'; break; case 0x106: for (i = 0; i < 9; i++) #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.P1_color[0].romm_cam[i] = #endif ((float *)romm_cam)[i] = getreal(11); romm_coeff(romm_cam); break; case 0x107: FORC3 cam_mul[c] = getreal(11); break; case 0x108: raw_width = data; break; case 0x109: raw_height = data; break; case 0x10a: left_margin = data; break; case 0x10b: top_margin = data; break; case 0x10c: width = data; break; case 0x10d: height = data; break; case 0x10e: ph1.format = data; break; case 0x10f: data_offset = data + base; break; case 0x110: meta_offset = data + base; meta_length = len; break; case 0x112: ph1.key_off = save - 4; break; case 0x210: ph1.tag_210 = int_to_float(data); break; case 0x21a: ph1.tag_21a = data; break; case 0x21c: strip_offset = data + base; break; case 0x21d: ph1.t_black = data; break; case 0x222: ph1.split_col = data; break; case 0x223: ph1.black_col = data + base; break; case 0x224: ph1.split_row = data; break; case 0x225: ph1.black_row = data + base; break; #ifdef LIBRAW_LIBRARY_BUILD case 0x226: for (i = 0; i < 9; i++) imgdata.color.P1_color[1].romm_cam[i] = getreal(11); break; #endif case 0x301: model[63] = 0; fread(model, 1, 63, ifp); if ((cp = strstr(model, " camera"))) *cp = 0; } fseek(ifp, save, SEEK_SET); } #ifdef LIBRAW_LIBRARY_BUILD if (!imgdata.lens.makernotes.body[0] && !imgdata.shootinginfo.BodySerial[0]) { fseek(ifp, meta_offset, SEEK_SET); order = get2(); fseek(ifp, 6, SEEK_CUR); fseek(ifp, meta_offset + get4(), SEEK_SET); entries = get4(); get4(); while (entries--) { tag = get4(); len = get4(); data = get4(); save = ftell(ifp); fseek(ifp, meta_offset + data, SEEK_SET); if (tag == 0x0407) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); if ((imgdata.shootinginfo.BodySerial[0] == 0x4c) && (imgdata.shootinginfo.BodySerial[1] == 0x49)) { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[2] & 0x3f)) - 0x41; } else { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[1] & 0x3f)) - 0x41; } setPhaseOneFeatures(unique_id); } fseek(ifp, save, SEEK_SET); } } #endif load_raw = ph1.format < 3 ? &CLASS phase_one_load_raw : &CLASS phase_one_load_raw_c; maximum = 0xffff; strcpy(make, "Phase One"); if (model[0]) return; switch (raw_height) { case 2060: strcpy(model, "LightPhase"); break; case 2682: strcpy(model, "H 10"); break; case 4128: strcpy(model, "H 20"); break; case 5488: strcpy(model, "H 25"); break; } } void CLASS parse_fuji(int offset) { unsigned entries, tag, len, save, c; fseek(ifp, offset, SEEK_SET); entries = get4(); if (entries > 255) return; #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_PARSEFUJI_PROCESSED; #endif while (entries--) { tag = get2(); len = get2(); save = ftell(ifp); if (tag == 0x100) { raw_height = get2(); raw_width = get2(); } else if (tag == 0x121) { height = get2(); if ((width = get2()) == 4284) width += 3; } else if (tag == 0x130) { fuji_layout = fgetc(ifp) >> 7; fuji_width = !(fgetc(ifp) & 8); } else if (tag == 0x131) { filters = 9; FORC(36) xtrans_abs[0][35 - c] = fgetc(ifp) & 3; } else if (tag == 0x2ff0) { FORC4 cam_mul[c ^ 1] = get2(); // IB start #ifdef LIBRAW_LIBRARY_BUILD } else if (tag == 0x9650) { short a = (short)get2(); float b = fMAX(1.0f, get2()); imgdata.makernotes.fuji.FujiExpoMidPointShift = a / b; } else if (tag == 0x2f00) { int nWBs = get4(); nWBs = MIN(nWBs, 6); for (int wb_ind = 0; wb_ind < nWBs; wb_ind++) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + wb_ind][c ^ 1] = get2(); fseek(ifp, 8, SEEK_CUR); } } else if (tag == 0x2000) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ 1] = get2(); } else if (tag == 0x2100) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][c ^ 1] = get2(); } else if (tag == 0x2200) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ 1] = get2(); } else if (tag == 0x2300) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ 1] = get2(); } else if (tag == 0x2301) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ 1] = get2(); } else if (tag == 0x2302) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][c ^ 1] = get2(); } else if (tag == 0x2310) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c ^ 1] = get2(); } else if (tag == 0x2400) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ 1] = get2(); } else if (tag == 0x2410) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ 1] = get2(); #endif // IB end } else if (tag == 0xc000) /* 0xc000 tag versions, second ushort; valid if the first ushort is 0 X100F 0x0259 X100T 0x0153 X-E2 0x014f 0x024f depends on firmware X-A1 0x014e XQ2 0x0150 XQ1 0x0150 X100S 0x0149 0x0249 depends on firmware X30 0x0152 X20 0x0146 X-T10 0x0154 X-T2 0x0258 X-M1 0x014d X-E2s 0x0355 X-A2 0x014e X-T20 0x025b GFX 50S 0x025a X-T1 0x0151 0x0251 0x0351 depends on firmware X70 0x0155 X-Pro2 0x0255 */ { c = order; order = 0x4949; if ((tag = get4()) > 10000) tag = get4(); if (tag > 10000) tag = get4(); width = tag; height = get4(); #ifdef LIBRAW_LIBRARY_BUILD if (!strcmp(model, "X-A3") || !strcmp(model, "X-A10")) { int wb[4]; int nWB, tWB, pWB; int iCCT = 0; int cnt; fseek(ifp, save + 0x200, SEEK_SET); for (int wb_ind = 0; wb_ind < 42; wb_ind++) { nWB = get4(); tWB = get4(); wb[0] = get4() << 1; wb[1] = get4(); wb[3] = get4(); wb[2] = get4() << 1; if (tWB && (iCCT < 255)) { imgdata.color.WBCT_Coeffs[iCCT][0] = tWB; for (cnt = 0; cnt < 4; cnt++) imgdata.color.WBCT_Coeffs[iCCT][cnt + 1] = wb[cnt]; iCCT++; } if (nWB != 70) { for (pWB = 1; pWB < nFuji_wb_list2; pWB += 2) { if (Fuji_wb_list2[pWB] == nWB) { for (cnt = 0; cnt < 4; cnt++) imgdata.color.WB_Coeffs[Fuji_wb_list2[pWB - 1]][cnt] = wb[cnt]; break; } } } } } else { libraw_internal_data.unpacker_data.posRAFData = save; libraw_internal_data.unpacker_data.lenRAFData = (len >> 1); } #endif order = c; } fseek(ifp, save + len, SEEK_SET); } height <<= fuji_layout; width >>= fuji_layout; } int CLASS parse_jpeg(int offset) { int len, save, hlen, mark; fseek(ifp, offset, SEEK_SET); if (fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8) return 0; while (fgetc(ifp) == 0xff && (mark = fgetc(ifp)) != 0xda) { order = 0x4d4d; len = get2() - 2; save = ftell(ifp); if (mark == 0xc0 || mark == 0xc3 || mark == 0xc9) { fgetc(ifp); raw_height = get2(); raw_width = get2(); } order = get2(); hlen = get4(); if (get4() == 0x48454150 #ifdef LIBRAW_LIBRARY_BUILD && (save + hlen) >= 0 && (save + hlen) <= ifp->size() #endif ) /* "HEAP" */ { #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; #endif parse_ciff(save + hlen, len - hlen, 0); } if (parse_tiff(save + 6)) apply_tiff(); fseek(ifp, save + len, SEEK_SET); } return 1; } void CLASS parse_riff() { unsigned i, size, end; char tag[4], date[64], month[64]; static const char mon[12][4] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; struct tm t; order = 0x4949; fread(tag, 4, 1, ifp); size = get4(); end = ftell(ifp) + size; if (!memcmp(tag, "RIFF", 4) || !memcmp(tag, "LIST", 4)) { int maxloop = 1000; get4(); while (ftell(ifp) + 7 < end && !feof(ifp) && maxloop--) parse_riff(); } else if (!memcmp(tag, "nctg", 4)) { while (ftell(ifp) + 7 < end) { i = get2(); size = get2(); if ((i + 1) >> 1 == 10 && size == 20) get_timestamp(0); else fseek(ifp, size, SEEK_CUR); } } else if (!memcmp(tag, "IDIT", 4) && size < 64) { fread(date, 64, 1, ifp); date[size] = 0; memset(&t, 0, sizeof t); if (sscanf(date, "%*s %s %d %d:%d:%d %d", month, &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec, &t.tm_year) == 6) { for (i = 0; i < 12 && strcasecmp(mon[i], month); i++) ; t.tm_mon = i; t.tm_year -= 1900; if (mktime(&t) > 0) timestamp = mktime(&t); } } else fseek(ifp, size, SEEK_CUR); } void CLASS parse_qt(int end) { unsigned save, size; char tag[4]; order = 0x4d4d; while (ftell(ifp) + 7 < end) { save = ftell(ifp); if ((size = get4()) < 8) return; fread(tag, 4, 1, ifp); if (!memcmp(tag, "moov", 4) || !memcmp(tag, "udta", 4) || !memcmp(tag, "CNTH", 4)) parse_qt(save + size); if (!memcmp(tag, "CNDA", 4)) parse_jpeg(ftell(ifp)); fseek(ifp, save + size, SEEK_SET); } } void CLASS parse_smal(int offset, int fsize) { int ver; fseek(ifp, offset + 2, SEEK_SET); order = 0x4949; ver = fgetc(ifp); if (ver == 6) fseek(ifp, 5, SEEK_CUR); if (get4() != fsize) return; if (ver > 6) data_offset = get4(); raw_height = height = get2(); raw_width = width = get2(); strcpy(make, "SMaL"); sprintf(model, "v%d %dx%d", ver, width, height); if (ver == 6) load_raw = &CLASS smal_v6_load_raw; if (ver == 9) load_raw = &CLASS smal_v9_load_raw; } void CLASS parse_cine() { unsigned off_head, off_setup, off_image, i; order = 0x4949; fseek(ifp, 4, SEEK_SET); is_raw = get2() == 2; fseek(ifp, 14, SEEK_CUR); is_raw *= get4(); off_head = get4(); off_setup = get4(); off_image = get4(); timestamp = get4(); if ((i = get4())) timestamp = i; fseek(ifp, off_head + 4, SEEK_SET); raw_width = get4(); raw_height = get4(); switch (get2(), get2()) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 16: load_raw = &CLASS unpacked_load_raw; } fseek(ifp, off_setup + 792, SEEK_SET); strcpy(make, "CINE"); sprintf(model, "%d", get4()); fseek(ifp, 12, SEEK_CUR); switch ((i = get4()) & 0xffffff) { case 3: filters = 0x94949494; break; case 4: filters = 0x49494949; break; default: is_raw = 0; } fseek(ifp, 72, SEEK_CUR); switch ((get4() + 3600) % 360) { case 270: flip = 4; break; case 180: flip = 1; break; case 90: flip = 7; break; case 0: flip = 2; } cam_mul[0] = getreal(11); cam_mul[2] = getreal(11); maximum = ~((~0u) << get4()); fseek(ifp, 668, SEEK_CUR); shutter = get4() / 1000000000.0; fseek(ifp, off_image, SEEK_SET); if (shot_select < is_raw) fseek(ifp, shot_select * 8, SEEK_CUR); data_offset = (INT64)get4() + 8; data_offset += (INT64)get4() << 32; } void CLASS parse_redcine() { unsigned i, len, rdvo; order = 0x4d4d; is_raw = 0; fseek(ifp, 52, SEEK_SET); width = get4(); height = get4(); fseek(ifp, 0, SEEK_END); fseek(ifp, -(i = ftello(ifp) & 511), SEEK_CUR); if (get4() != i || get4() != 0x52454f42) { #ifdef DCRAW_VERBOSE fprintf(stderr, _("%s: Tail is missing, parsing from head...\n"), ifname); #endif fseek(ifp, 0, SEEK_SET); while ((len = get4()) != EOF) { if (get4() == 0x52454456) if (is_raw++ == shot_select) data_offset = ftello(ifp) - 8; fseek(ifp, len - 8, SEEK_CUR); } } else { rdvo = get4(); fseek(ifp, 12, SEEK_CUR); is_raw = get4(); fseeko(ifp, rdvo + 8 + shot_select * 4, SEEK_SET); data_offset = get4(); } } //@end COMMON char *CLASS foveon_gets(int offset, char *str, int len) { int i; fseek(ifp, offset, SEEK_SET); for (i = 0; i < len - 1; i++) if ((str[i] = get2()) == 0) break; str[i] = 0; return str; } void CLASS parse_foveon() { int entries, img = 0, off, len, tag, save, i, wide, high, pent, poff[256][2]; char name[64], value[64]; order = 0x4949; /* Little-endian */ fseek(ifp, 36, SEEK_SET); flip = get4(); fseek(ifp, -4, SEEK_END); fseek(ifp, get4(), SEEK_SET); if (get4() != 0x64434553) return; /* SECd */ entries = (get4(), get4()); while (entries--) { off = get4(); len = get4(); tag = get4(); save = ftell(ifp); fseek(ifp, off, SEEK_SET); if (get4() != (0x20434553 | (tag << 24))) return; switch (tag) { case 0x47414d49: /* IMAG */ case 0x32414d49: /* IMA2 */ fseek(ifp, 8, SEEK_CUR); pent = get4(); wide = get4(); high = get4(); if (wide > raw_width && high > raw_height) { switch (pent) { case 5: load_flags = 1; case 6: load_raw = &CLASS foveon_sd_load_raw; break; case 30: load_raw = &CLASS foveon_dp_load_raw; break; default: load_raw = 0; } raw_width = wide; raw_height = high; data_offset = off + 28; is_foveon = 1; } fseek(ifp, off + 28, SEEK_SET); if (fgetc(ifp) == 0xff && fgetc(ifp) == 0xd8 && thumb_length < len - 28) { thumb_offset = off + 28; thumb_length = len - 28; write_thumb = &CLASS jpeg_thumb; } if (++img == 2 && !thumb_length) { thumb_offset = off + 24; thumb_width = wide; thumb_height = high; write_thumb = &CLASS foveon_thumb; } break; case 0x464d4143: /* CAMF */ meta_offset = off + 8; meta_length = len - 28; break; case 0x504f5250: /* PROP */ pent = (get4(), get4()); fseek(ifp, 12, SEEK_CUR); off += pent * 8 + 24; if ((unsigned)pent > 256) pent = 256; for (i = 0; i < pent * 2; i++) ((int *)poff)[i] = off + get4() * 2; for (i = 0; i < pent; i++) { foveon_gets(poff[i][0], name, 64); foveon_gets(poff[i][1], value, 64); if (!strcmp(name, "ISO")) iso_speed = atoi(value); if (!strcmp(name, "CAMMANUF")) strcpy(make, value); if (!strcmp(name, "CAMMODEL")) strcpy(model, value); if (!strcmp(name, "WB_DESC")) strcpy(model2, value); if (!strcmp(name, "TIME")) timestamp = atoi(value); if (!strcmp(name, "EXPTIME")) shutter = atoi(value) / 1000000.0; if (!strcmp(name, "APERTURE")) aperture = atof(value); if (!strcmp(name, "FLENGTH")) focal_len = atof(value); #ifdef LIBRAW_LIBRARY_BUILD if (!strcmp(name, "CAMSERIAL")) strcpy(imgdata.shootinginfo.BodySerial, value); if (!strcmp(name, "FLEQ35MM")) imgdata.lens.makernotes.FocalLengthIn35mmFormat = atof(value); if (!strcmp(name, "LENSARANGE")) { char *sp; imgdata.lens.makernotes.MaxAp4CurFocal = imgdata.lens.makernotes.MinAp4CurFocal = atof(value); sp = strrchr(value, ' '); if (sp) { imgdata.lens.makernotes.MinAp4CurFocal = atof(sp); if (imgdata.lens.makernotes.MaxAp4CurFocal > imgdata.lens.makernotes.MinAp4CurFocal) my_swap(float, imgdata.lens.makernotes.MaxAp4CurFocal, imgdata.lens.makernotes.MinAp4CurFocal); } } if (!strcmp(name, "LENSFRANGE")) { char *sp; imgdata.lens.makernotes.MinFocal = imgdata.lens.makernotes.MaxFocal = atof(value); sp = strrchr(value, ' '); if (sp) { imgdata.lens.makernotes.MaxFocal = atof(sp); if ((imgdata.lens.makernotes.MaxFocal + 0.17f) < imgdata.lens.makernotes.MinFocal) my_swap(float, imgdata.lens.makernotes.MaxFocal, imgdata.lens.makernotes.MinFocal); } } if (!strcmp(name, "LENSMODEL")) { char *sp; imgdata.lens.makernotes.LensID = strtol(value, &sp, 16); // atoi(value); if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = Sigma_X3F; } } #endif } #ifdef LOCALTIME timestamp = mktime(gmtime(&timestamp)); #endif } fseek(ifp, save, SEEK_SET); } } //@out COMMON /* All matrices are from Adobe DNG Converter unless otherwise noted. */ void CLASS adobe_coeff(const char *t_make, const char *t_model #ifdef LIBRAW_LIBRARY_BUILD , int internal_only #endif ) { // clang-format off static const struct { const char *prefix; int t_black, t_maximum, trans[12]; } table[] = { { "AgfaPhoto DC-833m", 0, 0, /* DJC */ { 11438,-3762,-1115,-2409,9914,2497,-1227,2295,5300 } }, { "Apple QuickTake", 0, 0, /* DJC */ { 21392,-5653,-3353,2406,8010,-415,7166,1427,2078 } }, {"Broadcom RPi IMX219", 66, 0x3ff, { 5302,1083,-728,-5320,14112,1699,-863,2371,5136 } }, /* LibRaw */ { "Broadcom RPi OV5647", 16, 0x3ff, { 12782,-4059,-379,-478,9066,1413,1340,1513,5176 } }, /* DJC */ { "Canon EOS D2000", 0, 0, { 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } }, { "Canon EOS D6000", 0, 0, { 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } }, { "Canon EOS D30", 0, 0, /* updated */ { 9900,-2771,-1324,-7072,14229,3140,-2790,3344,8861 } }, { "Canon EOS D60", 0, 0xfa0, /* updated */ { 6211,-1358,-896,-8557,15766,3012,-3001,3507,8567 } }, { "Canon EOS 5DS", 0, 0x3c96, { 6250,-711,-808,-5153,12794,2636,-1249,2198,5610 } }, { "Canon EOS 5D Mark IV", 0, 0, { 6446,-366,-864,-4436,12204,2513,-952,2496,6348 } }, { "Canon EOS 5D Mark III", 0, 0x3c80, { 6722,-635,-963,-4287,12460,2028,-908,2162,5668 } }, { "Canon EOS 5D Mark II", 0, 0x3cf0, { 4716,603,-830,-7798,15474,2480,-1496,1937,6651 } }, { "Canon EOS 5D", 0, 0xe6c, { 6347,-479,-972,-8297,15954,2480,-1968,2131,7649 } }, { "Canon EOS 6D Mark II", 0, 0x38de, /* updated */ { 6875,-970,-932,-4691,12459,2501,-874,1953,5809 } }, { "Canon EOS 6D", 0, 0x3c82, /* skipped update */ { 8621,-2197,-787,-3150,11358,912,-1161,2400,4836 } }, { "Canon EOS 77D", 0, 0, { 7377,-742,-998,-4235,11981,2549,-673,1918,5538 } }, { "Canon EOS 7D Mark II", 0, 0x3510, { 7268,-1082,-969,-4186,11839,2663,-825,2029,5839 } }, { "Canon EOS 7D", 0, 0x3510, { 6844,-996,-856,-3876,11761,2396,-593,1772,6198 } }, { "Canon EOS 800D", 0, 0, { 6970,-512,-968,-4425,12161,2553,-739,1982,5601 } }, { "Canon EOS 80D", 0, 0, { 7457,-671,-937,-4849,12495,2643,-1213,2354,5492 } }, { "Canon EOS 10D", 0, 0xfa0, /* updated */ { 8250,-2044,-1127,-8092,15606,2664,-2893,3453,8348 } }, { "Canon EOS 200D", 0, 0, { 7377,-742,-998,-4235,11981,2549,-673,1918,5538 } }, { "Canon EOS 20Da", 0, 0, { 14155,-5065,-1382,-6550,14633,2039,-1623,1824,6561 } }, { "Canon EOS 20D", 0, 0xfff, { 6599,-537,-891,-8071,15783,2424,-1983,2234,7462 } }, { "Canon EOS 30D", 0, 0, { 6257,-303,-1000,-7880,15621,2396,-1714,1904,7046 } }, { "Canon EOS 40D", 0, 0x3f60, { 6071,-747,-856,-7653,15365,2441,-2025,2553,7315 } }, { "Canon EOS 50D", 0, 0x3d93, { 4920,616,-593,-6493,13964,2784,-1774,3178,7005 } }, { "Canon EOS 60Da", 0, 0x2ff7, /* added */ { 17492,-7240,-2023,-1791,10323,1701,-186,1329,5406 } }, { "Canon EOS 60D", 0, 0x2ff7, { 6719,-994,-925,-4408,12426,2211,-887,2129,6051 } }, { "Canon EOS 70D", 0, 0x3bc7, { 7034,-804,-1014,-4420,12564,2058,-851,1994,5758 } }, { "Canon EOS 100D", 0, 0x350f, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS 300D", 0, 0xfa0, /* updated */ { 8250,-2044,-1127,-8092,15606,2664,-2893,3453,8348 } }, { "Canon EOS 350D", 0, 0xfff, { 6018,-617,-965,-8645,15881,2975,-1530,1719,7642 } }, { "Canon EOS 400D", 0, 0xe8e, { 7054,-1501,-990,-8156,15544,2812,-1278,1414,7796 } }, { "Canon EOS 450D", 0, 0x390d, { 5784,-262,-821,-7539,15064,2672,-1982,2681,7427 } }, { "Canon EOS 500D", 0, 0x3479, { 4763,712,-646,-6821,14399,2640,-1921,3276,6561 } }, { "Canon EOS 550D", 0, 0x3dd7, { 6941,-1164,-857,-3825,11597,2534,-416,1540,6039 } }, { "Canon EOS 600D", 0, 0x3510, { 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } }, { "Canon EOS 650D", 0, 0x354d, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS 750D", 0, 0x3c00, { 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } }, { "Canon EOS 760D", 0, 0x3c00, { 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } }, { "Canon EOS 700D", 0, 0x3c00, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS 1000D", 0, 0xe43, { 6771,-1139,-977,-7818,15123,2928,-1244,1437,7533 } }, { "Canon EOS 1100D", 0, 0x3510, { 6444,-904,-893,-4563,12308,2535,-903,2016,6728 } }, { "Canon EOS 1200D", 0, 0x37c2, { 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } }, { "Canon EOS 1300D", 0, 0x37c2, { 6939,-1016,-866,-4428,12473,2177,-1175,2178,6162 } }, { "Canon EOS M6", 0, 0, { 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } }, { "Canon EOS M5", 0, 0, { 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } }, { "Canon EOS M3", 0, 0, { 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } }, { "Canon EOS M2", 0, 0, /* added */ { 6400,-480,-888,-5294,13416,2047,-1296,2203,6137 } }, { "Canon EOS M10", 0, 0, { 6400,-480,-888,-5294,13416,2047,-1296,2203,6137 } }, { "Canon EOS M", 0, 0, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS-1Ds Mark III", 0, 0x3bb0, { 5859,-211,-930,-8255,16017,2353,-1732,1887,7448 } }, { "Canon EOS-1Ds Mark II", 0, 0xe80, { 6517,-602,-867,-8180,15926,2378,-1618,1771,7633 } }, { "Canon EOS-1D Mark IV", 0, 0x3bb0, { 6014,-220,-795,-4109,12014,2361,-561,1824,5787 } }, { "Canon EOS-1D Mark III", 0, 0x3bb0, { 6291,-540,-976,-8350,16145,2311,-1714,1858,7326 } }, { "Canon EOS-1D Mark II N", 0, 0xe80, { 6240,-466,-822,-8180,15825,2500,-1801,1938,8042 } }, { "Canon EOS-1D Mark II", 0, 0xe80, { 6264,-582,-724,-8312,15948,2504,-1744,1919,8664 } }, { "Canon EOS-1DS", 0, 0xe20, /* updated */ { 3925,4060,-1739,-8973,16552,2545,-3287,3945,8243 } }, { "Canon EOS-1D C", 0, 0x3c4e, { 6847,-614,-1014,-4669,12737,2139,-1197,2488,6846 } }, { "Canon EOS-1D X Mark II", 0, 0x3c4e, /* updated */ { 7596,-978,-967,-4808,12571,2503,-1398,2567,5752 } }, { "Canon EOS-1D X", 0, 0x3c4e, { 6847,-614,-1014,-4669,12737,2139,-1197,2488,6846 } }, { "Canon EOS-1D", 0, 0xe20, { 6806,-179,-1020,-8097,16415,1687,-3267,4236,7690 } }, { "Canon EOS C500", 853, 0, /* DJC */ { 17851,-10604,922,-7425,16662,763,-3660,3636,22278 } }, {"Canon PowerShot 600", 0, 0, /* added */ { -3822,10019,1311,4085,-157,3386,-5341,10829,4812,-1969,10969,1126 } }, { "Canon PowerShot A530", 0, 0, { 0 } }, /* don't want the A5 matrix */ { "Canon PowerShot A50", 0, 0, { -5300,9846,1776,3436,684,3939,-5540,9879,6200,-1404,11175,217 } }, { "Canon PowerShot A5", 0, 0, { -4801,9475,1952,2926,1611,4094,-5259,10164,5947,-1554,10883,547 } }, { "Canon PowerShot G10", 0, 0, { 11093,-3906,-1028,-5047,12492,2879,-1003,1750,5561 } }, { "Canon PowerShot G11", 0, 0, { 12177,-4817,-1069,-1612,9864,2049,-98,850,4471 } }, { "Canon PowerShot G12", 0, 0, { 13244,-5501,-1248,-1508,9858,1935,-270,1083,4366 } }, { "Canon PowerShot G15", 0, 0, { 7474,-2301,-567,-4056,11456,2975,-222,716,4181 } }, { "Canon PowerShot G16", 0, 0, /* updated */ { 8020,-2687,-682,-3704,11879,2052,-965,1921,5556 } }, { "Canon PowerShot G1 X Mark II", 0, 0, { 7378,-1255,-1043,-4088,12251,2048,-876,1946,5805 } }, { "Canon PowerShot G1 X", 0, 0, { 7378,-1255,-1043,-4088,12251,2048,-876,1946,5805 } }, { "Canon PowerShot G1", 0, 0, /* updated */ { -5686,10300,2223,4725,-1157,4383,-6128,10783,6163,-2688,12093,604 } }, { "Canon PowerShot G2", 0, 0, /* updated */ { 9194,-2787,-1059,-8098,15657,2608,-2610,3064,7867 } }, { "Canon PowerShot G3 X", 0, 0, { 9701,-3857,-921,-3149,11537,1817,-786,1817,5147 } }, { "Canon PowerShot G3", 0, 0, /* updated */ { 9326,-2882,-1084,-7940,15447,2677,-2620,3090,7740 } }, { "Canon PowerShot G5 X",0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G5", 0, 0, /* updated */ { 9869,-2972,-942,-7314,15098,2369,-1898,2536,7282 } }, { "Canon PowerShot G6", 0, 0, { 9877,-3775,-871,-7613,14807,3072,-1448,1305,7485 } }, { "Canon PowerShot G7 X Mark II", 0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G7 X", 0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G9 X Mark II", 0, 0, { 10056,-4131,-944,-2576,11143,1625,-238,1294,5179 } }, { "Canon PowerShot G9 X",0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G9", 0, 0, { 7368,-2141,-598,-5621,13254,2625,-1418,1696,5743 } }, { "Canon PowerShot Pro1", 0, 0, { 10062,-3522,-999,-7643,15117,2730,-765,817,7323 } }, { "Canon PowerShot Pro70", 34, 0, /* updated */ { -5106,10695,1576,3820,53,4566,-6497,10736,6701,-3336,11887,1394 } }, { "Canon PowerShot Pro90", 0, 0, /* updated */ { -5912,10768,2288,4612,-989,4333,-6153,10897,5944,-2907,12288,624 } }, { "Canon PowerShot S30", 0, 0, /* updated */ { 10744,-3813,-1142,-7962,15966,2075,-2492,2805,7744 } }, { "Canon PowerShot S40", 0, 0, /* updated */ { 8606,-2573,-949,-8237,15489,2974,-2649,3076,9100 } }, { "Canon PowerShot S45", 0, 0, /* updated */ { 8251,-2410,-964,-8047,15430,2823,-2380,2824,8119 } }, { "Canon PowerShot S50", 0, 0, /* updated */ { 8979,-2658,-871,-7721,15500,2357,-1773,2366,6634 } }, { "Canon PowerShot S60", 0, 0, { 8795,-2482,-797,-7804,15403,2573,-1422,1996,7082 } }, { "Canon PowerShot S70", 0, 0, { 9976,-3810,-832,-7115,14463,2906,-901,989,7889 } }, { "Canon PowerShot S90", 0, 0, { 12374,-5016,-1049,-1677,9902,2078,-83,852,4683 } }, { "Canon PowerShot S95", 0, 0, { 13440,-5896,-1279,-1236,9598,1931,-180,1001,4651 } }, { "Canon PowerShot S120", 0, 0, { 6961,-1685,-695,-4625,12945,1836,-1114,2152,5518 } }, { "Canon PowerShot S110", 0, 0, { 8039,-2643,-654,-3783,11230,2930,-206,690,4194 } }, { "Canon PowerShot S100", 0, 0, { 7968,-2565,-636,-2873,10697,2513,180,667,4211 } }, { "Canon PowerShot SX1 IS", 0, 0, { 6578,-259,-502,-5974,13030,3309,-308,1058,4970 } }, { "Canon PowerShot SX50 HS", 0, 0, { 12432,-4753,-1247,-2110,10691,1629,-412,1623,4926 } }, { "Canon PowerShot SX60 HS", 0, 0, { 13161,-5451,-1344,-1989,10654,1531,-47,1271,4955 } }, { "Canon PowerShot A3300", 0, 0, /* DJC */ { 10826,-3654,-1023,-3215,11310,1906,0,999,4960 } }, { "Canon PowerShot A470", 0, 0, /* DJC */ { 12513,-4407,-1242,-2680,10276,2405,-878,2215,4734 } }, { "Canon PowerShot A610", 0, 0, /* DJC */ { 15591,-6402,-1592,-5365,13198,2168,-1300,1824,5075 } }, { "Canon PowerShot A620", 0, 0, /* DJC */ { 15265,-6193,-1558,-4125,12116,2010,-888,1639,5220 } }, { "Canon PowerShot A630", 0, 0, /* DJC */ { 14201,-5308,-1757,-6087,14472,1617,-2191,3105,5348 } }, { "Canon PowerShot A640", 0, 0, /* DJC */ { 13124,-5329,-1390,-3602,11658,1944,-1612,2863,4885 } }, { "Canon PowerShot A650", 0, 0, /* DJC */ { 9427,-3036,-959,-2581,10671,1911,-1039,1982,4430 } }, { "Canon PowerShot A720", 0, 0, /* DJC */ { 14573,-5482,-1546,-1266,9799,1468,-1040,1912,3810 } }, { "Canon PowerShot D10", 127, 0, /* DJC */ { 14052,-5229,-1156,-1325,9420,2252,-498,1957,4116 } }, { "Canon PowerShot S3 IS", 0, 0, /* DJC */ { 14062,-5199,-1446,-4712,12470,2243,-1286,2028,4836 } }, { "Canon PowerShot SX110 IS", 0, 0, /* DJC */ { 14134,-5576,-1527,-1991,10719,1273,-1158,1929,3581 } }, { "Canon PowerShot SX220", 0, 0, /* DJC */ { 13898,-5076,-1447,-1405,10109,1297,-244,1860,3687 } }, { "Canon IXUS 160", 0, 0, /* DJC */ { 11657,-3781,-1136,-3544,11262,2283,-160,1219,4700 } }, { "Casio EX-F1", 0, 0, /* added */ { 9084,-2016,-848,-6711,14351,2570,-1059,1725,6135 } }, { "Casio EX-FH100", 0, 0, /* added */ { 12771,-4179,-1558,-2149,10938,1375,-453,1751,4494 } }, { "Casio EX-S20", 0, 0, /* DJC */ { 11634,-3924,-1128,-4968,12954,2015,-1588,2648,7206 } }, { "Casio EX-Z750", 0, 0, /* DJC */ { 10819,-3873,-1099,-4903,13730,1175,-1755,3751,4632 } }, { "Casio EX-Z10", 128, 0xfff, /* DJC */ { 9790,-3338,-603,-2321,10222,2099,-344,1273,4799 } }, { "CINE 650", 0, 0, { 3390,480,-500,-800,3610,340,-550,2336,1192 } }, { "CINE 660", 0, 0, { 3390,480,-500,-800,3610,340,-550,2336,1192 } }, { "CINE", 0, 0, { 20183,-4295,-423,-3940,15330,3985,-280,4870,9800 } }, { "Contax N Digital", 0, 0xf1e, { 7777,1285,-1053,-9280,16543,2916,-3677,5679,7060 } }, { "DXO ONE", 0, 0, { 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } }, { "Epson R-D1", 0, 0, { 6827,-1878,-732,-8429,16012,2564,-704,592,7145 } }, { "Fujifilm E550", 0, 0, /* updated */ { 11044,-3888,-1120,-7248,15167,2208,-1531,2276,8069 } }, { "Fujifilm E900", 0, 0, { 9183,-2526,-1078,-7461,15071,2574,-2022,2440,8639 } }, { "Fujifilm F5", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm F6", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm F77", 0, 0xfe9, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm F7", 0, 0, { 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } }, { "Fujifilm F810", 0, 0, /* added */ { 11044,-3888,-1120,-7248,15167,2208,-1531,2276,8069 } }, { "Fujifilm F8", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm S100FS", 514, 0, { 11521,-4355,-1065,-6524,13767,3058,-1466,1984,6045 } }, { "Fujifilm S1", 0, 0, { 12297,-4882,-1202,-2106,10691,1623,-88,1312,4790 } }, { "Fujifilm S20Pro", 0, 0, { 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } }, { "Fujifilm S20", 512, 0x3fff, { 11401,-4498,-1312,-5088,12751,2613,-838,1568,5941 } }, { "Fujifilm S2Pro", 128, 0, /* updated */ { 12741,-4916,-1420,-8510,16791,1715,-1767,2302,7771 } }, { "Fujifilm S3Pro", 0, 0, { 11807,-4612,-1294,-8927,16968,1988,-2120,2741,8006 } }, { "Fujifilm S5Pro", 0, 0, { 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } }, { "Fujifilm S5000", 0, 0, { 8754,-2732,-1019,-7204,15069,2276,-1702,2334,6982 } }, { "Fujifilm S5100", 0, 0, { 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } }, { "Fujifilm S5500", 0, 0, { 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } }, { "Fujifilm S5200", 0, 0, { 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } }, { "Fujifilm S5600", 0, 0, { 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } }, { "Fujifilm S6", 0, 0, { 12628,-4887,-1401,-6861,14996,1962,-2198,2782,7091 } }, { "Fujifilm S7000", 0, 0, { 10190,-3506,-1312,-7153,15051,2238,-2003,2399,7505 } }, { "Fujifilm S9000", 0, 0, { 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } }, { "Fujifilm S9500", 0, 0, { 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } }, { "Fujifilm S9100", 0, 0, { 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } }, { "Fujifilm S9600", 0, 0, { 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } }, { "Fujifilm SL1000", 0, 0, { 11705,-4262,-1107,-2282,10791,1709,-555,1713,4945 } }, { "Fujifilm IS-1", 0, 0, { 21461,-10807,-1441,-2332,10599,1999,289,875,7703 } }, { "Fujifilm IS Pro", 0, 0, { 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } }, { "Fujifilm HS10 HS11", 0, 0xf68, { 12440,-3954,-1183,-1123,9674,1708,-83,1614,4086 } }, { "Fujifilm HS2", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm HS3", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm HS50EXR", 0, 0, { 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } }, { "Fujifilm F900EXR", 0, 0, { 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } }, { "Fujifilm X100S", 0, 0, { 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } }, { "Fujifilm X100F", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm X100T", 0, 0, { 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } }, { "Fujifilm X100", 0, 0, { 12161,-4457,-1069,-5034,12874,2400,-795,1724,6904 } }, { "Fujifilm X10", 0, 0, { 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } }, { "Fujifilm X20", 0, 0, { 11768,-4971,-1133,-4904,12927,2183,-480,1723,4605 } }, { "Fujifilm X30", 0, 0, { 12328,-5256,-1144,-4469,12927,1675,-87,1291,4351 } }, { "Fujifilm X70", 0, 0, { 10450,-4329,-878,-3217,11105,2421,-752,1758,6519 } }, { "Fujifilm X-Pro1", 0, 0, { 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } }, { "Fujifilm X-Pro2", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm X-A10", 0, 0, { 11540,-4999,-991,-2949,10963,2278,-382,1049,5605} }, { "Fujifilm X-A1", 0, 0, { 11086,-4555,-839,-3512,11310,2517,-815,1341,5940 } }, { "Fujifilm X-A2", 0, 0, { 10763,-4560,-917,-3346,11311,2322,-475,1135,5843 } }, { "Fujifilm X-A3", 0, 0, { 12407,-5222,-1086,-2971,11116,2120,-294,1029,5284 } }, { "Fujifilm X-E1", 0, 0, { 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } }, { "Fujifilm X-E2S", 0, 0, { 11562,-5118,-961,-3022,11007,2311,-525,1569,6097 } }, { "Fujifilm X-E2", 0, 0, { 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } }, { "Fujifilm XF1", 0, 0, { 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } }, { "Fujifilm X-M1", 0, 0, { 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } }, { "Fujifilm X-S1", 0, 0, { 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } }, { "Fujifilm X-T20", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm X-T2", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm X-T10", 0, 0, /* updated */ { 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } }, { "Fujifilm X-T1", 0, 0, { 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } }, { "Fujifilm XQ1", 0, 0, { 9252,-2704,-1064,-5893,14265,1717,-1101,2341,4349 } }, { "Fujifilm XQ2", 0, 0, { 9252,-2704,-1064,-5893,14265,1717,-1101,2341,4349 } }, { "Fujifilm GFX 50S", 0, 0, { 11756,-4754,-874,-3056,11045,2305,-381,1457,6006 } }, { "GITUP GIT2P", 4160, 0, { 8489, -2583,-1036,-8051,15583,2643,-1307,1407,7354 } }, { "GITUP GIT2", 3200, 0, { 8489, -2583,-1036,-8051,15583,2643,-1307,1407,7354 } }, { "Hasselblad HV", 0, 0, /* added */ { 6344,-1612,-461,-4862,12476,2680,-864,1785,6898 } }, { "Hasselblad Lunar", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Hasselblad Lusso", 0, 0, /* added */ { 4912,-540,-201,-6129,13513,2906,-1563,2151,7182 } }, { "Hasselblad Stellar", -800, 0, { 8651,-2754,-1057,-3464,12207,1373,-568,1398,4434 } }, { "Hasselblad 500 mech.", 0, 0, /* added */ { 8519,-3260,-280,-5081,13459,1738,-1449,2960,7809 } }, { "Hasselblad CFV", 0, 0, { 8519,-3260,-280,-5081,13459,1738,-1449,2960,7809 } }, { "Hasselblad H-16MP", 0, 0, /* LibRaw */ { 17765,-5322,-1734,-6168,13354,2135,-264,2524,7440 } }, { "Hasselblad H-22MP", 0, 0, /* LibRaw */ { 17765,-5322,-1734,-6168,13354,2135,-264,2524,7440 } }, { "Hasselblad H-31MP",0, 0, /* LibRaw */ { 14480,-5448,-1686,-3534,13123,2260,384,2952,7232 } }, { "Hasselblad 39-Coated", 0, 0, /* added */ { 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } }, { "Hasselblad H-39MP",0, 0, { 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } }, { "Hasselblad H2D-39", 0, 0, /* added */ { 3894,-110,287,-4672,12610,2295,-2092,4100,6196 } }, { "Hasselblad H3D-50", 0, 0, { 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } }, { "Hasselblad H3D", 0, 0, /* added */ { 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } }, { "Hasselblad H4D-40",0, 0, /* LibRaw */ { 6325,-860,-957,-6559,15945,266,167,770,5936 } }, { "Hasselblad H4D-50",0, 0, /* LibRaw */ { 15283,-6272,-465,-2030,16031,478,-2379,390,7965 } }, { "Hasselblad H4D-60",0, 0, { 9662,-684,-279,-4903,12293,2950,-344,1669,6024 } }, { "Hasselblad H5D-50c",0, 0, { 4932,-835,141,-4878,11868,3437,-1138,1961,7067 } }, { "Hasselblad H5D-50",0, 0, { 5656,-659,-346,-3923,12306,1791,-1602,3509,5442 } }, { "Hasselblad H6D-100c",0, 0, { 5110,-1357,-308,-5573,12835,3077,-1279,2025,7010 } }, { "Hasselblad X1D",0, 0, { 4932,-835,141,-4878,11868,3437,-1138,1961,7067 } }, { "HTC One A9", 64, 1023, /* this is CM1 transposed */ { 101, -20, -2, -11, 145, 41, -24, 1, 56 } }, { "Imacon Ixpress", 0, 0, /* DJC */ { 7025,-1415,-704,-5188,13765,1424,-1248,2742,6038 } }, { "Kodak NC2000", 0, 0, { 13891,-6055,-803,-465,9919,642,2121,82,1291 } }, { "Kodak DCS315C", -8, 0, { 17523,-4827,-2510,756,8546,-137,6113,1649,2250 } }, { "Kodak DCS330C", -8, 0, { 20620,-7572,-2801,-103,10073,-396,3551,-233,2220 } }, { "Kodak DCS420", 0, 0, { 10868,-1852,-644,-1537,11083,484,2343,628,2216 } }, { "Kodak DCS460", 0, 0, { 10592,-2206,-967,-1944,11685,230,2206,670,1273 } }, { "Kodak EOSDCS1", 0, 0, { 10592,-2206,-967,-1944,11685,230,2206,670,1273 } }, { "Kodak EOSDCS3B", 0, 0, { 9898,-2700,-940,-2478,12219,206,1985,634,1031 } }, { "Kodak DCS520C", -178, 0, { 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } }, { "Kodak DCS560C", -177, 0, { 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } }, { "Kodak DCS620C", -177, 0, { 23617,-10175,-3149,-2054,11749,-272,2586,-489,3453 } }, { "Kodak DCS620X", -176, 0, { 13095,-6231,154,12221,-21,-2137,895,4602,2258 } }, { "Kodak DCS660C", -173, 0, { 18244,-6351,-2739,-791,11193,-521,3711,-129,2802 } }, { "Kodak DCS720X", 0, 0, { 11775,-5884,950,9556,1846,-1286,-1019,6221,2728 } }, { "Kodak DCS760C", 0, 0, { 16623,-6309,-1411,-4344,13923,323,2285,274,2926 } }, { "Kodak DCS Pro SLR", 0, 0, { 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } }, { "Kodak DCS Pro 14nx", 0, 0, { 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } }, { "Kodak DCS Pro 14", 0, 0, { 7791,3128,-776,-8588,16458,2039,-2455,4006,6198 } }, { "Photo Control Camerz ZDS 14", 0, 0, { 7791,3128,-776,-8588,16458,2039,-2455,4006,6198 } }, { "Kodak ProBack645", 0, 0, { 16414,-6060,-1470,-3555,13037,473,2545,122,4948 } }, { "Kodak ProBack", 0, 0, { 21179,-8316,-2918,-915,11019,-165,3477,-180,4210 } }, { "Kodak P712", 0, 0, { 9658,-3314,-823,-5163,12695,2768,-1342,1843,6044 } }, { "Kodak P850", 0, 0xf7c, { 10511,-3836,-1102,-6946,14587,2558,-1481,1792,6246 } }, { "Kodak P880", 0, 0xfff, { 12805,-4662,-1376,-7480,15267,2360,-1626,2194,7904 } }, { "Kodak EasyShare Z980", 0, 0, { 11313,-3559,-1101,-3893,11891,2257,-1214,2398,4908 } }, { "Kodak EasyShare Z981", 0, 0, { 12729,-4717,-1188,-1367,9187,2582,274,860,4411 } }, { "Kodak EasyShare Z990", 0, 0xfed, { 11749,-4048,-1309,-1867,10572,1489,-138,1449,4522 } }, { "Kodak EASYSHARE Z1015", 0, 0xef1, { 11265,-4286,-992,-4694,12343,2647,-1090,1523,5447 } }, { "Leaf C-Most", 0, 0, /* updated */ { 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } }, { "Leaf Valeo 6", 0, 0, { 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } }, { "Leaf Aptus 54S", 0, 0, { 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } }, { "Leaf Aptus-II 8", 0, 0, /* added */ { 7361,1257,-163,-6929,14061,3176,-1839,3454,5603 } }, { "Leaf AFi-II 7", 0, 0, /* added */ { 7691,-108,-339,-6185,13627,2833,-2046,3899,5952 } }, { "Leaf Aptus-II 5", 0, 0, /* added */ { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf Aptus 65", 0, 0, { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf AFi 65S", 0, 0, /* added */ { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf Aptus 75", 0, 0, { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf AFi 75S", 0, 0, /* added */ { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf Credo 40", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Leaf Credo 50", 0, 0, { 3984,0,0,0,10000,0,0,0,7666 } }, { "Leaf Credo 60", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Leaf Credo 80", 0, 0, { 6294,686,-712,-5435, 13417,2211,-1006,2435,5042 } }, { "Leaf", 0, 0, { 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } }, { "Leica M10", 0, 0, /* added */ { 9090,-3342,-740,-4006,13456,493,-569,2266,6871 } }, { "Leica M9", 0, 0, /* added */ { 6687,-1751,-291,-3556,11373,2492,-548,2204,7146 } }, { "Leica M8", 0, 0, /* added */ { 7675,-2196,-305,-5860,14119,1856,-2425,4006,6578 } }, { "Leica M (Typ 240)", 0, 0, /* added */ { 7199,-2140,-712,-4005,13327,649,-810,2521,6673 } }, { "Leica M (Typ 262)", 0, 0, { 7199,-2140,-712,-4005,13327,649,-810,2521,6673 } }, { "Leica SL (Typ 601)", 0, 0, { 11865,-4523,-1441,-5423,14458,935,-1587,2687,4830} }, { "Leica S2", 0, 0, /* added */ { 5627,-721,-447,-4423,12456,2192,-1048,2948,7379 } }, {"Leica S-E (Typ 006)", 0, 0, /* added */ { 5749,-1072,-382,-4274,12432,2048,-1166,3104,7105 } }, {"Leica S (Typ 006)", 0, 0, /* added */ { 5749,-1072,-382,-4274,12432,2048,-1166,3104,7105 } }, { "Leica S (Typ 007)", 0, 0, { 6063,-2234,-231,-5210,13787,1500,-1043,2866,6997 } }, { "Leica Q (Typ 116)", 0, 0, /* updated */ { 10068,-4043,-1068,-5319,14268,1044,-765,1701,6522 } }, { "Leica T (Typ 701)", 0, 0, /* added */ { 6295 ,-1679 ,-475 ,-5586 ,13046 ,2837 ,-1410 ,1889 ,7075 } }, { "Leica X2", 0, 0, /* added */ { 8336,-2853,-699,-4425,11989,2760,-954,1625,6396 } }, { "Leica X1", 0, 0, /* added */ { 9055,-2611,-666,-4906,12652,2519,-555,1384,7417 } }, { "Leica X", 0, 0, /* X(113), X-U(113), XV, X Vario(107) */ /* updated */ { 9062,-3198,-828,-4065,11772,2603,-761,1468,6458 } }, { "Mamiya M31", 0, 0, /* added */ { 4516 ,-244 ,-36 ,-7020 ,14976 ,2174 ,-3206 ,4670 ,7087 } }, { "Mamiya M22", 0, 0, /* added */ { 2905 ,732 ,-237 ,-8135 ,16626 ,1476 ,-3038 ,4253 ,7517 } }, { "Mamiya M18", 0, 0, /* added */ { 6516 ,-2050 ,-507 ,-8217 ,16703 ,1479 ,-3492 ,4741 ,8489 } }, { "Mamiya ZD", 0, 0, { 7645,2579,-1363,-8689,16717,2015,-3712,5941,5961 } }, { "Micron 2010", 110, 0, /* DJC */ { 16695,-3761,-2151,155,9682,163,3433,951,4904 } }, { "Minolta DiMAGE 5", 0, 0xf7d, /* updated */ { 9117,-3063,-973,-7949,15763,2306,-2752,3136,8093 } }, { "Minolta DiMAGE 7Hi", 0, 0xf7d, /* updated */ { 11555,-4064,-1256,-7903,15633,2409,-2811,3320,7358 } }, { "Minolta DiMAGE 7i", 0, 0xf7d, /* added */ { 11050,-3791,-1199,-7875,15585,2434,-2797,3359,7560 } }, { "Minolta DiMAGE 7", 0, 0xf7d, /* updated */ { 9258,-2879,-1008,-8076,15847,2351,-2806,3280,7821 } }, { "Minolta DiMAGE A1", 0, 0xf8b, /* updated */ { 9274,-2548,-1167,-8220,16324,1943,-2273,2721,8340 } }, { "Minolta DiMAGE A200", 0, 0, { 8560,-2487,-986,-8112,15535,2771,-1209,1324,7743 } }, { "Minolta DiMAGE A2", 0, 0xf8f, { 9097,-2726,-1053,-8073,15506,2762,-966,981,7763 } }, { "Minolta DiMAGE Z2", 0, 0, /* DJC */ { 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } }, { "Minolta DYNAX 5", 0, 0xffb, { 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } }, { "Minolta Maxxum 5D", 0, 0xffb, /* added */ { 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } }, { "Minolta ALPHA-5 DIGITAL", 0, 0xffb, /* added */ { 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } }, { "Minolta ALPHA SWEET DIGITAL", 0, 0xffb, /* added */ { 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } }, { "Minolta DYNAX 7", 0, 0xffb, { 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } }, { "Minolta Maxxum 7D", 0, 0xffb, /* added */ { 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } }, { "Minolta ALPHA-7 DIGITAL", 0, 0xffb, /* added */ { 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } }, { "Motorola PIXL", 0, 0, /* DJC */ { 8898,-989,-1033,-3292,11619,1674,-661,3178,5216 } }, { "Nikon D100", 0, 0, { 5902,-933,-782,-8983,16719,2354,-1402,1455,6464 } }, { "Nikon D1H", 0, 0, /* updated */ { 7659,-2238,-935,-8942,16969,2004,-2701,3051,8690 } }, { "Nikon D1X", 0, 0, { 7702,-2245,-975,-9114,17242,1875,-2679,3055,8521 } }, { "Nikon D1", 0, 0, /* multiplied by 2.218750, 1.0, 1.148438 */ { 16772,-4726,-2141,-7611,15713,1972,-2846,3494,9521 } }, { "Nikon D200", 0, 0xfbc, { 8367,-2248,-763,-8758,16447,2422,-1527,1550,8053 } }, { "Nikon D2H", 0, 0, { 5733,-911,-629,-7967,15987,2055,-3050,4013,7048 } }, { "Nikon D2X", 0, 0, /* updated */ { 10231,-2768,-1254,-8302,15900,2551,-797,681,7148 } }, { "Nikon D3000", 0, 0, { 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } }, { "Nikon D3100", 0, 0, { 7911,-2167,-813,-5327,13150,2408,-1288,2483,7968 } }, { "Nikon D3200", 0, 0xfb9, { 7013,-1408,-635,-5268,12902,2640,-1470,2801,7379 } }, { "Nikon D3300", 0, 0, { 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } }, { "Nikon D3400", 0, 0, { 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } }, { "Nikon D300", 0, 0, { 9030,-1992,-715,-8465,16302,2255,-2689,3217,8069 } }, { "Nikon D3X", 0, 0, { 7171,-1986,-648,-8085,15555,2718,-2170,2512,7457 } }, { "Nikon D3S", 0, 0, { 8828,-2406,-694,-4874,12603,2541,-660,1509,7587 } }, { "Nikon D3", 0, 0, { 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } }, { "Nikon D40X", 0, 0, { 8819,-2543,-911,-9025,16928,2151,-1329,1213,8449 } }, { "Nikon D40", 0, 0, { 6992,-1668,-806,-8138,15748,2543,-874,850,7897 } }, { "Nikon D4S", 0, 0, { 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } }, { "Nikon D4", 0, 0, { 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } }, { "Nikon Df", 0, 0, { 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } }, { "Nikon D5000", 0, 0xf00, { 7309,-1403,-519,-8474,16008,2622,-2433,2826,8064 } }, { "Nikon D5100", 0, 0x3de6, { 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } }, { "Nikon D5200", 0, 0, { 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } }, { "Nikon D5300", 0, 0, { 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } }, { "Nikon D5500", 0, 0, { 8821,-2938,-785,-4178,12142,2287,-824,1651,6860 } }, { "Nikon D5600", 0, 0, { 8821,-2938,-785,-4178,12142,2287,-824,1651,6860 } }, { "Nikon D500", 0, 0, { 8813,-3210,-1036,-4703,12868,2021,-1054,1940,6129 } }, { "Nikon D50", 0, 0, { 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } }, { "Nikon D5", 0, 0, { 9200,-3522,-992,-5755,13803,2117,-753,1486,6338 } }, { "Nikon D600", 0, 0x3e07, { 8178,-2245,-609,-4857,12394,2776,-1207,2086,7298 } }, { "Nikon D610",0, 0, /* updated */ { 8178,-2245,-609,-4857,12394,2776,-1207,2086,7298 } }, { "Nikon D60", 0, 0, { 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } }, { "Nikon D7000", 0, 0, { 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } }, { "Nikon D7100", 0, 0, { 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } }, { "Nikon D7200", 0, 0, { 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } }, { "Nikon D7500", 0, 0, { 8813,-3210,-1036,-4703,12868,2021,-1054,1940,6129 } }, { "Nikon D750", -600, 0, { 9020,-2890,-715,-4535,12436,2348,-934,1919,7086 } }, { "Nikon D700", 0, 0, { 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } }, { "Nikon D70", 0, 0, { 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } }, { "Nikon D810A", 0, 0, { 11973,-5685,-888,-1965,10326,1901,-115,1123,7169 } }, { "Nikon D810", 0, 0, { 9369,-3195,-791,-4488,12430,2301,-893,1796,6872 } }, { "Nikon D800", 0, 0, { 7866,-2108,-555,-4869,12483,2681,-1176,2069,7501 } }, { "Nikon D80", 0, 0, { 8629,-2410,-883,-9055,16940,2171,-1490,1363,8520 } }, { "Nikon D90", 0, 0xf00, { 7309,-1403,-519,-8474,16008,2622,-2434,2826,8064 } }, { "Nikon E700", 0, 0x3dd, /* DJC */ { -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } }, { "Nikon E800", 0, 0x3dd, /* DJC */ { -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } }, { "Nikon E950", 0, 0x3dd, /* DJC */ { -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } }, { "Nikon E995", 0, 0, /* copied from E5000 */ { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E2100", 0, 0, /* copied from Z2, new white balance */ { 13142,-4152,-1596,-4655,12374,2282,-1769,2696,6711 } }, { "Nikon E2500", 0, 0, { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E3200", 0, 0, /* DJC */ { 9846,-2085,-1019,-3278,11109,2170,-774,2134,5745 } }, { "Nikon E4300", 0, 0, /* copied from Minolta DiMAGE Z2 */ { 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } }, { "Nikon E4500", 0, 0, { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E5000", 0, 0, /* updated */ { -6678,12805,2248,5725,-499,3375,-5903,10713,6034,-270,9976,134 } }, { "Nikon E5400", 0, 0, /* updated */ { 9349,-2988,-1001,-7918,15766,2266,-2097,2680,6839 } }, { "Nikon E5700", 0, 0, /* updated */ { -6475,12496,2428,5409,-16,3180,-5965,10912,5866,-177,9918,248 } }, { "Nikon E8400", 0, 0, { 7842,-2320,-992,-8154,15718,2599,-1098,1342,7560 } }, { "Nikon E8700", 0, 0, { 8489,-2583,-1036,-8051,15583,2643,-1307,1407,7354 } }, { "Nikon E8800", 0, 0, { 7971,-2314,-913,-8451,15762,2894,-1442,1520,7610 } }, { "Nikon COOLPIX A", 0, 0, { 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } }, { "Nikon COOLPIX B700", 0, 0, { 14387,-6014,-1299,-1357,9975,1616,467,1047,4744 } }, { "Nikon COOLPIX P330", -200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX P340", -200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX Kalon", 0, 0, /* added */ { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX Deneb", 0, 0, /* added */ { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX P6000", 0, 0, { 9698,-3367,-914,-4706,12584,2368,-837,968,5801 } }, { "Nikon COOLPIX P7000", 0, 0, { 11432,-3679,-1111,-3169,11239,2202,-791,1380,4455 } }, { "Nikon COOLPIX P7100", 0, 0, { 11053,-4269,-1024,-1976,10182,2088,-526,1263,4469 } }, { "Nikon COOLPIX P7700", -3200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX P7800", -3200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon 1 V3", -200, 0, { 5958,-1559,-571,-4021,11453,2939,-634,1548,5087 } }, { "Nikon 1 J4", 0, 0, { 5958,-1559,-571,-4021,11453,2939,-634,1548,5087 } }, { "Nikon 1 J5", 0, 0, { 7520,-2518,-645,-3844,12102,1945,-913,2249,6835 } }, { "Nikon 1 S2", -200, 0, { 6612,-1342,-618,-3338,11055,2623,-174,1792,5075 } }, { "Nikon 1 V2", 0, 0, { 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } }, { "Nikon 1 J3", 0, 0, /* updated */ { 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } }, { "Nikon 1 AW1", 0, 0, { 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } }, { "Nikon 1 ", 0, 0, /* J1, J2, S1, V1 */ { 8994,-2667,-865,-4594,12324,2552,-699,1786,6260 } }, { "Olympus AIR-A01", 0, 0xfe1, { 8992,-3093,-639,-2563,10721,2122,-437,1270,5473 } }, { "Olympus C5050", 0, 0, /* updated */ { 10633,-3234,-1285,-7460,15570,1967,-1917,2510,6299 } }, { "Olympus C5060", 0, 0, { 10445,-3362,-1307,-7662,15690,2058,-1135,1176,7602 } }, { "Olympus C7070", 0, 0, { 10252,-3531,-1095,-7114,14850,2436,-1451,1723,6365 } }, { "Olympus C70", 0, 0, { 10793,-3791,-1146,-7498,15177,2488,-1390,1577,7321 } }, { "Olympus C80", 0, 0, { 8606,-2509,-1014,-8238,15714,2703,-942,979,7760 } }, { "Olympus E-10", 0, 0xffc, /* updated */ { 12970,-4703,-1433,-7466,15843,1644,-2191,2451,6668 } }, { "Olympus E-1", 0, 0, { 11846,-4767,-945,-7027,15878,1089,-2699,4122,8311 } }, { "Olympus E-20", 0, 0xffc, /* updated */ { 13414,-4950,-1517,-7166,15293,1960,-2325,2664,7212 } }, { "Olympus E-300", 0, 0, { 7828,-1761,-348,-5788,14071,1830,-2853,4518,6557 } }, { "Olympus E-330", 0, 0, { 8961,-2473,-1084,-7979,15990,2067,-2319,3035,8249 } }, { "Olympus E-30", 0, 0xfbc, { 8144,-1861,-1111,-7763,15894,1929,-1865,2542,7607 } }, { "Olympus E-3", 0, 0xf99, { 9487,-2875,-1115,-7533,15606,2010,-1618,2100,7389 } }, { "Olympus E-400", 0, 0, { 6169,-1483,-21,-7107,14761,2536,-2904,3580,8568 } }, { "Olympus E-410", 0, 0xf6a, { 8856,-2582,-1026,-7761,15766,2082,-2009,2575,7469 } }, { "Olympus E-420", 0, 0xfd7, { 8746,-2425,-1095,-7594,15612,2073,-1780,2309,7416 } }, { "Olympus E-450", 0, 0xfd2, { 8745,-2425,-1095,-7594,15613,2073,-1780,2309,7416 } }, { "Olympus E-500", 0, 0, { 8136,-1968,-299,-5481,13742,1871,-2556,4205,6630 } }, { "Olympus E-510", 0, 0xf6a, { 8785,-2529,-1033,-7639,15624,2112,-1783,2300,7817 } }, { "Olympus E-520", 0, 0xfd2, { 8344,-2322,-1020,-7596,15635,2048,-1748,2269,7287 } }, { "Olympus E-5", 0, 0xeec, { 11200,-3783,-1325,-4576,12593,2206,-695,1742,7504 } }, { "Olympus E-600", 0, 0xfaf, { 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } }, { "Olympus E-620", 0, 0xfaf, { 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } }, { "Olympus E-P1", 0, 0xffd, { 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } }, { "Olympus E-P2", 0, 0xffd, { 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } }, { "Olympus E-P3", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { "Olympus E-P5", 0, 0, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-PL1s", 0, 0, { 11409,-3872,-1393,-4572,12757,2003,-709,1810,7415 } }, { "Olympus E-PL1", 0, 0, { 11408,-4289,-1215,-4286,12385,2118,-387,1467,7787 } }, { "Olympus E-PL2", 0, 0xcf3, { 15030,-5552,-1806,-3987,12387,1767,-592,1670,7023 } }, { "Olympus E-PL3", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { "Olympus E-PL5", 0, 0xfcb, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-PL6", 0, 0, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-PL7", 0, 0, { 9197,-3190,-659,-2606,10830,2039,-458,1250,5458 } }, { "Olympus E-PL8", 0, 0, { 9197,-3190,-659,-2606,10830,2039,-458,1250,5458 } }, { "Olympus E-PM1", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { "Olympus E-PM2", 0, 0, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-M10", 0, 0, /* Same for E-M10MarkII */ { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-M1MarkII", 0, 0, { 9383,-3170,-763,-2457,10702,2020,-384,1236,5552 } }, { "Olympus E-M1", 0, 0, { 7687,-1984,-606,-4327,11928,2721,-1381,2339,6452 } }, { "Olympus E-M5MarkII", 0, 0, { 9422,-3258,-711,-2655,10898,2015,-512,1354,5512 } }, { "Olympus E-M5", 0, 0xfe1, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus PEN-F",0, 0, { 9476,-3182,-765,-2613,10958,1893,-449,1315,5268 } }, { "Olympus SP350", 0, 0, { 12078,-4836,-1069,-6671,14306,2578,-786,939,7418 } }, { "Olympus SP3", 0, 0, { 11766,-4445,-1067,-6901,14421,2707,-1029,1217,7572 } }, { "Olympus SP500UZ", 0, 0xfff, { 9493,-3415,-666,-5211,12334,3260,-1548,2262,6482 } }, { "Olympus SP510UZ", 0, 0xffe, { 10593,-3607,-1010,-5881,13127,3084,-1200,1805,6721 } }, { "Olympus SP550UZ", 0, 0xffe, { 11597,-4006,-1049,-5432,12799,2957,-1029,1750,6516 } }, { "Olympus SP560UZ", 0, 0xff9, { 10915,-3677,-982,-5587,12986,2911,-1168,1968,6223 } }, { "Olympus SP565UZ", 0, 0, /* added */ { 11856,-4469,-1159,-4814,12368,2756,-993,1779,5589 } }, { "Olympus SP570UZ", 0, 0, { 11522,-4044,-1146,-4736,12172,2904,-988,1829,6039 } }, { "Olympus SH-2", 0, 0, { 10156,-3425,-1077,-2611,11177,1624,-385,1592,5080 } }, { "Olympus SH-3", 0, 0, /* Alias of SH-2 */ { 10156,-3425,-1077,-2611,11177,1624,-385,1592,5080 } }, { "Olympus STYLUS1",0, 0, /* updated */ { 8360,-2420,-880,-3928,12353,1739,-1381,2416,5173 } }, { "Olympus TG-4", 0, 0, { 11426,-4159,-1126,-2066,10678,1593,-120,1327,4998 } }, { "Olympus TG-5", 0, 0, { 10899,-3833,-1082,-2112,10736,1575,-267,1452,5269 } }, { "Olympus XZ-10", 0, 0, { 9777,-3483,-925,-2886,11297,1800,-602,1663,5134 } }, { "Olympus XZ-1", 0, 0, { 10901,-4095,-1074,-1141,9208,2293,-62,1417,5158 } }, { "Olympus XZ-2", 0, 0, { 9777,-3483,-925,-2886,11297,1800,-602,1663,5134 } }, { "OmniVision", 16, 0x3ff, { 12782,-4059,-379,-478,9066,1413,1340,1513,5176 } }, /* DJC */ { "Pentax *ist DL2", 0, 0, { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { "Pentax *ist DL", 0, 0, { 10829,-2838,-1115,-8339,15817,2696,-837,680,11939 } }, { "Pentax *ist DS2", 0, 0, { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { "Pentax *ist DS", 0, 0, { 10371,-2333,-1206,-8688,16231,2602,-1230,1116,11282 } }, { "Pentax *ist D", 0, 0, { 9651,-2059,-1189,-8881,16512,2487,-1460,1345,10687 } }, { "Pentax GR", 0, 0, /* added */ { 5329,-1459,-390,-5407,12930,2768,-1119,1772,6046 } }, { "Pentax K-01", 0, 0, /* added */ { 8134,-2728,-645,-4365,11987,2694,-838,1509,6498 } }, { "Pentax K10D", 0, 0, /* updated */ { 9679,-2965,-811,-8622,16514,2182,-975,883,9793 } }, { "Pentax K1", 0, 0, { 11095,-3157,-1324,-8377,15834,2720,-1108,947,11688 } }, { "Pentax K20D", 0, 0, { 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } }, { "Pentax K200D", 0, 0, { 9186,-2678,-907,-8693,16517,2260,-1129,1094,8524 } }, { "Pentax K2000", 0, 0, /* updated */ { 9730,-2989,-970,-8527,16258,2381,-1060,970,8362 } }, { "Pentax K-m", 0, 0, /* updated */ { 9730,-2989,-970,-8527,16258,2381,-1060,970,8362 } }, { "Pentax KP", 0, 0, { 7825,-2160,-1403,-4841,13555,1349,-1559,2449,5814 } }, { "Pentax K-x", 0, 0, { 8843,-2837,-625,-5025,12644,2668,-411,1234,7410 } }, { "Pentax K-r", 0, 0, { 9895,-3077,-850,-5304,13035,2521,-883,1768,6936 } }, { "Pentax K-1", 0, 0, /* updated */ { 8596,-2981,-639,-4202,12046,2431,-685,1424,6122 } }, { "Pentax K-30", 0, 0, /* updated */ { 8134,-2728,-645,-4365,11987,2694,-838,1509,6498 } }, { "Pentax K-3 II", 0, 0, /* updated */ { 7415,-2052,-721,-5186,12788,2682,-1446,2157,6773 } }, { "Pentax K-3", 0, 0, { 7415,-2052,-721,-5186,12788,2682,-1446,2157,6773 } }, { "Pentax K-5 II", 0, 0, { 8170,-2725,-639,-4440,12017,2744,-771,1465,6599 } }, { "Pentax K-500", 0, 0, /* added */ { 8109,-2740,-608,-4593,12175,2731,-1006,1515,6545 } }, { "Pentax K-50", 0, 0, /* added */ { 8109,-2740,-608,-4593,12175,2731,-1006,1515,6545 } }, { "Pentax K-5", 0, 0, { 8713,-2833,-743,-4342,11900,2772,-722,1543,6247 } }, { "Pentax K-70", 0, 0, { 8766,-3149,-747,-3976,11943,2292,-517,1259,5552 } }, { "Pentax K-7", 0, 0, { 9142,-2947,-678,-8648,16967,1663,-2224,2898,8615 } }, { "Pentax KP", 0, 0, /* temp */ { 8626,-2607,-1155,-3995,12301,1881,-1039,1822,6925 } }, { "Pentax K-S1", 0, 0, { 8512,-3211,-787,-4167,11966,2487,-638,1288,6054 } }, { "Pentax K-S2", 0, 0, { 8662,-3280,-798,-3928,11771,2444,-586,1232,6054 } }, { "Pentax Q-S1", 0, 0, { 12995,-5593,-1107,-1879,10139,2027,-64,1233,4919 } }, { "Pentax Q7", 0, 0, /* added */ { 10901,-3938,-1025,-2743,11210,1738,-823,1805,5344 } }, { "Pentax Q10", 0, 0, /* updated */ { 11562,-4183,-1172,-2357,10919,1641,-582,1726,5112 } }, { "Pentax Q", 0, 0, /* added */ { 11731,-4169,-1267,-2015,10727,1473,-217,1492,4870 } }, { "Pentax MX-1", 0, 0, /* updated */ { 9296,-3146,-888,-2860,11287,1783,-618,1698,5151 } }, { "Pentax 645D", 0, 0x3e00, { 10646,-3593,-1158,-3329,11699,1831,-667,2874,6287 } }, { "Pentax 645Z", 0, 0, /* updated */ { 9519,-3591,-664,-4074,11725,2671,-624,1501,6653 } }, { "Panasonic DMC-CM10", -15, 0, { 8770,-3194,-820,-2871,11281,1803,-513,1552,4434 } }, { "Panasonic DMC-CM1", -15, 0, { 8770,-3194,-820,-2871,11281,1803,-513,1552,4434 } }, { "Panasonic DC-FZ82", -15, 0, /* markets: FZ80 FZ82 */ { 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } }, { "Panasonic DC-FZ80", -15, 0, /* markets: FZ80 FZ82 */ { 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } }, { "Panasonic DMC-FZ8", 0, 0xf7f, { 8986,-2755,-802,-6341,13575,3077,-1476,2144,6379 } }, { "Panasonic DMC-FZ18", 0, 0, { 9932,-3060,-935,-5809,13331,2753,-1267,2155,5575 } }, { "Panasonic DMC-FZ28", -15, 0xf96, { 10109,-3488,-993,-5412,12812,2916,-1305,2140,5543 } }, { "Panasonic DMC-FZ300", -15, 0xfff, { 8378,-2798,-769,-3068,11410,1877,-538,1792,4623 } }, { "Panasonic DMC-FZ330", -15, 0xfff, { 8378,-2798,-769,-3068,11410,1877,-538,1792,4623 } }, { "Panasonic DMC-FZ30", 0, 0xf94, { 10976,-4029,-1141,-7918,15491,2600,-1670,2071,8246 } }, { "Panasonic DMC-FZ3", -15, 0, { 9938,-2780,-890,-4604,12393,2480,-1117,2304,4620 } }, { "Panasonic DMC-FZ4", -15, 0, /* 40,42,45 */ { 13639,-5535,-1371,-1698,9633,2430,316,1152,4108 } }, { "Panasonic DMC-FZ50", 0, 0, { 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } }, { "Panasonic DMC-FZ7", -15, 0, { 11532,-4324,-1066,-2375,10847,1749,-564,1699,4351 } }, { "Leica V-LUX1", 0, 0, { 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } }, { "Leica V-LUX 1", 0, 0, { 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } }, { "Panasonic DMC-L10", -15, 0xf96, { 8025,-1942,-1050,-7920,15904,2100,-2456,3005,7039 } }, { "Panasonic DMC-L1", 0, 0xf7f, { 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } }, { "Leica DIGILUX3", 0, 0xf7f, /* added */ { 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } }, { "Leica DIGILUX 3", 0, 0xf7f, { 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } }, { "Panasonic DMC-LC1", 0, 0, { 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } }, { "Leica DIGILUX2", 0, 0, /* added */ { 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } }, { "Leica DIGILUX 2", 0, 0, { 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } }, { "Panasonic DMC-LX100", -15, 0, { 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } }, { "Leica D-LUX (Typ 109)", -15, 0, { 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } }, { "Panasonic DMC-LF1", -15, 0, { 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 } }, { "Leica C (Typ 112)", -15, 0, { 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 } }, { "Panasonic DMC-LX9", -15, 0, /* markets: LX9 LX10 LX15 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-LX10", -15, 0, /* markets: LX9 LX10 LX15 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-LX15", -15, 0, /* markets: LX9 LX10 LX15 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-LX1", 0, 0xf7f, { 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } }, { "Leica D-Lux (Typ 109)", 0, 0xf7f, { 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } }, { "Leica D-LUX2", 0, 0xf7f, { 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } }, { "Leica D-LUX 2", 0, 0xf7f, /* added */ { 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } }, { "Panasonic DMC-LX2", 0, 0, { 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } }, { "Leica D-LUX3", 0, 0, { 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } }, { "Leica D-LUX 3", 0, 0, /* added */ { 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } }, { "Panasonic DMC-LX3", -15, 0, { 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } }, { "Leica D-LUX 4", -15, 0, { 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } }, { "Panasonic DMC-LX5", -15, 0, { 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } }, { "Leica D-LUX 5", -15, 0, { 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } }, { "Panasonic DMC-LX7", -15, 0, { 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 } }, { "Leica D-LUX 6", -15, 0, { 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 } }, { "Panasonic DMC-FZ1000", -15, 0, { 7830,-2696,-763,-3325,11667,1866,-641,1712,4824 } }, { "Leica V-LUX (Typ 114)", 15, 0, { 7830,-2696,-763,-3325,11667,1866,-641,1712,4824 } }, { "Panasonic DMC-FZ100", -15, 0xfff, { 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } }, { "Leica V-LUX 2", -15, 0xfff, { 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } }, { "Panasonic DMC-FZ150", -15, 0xfff, { 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } }, { "Leica V-LUX 3", -15, 0xfff, { 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } }, { "Panasonic DMC-FZ2000", -15, 0, /* markets: DMC-FZ2000, DMC-FZ2500 ,FZH1 */ { 7386,-2443,-743,-3437,11864,1757,-608,1660,4766 } }, { "Panasonic DMC-FZ2500", -15, 0, { 7386,-2443,-743,-3437,11864,1757,-608,1660,4766 } }, { "Panasonic DMC-FZH1", -15, 0, { 7386,-2443,-743,-3437,11864,1757,-608,1660,4766 } }, { "Panasonic DMC-FZ200", -15, 0xfff, { 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 } }, { "Leica V-LUX 4", -15, 0xfff, { 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 } }, { "Panasonic DMC-FX150", -15, 0xfff, { 9082,-2907,-925,-6119,13377,3058,-1797,2641,5609 } }, { "Panasonic DMC-FX180", -15, 0xfff, /* added */ { 9082,-2907,-925,-6119,13377,3058,-1797,2641,5609 } }, { "Panasonic DMC-G10", 0, 0, { 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } }, { "Panasonic DMC-G1", -15, 0xf94, { 8199,-2065,-1056,-8124,16156,2033,-2458,3022,7220 } }, { "Panasonic DMC-G2", -15, 0xf3c, { 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } }, { "Panasonic DMC-G3", -15, 0xfff, { 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 } }, { "Panasonic DMC-G5", -15, 0xfff, { 7798,-2562,-740,-3879,11584,2613,-1055,2248,5434 } }, { "Panasonic DMC-G6", -15, 0xfff, { 8294,-2891,-651,-3869,11590,2595,-1183,2267,5352 } }, { "Panasonic DMC-G7", -15, 0xfff, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-G8", -15, 0xfff, /* markets: DMC-G8, DMC-G80, DMC-G81, DMC-G85 */ { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GF1", -15, 0xf92, { 7888,-1902,-1011,-8106,16085,2099,-2353,2866,7330 } }, { "Panasonic DMC-GF2", -15, 0xfff, { 7888,-1902,-1011,-8106,16085,2099,-2353,2866,7330 } }, { "Panasonic DMC-GF3", -15, 0xfff, { 9051,-2468,-1204,-5212,13276,2121,-1197,2510,6890 } }, { "Panasonic DMC-GF5", -15, 0xfff, { 8228,-2945,-660,-3938,11792,2430,-1094,2278,5793 } }, { "Panasonic DMC-GF6", -15, 0, { 8130,-2801,-946,-3520,11289,2552,-1314,2511,5791 } }, { "Panasonic DMC-GF7", -15, 0, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GF8", -15, 0, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GH1", -15, 0xf92, { 6299,-1466,-532,-6535,13852,2969,-2331,3112,5984 } }, { "Panasonic DMC-GH2", -15, 0xf95, { 7780,-2410,-806,-3913,11724,2484,-1018,2390,5298 } }, { "Panasonic DMC-GH3", -15, 0, { 6559,-1752,-491,-3672,11407,2586,-962,1875,5130 } }, { "Panasonic DMC-GH4", -15, 0, { 7122,-2108,-512,-3155,11201,2231,-541,1423,5045 } }, { "Panasonic AG-GH4", -15, 0, /* added */ { 7122,-2108,-512,-3155,11201,2231,-541,1423,5045 } }, { "Panasonic DC-GH5", -15, 0, { 7641,-2336,-605,-3218,11299,2187,-485,1338,5121 } }, { "Yuneec CGO4", -15, 0, { 7122,-2108,-512,-3155,11201,2231,-541,1423,5045 } }, { "Panasonic DMC-GM1", -15, 0, { 6770,-1895,-744,-5232,13145,2303,-1664,2691,5703 } }, { "Panasonic DMC-GM5", -15, 0, { 8238,-3244,-679,-3921,11814,2384,-836,2022,5852 } }, { "Panasonic DMC-GX1", -15, 0, { 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 } }, { "Panasonic DC-GX850", -15, 0, /* markets: GX850 GX800 GF9 */ { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DC-GX800", -15, 0, /* markets: GX850 GX800 GF9 */ { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DC-GF9", -15, 0, /* markets: GX850 GX800 GF9 */ { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GX85", -15, 0, /* markets: GX85 GX80 GX7MK2 */ { 7771,-3020,-629,-4029,11950,2345,-821,1977,6119 } }, { "Panasonic DMC-GX80", -15, 0, /* markets: GX85 GX80 GX7MK2 */ { 7771,-3020,-629,-4029,11950,2345,-821,1977,6119 } }, { "Panasonic DMC-GX7MK2", -15, 0, /* markets: GX85 GX80 GX7MK2 */ { 7771,-3020,-629,-4029,11950,2345,-821,1977,6119 } }, { "Panasonic DMC-GX7", -15,0, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GX8", -15,0, { 7564,-2263,-606,-3148,11239,2177,-540,1435,4853 } }, { "Panasonic DMC-TZ6", -15, 0, /* markets: ZS40 TZ60 TZ61 */ { 8607,-2822,-808,-3755,11930,2049,-820,2060,5224 } }, { "Panasonic DMC-TZ8", -15, 0, /* markets: ZS60 TZ80 TZ81 TZ82 TZ85 */ { 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } }, { "Panasonic DC-TZ90", -15, 0, /* markets: ZS70 TZ90 TZ91 TZ92 T93 */ { 9052,-3117,-883,-3045,11346,1927,-205,1520,4730 } }, { "Panasonic DC-TZ91", -15, 0, /* markets: ZS70 TZ90 TZ91 TZ92 T93 */ { 9052,-3117,-883,-3045,11346,1927,-205,1520,4730 } }, { "Panasonic DC-TZ92", -15, 0, /* markets: ZS70 TZ90 TZ91 TZ92 T93 */ { 9052,-3117,-883,-3045,11346,1927,-205,1520,4730 } }, { "Panasonic DC-T93", -15, 0, /* markets: ZS70 TZ90 TZ91 TZ92 T93 */ { 9052,-3117,-883,-3045,11346,1927,-205,1520,4730 } }, { "Panasonic DMC-ZS4", -15, 0, /* markets: ZS40 TZ60 TZ61 */ { 8607,-2822,-808,-3755,11930,2049,-820,2060,5224 } }, { "Panasonic DMC-TZ7", -15, 0, /* markets: ZS50 TZ70 TZ71 */ { 8802,-3135,-789,-3151,11468,1904,-550,1745,4810 } }, { "Panasonic DMC-ZS5", -15, 0, /* markets: ZS50 TZ70 TZ71 */ { 8802,-3135,-789,-3151,11468,1904,-550,1745,4810 } }, { "Panasonic DMC-ZS6", -15, 0, /* markets: ZS60 TZ80 TZ81 TZ85 */ { 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } }, { "Panasonic DC-ZS70", -15, 0, /* markets: ZS70 TZ90 TZ91 TZ92 T93 */ { 9052,-3117,-883,-3045,11346,1927,-205,1520,4730 } }, { "Panasonic DMC-ZS100", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-ZS110", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TZ100", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TZ101", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TZ110", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TX1", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Phase One H 20", 0, 0, /* DJC */ { 1313,1855,-109,-6715,15908,808,-327,1840,6020 } }, { "Phase One H20", 0, 0, /* DJC */ { 1313,1855,-109,-6715,15908,808,-327,1840,6020 } }, { "Phase One H 25", 0, 0, { 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } }, { "Phase One H25", 0, 0, /* added */ { 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } }, { "Phase One IQ280", 0, 0, /* added */ { 6294,686,-712,-5435,13417,2211,-1006,2435,5042 } }, { "Phase One IQ260", 0, 0, /* added */ { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One IQ250",0, 0, // { 4396,-153,-249,-5267,12249,2657,-1397,2323,6014 } }, /* keep for now */ { 3984,0,0,0,10000,0,0,0,7666 } }, { "Phase One IQ180", 0, 0, /* added */ { 6294,686,-712,-5435,13417,2211,-1006,2435,5042 } }, { "Phase One IQ160", 0, 0, /* added */ { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One IQ150", 0, 0, /* added */ { 3984,0,0,0,10000,0,0,0,7666 } }, { "Phase One IQ140", 0, 0, /* added */ { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One P65", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One P 65", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One P45", 0, 0, /* added */ { 5053,-24,-117,-5685,14077,1703,-2619,4491,5850 } }, { "Phase One P 45", 0, 0, /* added */ { 5053,-24,-117,-5685,14077,1703,-2619,4491,5850 } }, { "Phase One P40", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One P 40", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One P30", 0, 0, /* added */ { 4516,-244,-36,-7020,14976,2174,-3206,4670,7087 } }, { "Phase One P 30", 0, 0, /* added */ { 4516,-244,-36,-7020,14976,2174,-3206,4670,7087 } }, { "Phase One P25", 0, 0, /* added */ { 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } }, { "Phase One P 25", 0, 0, /* added */ { 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } }, { "Phase One P21", 0, 0, /* added */ { 6516,-2050,-507,-8217,16703,1479,-3492,4741,8489 } }, { "Phase One P 21", 0, 0, /* added */ { 6516,-2050,-507,-8217,16703,1479,-3492,4741,8489 } }, { "Phase One P20", 0, 0, /* added */ { 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } }, { "Phase One P20", 0, 0, /* added */ { 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } }, { "Phase One P 2", 0, 0, { 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } }, { "Phase One P2", 0, 0, { 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } }, { "Phase One IQ3 100MP", 0, 0, /* added */ { 2423,0,0,0,9901,0,0,0,7989 } }, { "Phase One IQ3 80MP", 0, 0, /* added */ { 6294,686,-712,-5435,13417,2211,-1006,2435,5042 } }, { "Phase One IQ3 60MP", 0, 0, /* added */ { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One IQ3 50MP", 0, 0, /* added */ { 3984,0,0,0,10000,0,0,0,7666 } }, { "Photron BC2-HD", 0, 0, /* DJC */ { 14603,-4122,-528,-1810,9794,2017,-297,2763,5936 } }, { "Polaroid x530", 0, 0, { 13458,-2556,-510,-5444,15081,205,0,0,12120 } }, { "Red One", 704, 0xffff, /* DJC */ { 21014,-7891,-2613,-3056,12201,856,-2203,5125,8042 } }, { "Ricoh S10 24-72mm F2.5-4.4 VC", 0, 0, /* added */ { 10531,-4043,-878,-2038,10270,2052,-107,895,4577 } }, { "Ricoh GR A12 50mm F2.5 MACRO", 0, 0, /* added */ { 8849,-2560,-689,-5092,12831,2520,-507,1280,7104 } }, { "Ricoh GR DIGITAL 3", 0, 0, /* added */ { 8170,-2496,-655,-5147,13056,2312,-1367,1859,5265 } }, { "Ricoh GR DIGITAL 4", 0, 0, /* added */ { 8771,-3151,-837,-3097,11015,2389,-703,1343,4924 } }, { "Ricoh GR II", 0, 0, { 4630,-834,-423,-4977,12805,2417,-638,1467,6115 } }, { "Ricoh GR", 0, 0, { 3708,-543,-160,-5381,12254,3556,-1471,1929,8234 } }, { "Ricoh GX200", 0, 0, /* added */ { 8040,-2368,-626,-4659,12543,2363,-1125,1581,5660 } }, { "Ricoh RICOH GX200", 0, 0, /* added */ { 8040,-2368,-626,-4659,12543,2363,-1125,1581,5660 } }, { "Ricoh GXR MOUNT A12", 0, 0, /* added */ { 7834,-2182,-739,-5453,13409,2241,-952,2005,6620 } }, { "Ricoh GXR A16", 0, 0, /* added */ { 7837,-2538,-730,-4370,12184,2461,-868,1648,5830 } }, { "Ricoh GXR A12", 0, 0, /* added */ { 10228,-3159,-933,-5304,13158,2371,-943,1873,6685 } }, { "Samsung EK-GN100", 0, 0, /* added */ /* Galaxy NX */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung EK-GN110", 0, 0, /* added */ /* Galaxy NX */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung EK-GN120", 0, 0, /* Galaxy NX */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung EK-KN120", 0, 0, /* added */ /* Galaxy NX */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung EX1", 0, 0x3e00, { 8898,-2498,-994,-3144,11328,2066,-760,1381,4576 } }, { "Samsung EX2F", 0, 0x7ff, { 10648,-3897,-1055,-2022,10573,1668,-492,1611,4742 } }, { "Samsung Galaxy S7 Edge", 0, 0, /* added */ { 9927,-3704,-1024,-3935,12758,1257,-389,1512,4993 } }, { "Samsung Galaxy S7", 0, 0, /* added */ { 9927,-3704,-1024,-3935,12758,1257,-389,1512,4993 } }, { "Samsung Galaxy NX", 0, 0, /* added */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung NX U", 0, 0, /* added */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung NX mini", 0, 0, { 5222,-1196,-550,-6540,14649,2009,-1666,2819,5657 } }, { "Samsung NX3300", 0, 0, { 8060,-2933,-761,-4504,12890,1762,-630,1489,5227 } }, { "Samsung NX3000", 0, 0, { 8060,-2933,-761,-4504,12890,1762,-630,1489,5227 } }, { "Samsung NX30", 0, 0, /* used for NX30/NX300/NX300M */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung NX2000", 0, 0, { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung NX2", 0, 0xfff, /* used for NX20/NX200/NX210 */ { 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } }, { "Samsung NX1000", 0, 0, { 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } }, { "Samsung NX1100", 0, 0, { 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } }, { "Samsung NX11", 0, 0, { 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } }, { "Samsung NX10", 0, 0, /* used for NX10/NX100 */ { 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } }, { "Samsung NX500", 0, 0, { 10686,-4042,-1052,-3595,13238,276,-464,1259,5931 } }, { "Samsung NX5", 0, 0, { 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } }, { "Samsung NX1", 0, 0, { 10686,-4042,-1052,-3595,13238,276,-464,1259,5931 } }, { "Samsung NXF1", 0, 0, /* added */ { 5222,-1196,-550,-6540,14649,2009,-1666,2819,5657 } }, { "Samsung WB2000", 0, 0xfff, { 12093,-3557,-1155,-1000,9534,1733,-22,1787,4576 } }, { "Samsung GX10", 0, 0, /* added */ /* Pentax K10D */ { 9679,-2965,-811,-8622,16514,2182,-975,883,9793 } }, { "Samsung GX-10", 0, 0, /* added */ /* Pentax K10D */ { 9679,-2965,-811,-8622,16514,2182,-975,883,9793 } }, { "Samsung GX-1", 0, 0, /* used for GX-1L/GX-1S */ { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { "Samsung GX20", 0, 0, /* copied from Pentax K20D */ { 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } }, { "Samsung GX-20", 0, 0, /* added */ /* copied from Pentax K20D */ { 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } }, { "Samsung S85", 0, 0, /* DJC */ { 11885,-3968,-1473,-4214,12299,1916,-835,1655,5549 } }, // Foveon: LibRaw color data { "Sigma dp0 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma dp1 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma dp2 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma dp3 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma sd Quattro H", 256, 0, { 1295,108,-311, 256,828,-65,-28,750,254 } }, /* temp */ { "Sigma sd Quattro", 2047, 0, { 1295,108,-311, 256,828,-65,-28,750,254 } }, /* temp */ { "Sigma SD9", 15, 4095, /* updated */ { 13564,-2537,-751,-5465,15154,194,-67,116,10425 } }, { "Sigma SD10", 15, 16383, /* updated */ { 6787,-1682,575,-3091,8357,160,217,-369,12314 } }, { "Sigma SD14", 15, 16383, /* updated */ { 13589,-2509,-739,-5440,15104,193,-61,105,10554 } }, { "Sigma SD15", 15, 4095, /* updated */ { 13556,-2537,-730,-5462,15144,195,-61,106,10577 } }, // Merills + SD1 { "Sigma SD1", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, { "Sigma DP1 Merrill", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, { "Sigma DP2 Merrill", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, { "Sigma DP3 Merrill", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, // Sigma DP (non-Merill Versions) { "Sigma DP1X", 0, 4095, /* updated */ { 13704,-2452,-857,-5413,15073,186,-89,151,9820 } }, { "Sigma DP1", 0, 4095, /* updated */ { 12774,-2591,-394,-5333,14676,207,15,-21,12127 } }, { "Sigma DP", 0, 4095, /* LibRaw */ // { 7401,-1169,-567,2059,3769,1510,664,3367,5328 } }, { 13100,-3638,-847,6855,2369,580,2723,3218,3251 } }, { "Sinar", 0, 0, /* DJC */ { 16442,-2956,-2422,-2877,12128,750,-1136,6066,4559 } }, { "Sony DSC-F828", 0, 0, { 7924,-1910,-777,-8226,15459,2998,-1517,2199,6818,-7242,11401,3481 } }, { "Sony DSC-R1", 0, 0, { 8512,-2641,-694,-8042,15670,2526,-1821,2117,7414 } }, { "Sony DSC-V3", 0, 0, { 7511,-2571,-692,-7894,15088,3060,-948,1111,8128 } }, {"Sony DSC-RX100M5", -800, 0, { 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } }, { "Sony DSC-RX100M", -800, 0, /* used for M2/M3/M4 */ { 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } }, { "Sony DSC-RX100", 0, 0, { 8651,-2754,-1057,-3464,12207,1373,-568,1398,4434 } }, { "Sony DSC-RX10",0, 0, /* same for M2/M3 */ { 6679,-1825,-745,-5047,13256,1953,-1580,2422,5183 } }, { "Sony DSC-RX1RM2", 0, 0, { 6629,-1900,-483,-4618,12349,2550,-622,1381,6514 } }, { "Sony DSC-RX1R", 0, 0, /* updated */ { 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } }, { "Sony DSC-RX1", 0, 0, { 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } }, { "Sony DSLR-A100", 0, 0xfeb, { 9437,-2811,-774,-8405,16215,2290,-710,596,7181 } }, { "Sony DSLR-A290", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { "Sony DSLR-A2", 0, 0, { 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } }, { "Sony DSLR-A300", 0, 0, { 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } }, { "Sony DSLR-A330", 0, 0, { 9847,-3091,-929,-8485,16346,2225,-714,595,7103 } }, { "Sony DSLR-A350", 0, 0xffc, { 6038,-1484,-578,-9146,16746,2513,-875,746,7217 } }, { "Sony DSLR-A380", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { "Sony DSLR-A390", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { "Sony DSLR-A450", 0, 0xfeb, { 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } }, { "Sony DSLR-A580", 0, 0xfeb, { 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } }, { "Sony DSLR-A500", 0, 0xfeb, { 6046,-1127,-278,-5574,13076,2786,-691,1419,7625 } }, { "Sony DSLR-A5", 0, 0xfeb, { 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } }, { "Sony DSLR-A700", 0, 0, { 5775,-805,-359,-8574,16295,2391,-1943,2341,7249 } }, { "Sony DSLR-A850", 0, 0, { 5413,-1162,-365,-5665,13098,2866,-608,1179,8440 } }, { "Sony DSLR-A900", 0, 0, { 5209,-1072,-397,-8845,16120,2919,-1618,1803,8654 } }, { "Sony ILCA-68", 0, 0, { 6435,-1903,-536,-4722,12449,2550,-663,1363,6517 } }, { "Sony ILCA-77M2", 0, 0, { 5991,-1732,-443,-4100,11989,2381,-704,1467,5992 } }, { "Sony ILCA-99M2", 0, 0, { 6660,-1918,-471,-4613,12398,2485,-649,1433,6447 } }, { "Sony ILCE-9", 0, 0, { 6389,-1703,-378,-4562,12265,2587,-670,1489,6550 } }, { "Sony ILCE-7M2", 0, 0, { 5271,-712,-347,-6153,13653,2763,-1601,2366,7242 } }, { "Sony ILCE-7SM2", 0, 0, { 5838,-1430,-246,-3497,11477,2297,-748,1885,5778 } }, { "Sony ILCE-7S", 0, 0, { 5838,-1430,-246,-3497,11477,2297,-748,1885,5778 } }, { "Sony ILCE-7RM2", 0, 0, { 6629,-1900,-483,-4618,12349,2550,-622,1381,6514 } }, { "Sony ILCE-7R", 0, 0, { 4913,-541,-202,-6130,13513,2906,-1564,2151,7183 } }, { "Sony ILCE-7", 0, 0, { 5271,-712,-347,-6153,13653,2763,-1601,2366,7242 } }, { "Sony ILCE-6300", 0, 0, { 5973,-1695,-419,-3826,11797,2293,-639,1398,5789 } }, { "Sony ILCE-6500", 0, 0, { 5973,-1695,-419,-3826,11797,2293,-639,1398,5789 } }, { "Sony ILCE", 0, 0, /* 3000, 5000, 5100, 6000, and QX1 */ { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony MODEL-NAME", 0, 0, /* added */ { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony NEX-5N", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony NEX-5R", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-5T", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-3N", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-3", 0, 0, { 6549,-1550,-436,-4880,12435,2753,-854,1868,6976 } }, { "Sony NEX-5", 0, 0, { 6549,-1550,-436,-4880,12435,2753,-854,1868,6976 } }, { "Sony NEX-6", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-7", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony NEX-VG30", 0, 0, /* added */ { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-VG900", 0, 0, /* added */ { 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } }, { "Sony NEX", 0, 0, /* NEX-C3, NEX-F3, NEX-VG20 */ { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A33", 0, 0, { 6069,-1221,-366,-5221,12779,2734,-1024,2066,6834 } }, { "Sony SLT-A35", 0, 0, { 5986,-1618,-415,-4557,11820,3120,-681,1404,6971 } }, { "Sony SLT-A37", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A55", 0, 0, { 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } }, { "Sony SLT-A57", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A58", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A65", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony SLT-A77", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony SLT-A99", 0, 0, { 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } }, }; // clang-format on double cam_xyz[4][3]; char name[130]; int i, j; if (colors > 4 || colors < 1) return; int bl4 = (cblack[0] + cblack[1] + cblack[2] + cblack[3]) / 4, bl64 = 0; if (cblack[4] * cblack[5] > 0) { for (unsigned c = 0; c < 4096 && c < cblack[4] * cblack[5]; c++) bl64 += cblack[c + 6]; bl64 /= cblack[4] * cblack[5]; } int rblack = black + bl4 + bl64; sprintf(name, "%s %s", t_make, t_model); for (i = 0; i < sizeof table / sizeof *table; i++) if (!strncasecmp(name, table[i].prefix, strlen(table[i].prefix))) { if (!dng_version) { if (table[i].t_black > 0) { black = (ushort)table[i].t_black; memset(cblack, 0, sizeof(cblack)); } else if (table[i].t_black < 0 && rblack == 0) { black = (ushort)(-table[i].t_black); memset(cblack, 0, sizeof(cblack)); } if (table[i].t_maximum) maximum = (ushort)table[i].t_maximum; } if (table[i].trans[0]) { for (raw_color = j = 0; j < 12; j++) #ifdef LIBRAW_LIBRARY_BUILD if (internal_only) imgdata.color.cam_xyz[0][j] = table[i].trans[j] / 10000.0; else imgdata.color.cam_xyz[0][j] = #endif ((double *)cam_xyz)[j] = table[i].trans[j] / 10000.0; #ifdef LIBRAW_LIBRARY_BUILD if (!internal_only) #endif cam_xyz_coeff(rgb_cam, cam_xyz); } break; } } void CLASS simple_coeff(int index) { static const float table[][12] = {/* index 0 -- all Foveon cameras */ {1.4032, -0.2231, -0.1016, -0.5263, 1.4816, 0.017, -0.0112, 0.0183, 0.9113}, /* index 1 -- Kodak DC20 and DC25 */ {2.25, 0.75, -1.75, -0.25, -0.25, 0.75, 0.75, -0.25, -0.25, -1.75, 0.75, 2.25}, /* index 2 -- Logitech Fotoman Pixtura */ {1.893, -0.418, -0.476, -0.495, 1.773, -0.278, -1.017, -0.655, 2.672}, /* index 3 -- Nikon E880, E900, and E990 */ {-1.936280, 1.800443, -1.448486, 2.584324, 1.405365, -0.524955, -0.289090, 0.408680, -1.204965, 1.082304, 2.941367, -1.818705}}; int i, c; for (raw_color = i = 0; i < 3; i++) FORCC rgb_cam[i][c] = table[index][i * colors + c]; } short CLASS guess_byte_order(int words) { uchar test[4][2]; int t = 2, msb; double diff, sum[2] = {0, 0}; fread(test[0], 2, 2, ifp); for (words -= 2; words--;) { fread(test[t], 2, 1, ifp); for (msb = 0; msb < 2; msb++) { diff = (test[t ^ 2][msb] << 8 | test[t ^ 2][!msb]) - (test[t][msb] << 8 | test[t][!msb]); sum[msb] += diff * diff; } t = (t + 1) & 3; } return sum[0] < sum[1] ? 0x4d4d : 0x4949; } float CLASS find_green(int bps, int bite, int off0, int off1) { UINT64 bitbuf = 0; int vbits, col, i, c; ushort img[2][2064]; double sum[] = {0, 0}; FORC(2) { fseek(ifp, c ? off1 : off0, SEEK_SET); for (vbits = col = 0; col < width; col++) { for (vbits -= bps; vbits < 0; vbits += bite) { bitbuf <<= bite; for (i = 0; i < bite; i += 8) bitbuf |= (unsigned)(fgetc(ifp) << i); } img[c][col] = bitbuf << (64 - bps - vbits) >> (64 - bps); } } FORC(width - 1) { sum[c & 1] += ABS(img[0][c] - img[1][c + 1]); sum[~c & 1] += ABS(img[1][c] - img[0][c + 1]); } return 100 * log(sum[0] / sum[1]); } #ifdef LIBRAW_LIBRARY_BUILD static void remove_trailing_spaces(char *string, size_t len) { if (len < 1) return; // not needed, b/c sizeof of make/model is 64 string[len - 1] = 0; if (len < 3) return; // also not needed len = strnlen(string, len - 1); for (int i = len - 1; i >= 0; i--) { if (isspace(string[i])) string[i] = 0; else break; } } void CLASS initdata() { tiff_flip = flip = filters = UINT_MAX; /* unknown */ raw_height = raw_width = fuji_width = fuji_layout = cr2_slice[0] = 0; maximum = height = width = top_margin = left_margin = 0; cdesc[0] = desc[0] = artist[0] = make[0] = model[0] = model2[0] = 0; iso_speed = shutter = aperture = focal_len = unique_id = 0; tiff_nifds = 0; memset(tiff_ifd, 0, sizeof tiff_ifd); for (int i = 0; i < LIBRAW_IFD_MAXCOUNT; i++) { tiff_ifd[i].dng_color[0].illuminant = tiff_ifd[i].dng_color[1].illuminant = 0xffff; for (int c = 0; c < 4; c++) tiff_ifd[i].dng_levels.analogbalance[c] = 1.0f; } for (int i = 0; i < 0x10000; i++) curve[i] = i; memset(gpsdata, 0, sizeof gpsdata); memset(cblack, 0, sizeof cblack); memset(white, 0, sizeof white); memset(mask, 0, sizeof mask); thumb_offset = thumb_length = thumb_width = thumb_height = 0; load_raw = thumb_load_raw = 0; write_thumb = &CLASS jpeg_thumb; data_offset = meta_offset = meta_length = tiff_bps = tiff_compress = 0; kodak_cbpp = zero_after_ff = dng_version = load_flags = 0; timestamp = shot_order = tiff_samples = black = is_foveon = 0; mix_green = profile_length = data_error = zero_is_bad = 0; pixel_aspect = is_raw = raw_color = 1; tile_width = tile_length = 0; } #endif /* Identify which camera created this file, and set global variables accordingly. */ void CLASS identify() { static const short pana[][6] = { {3130, 1743, 4, 0, -6, 0}, {3130, 2055, 4, 0, -6, 0}, {3130, 2319, 4, 0, -6, 0}, {3170, 2103, 18, 0, -42, 20}, {3170, 2367, 18, 13, -42, -21}, {3177, 2367, 0, 0, -1, 0}, {3304, 2458, 0, 0, -1, 0}, {3330, 2463, 9, 0, -5, 0}, {3330, 2479, 9, 0, -17, 4}, {3370, 1899, 15, 0, -44, 20}, {3370, 2235, 15, 0, -44, 20}, {3370, 2511, 15, 10, -44, -21}, {3690, 2751, 3, 0, -8, -3}, {3710, 2751, 0, 0, -3, 0}, {3724, 2450, 0, 0, 0, -2}, {3770, 2487, 17, 0, -44, 19}, {3770, 2799, 17, 15, -44, -19}, {3880, 2170, 6, 0, -6, 0}, {4060, 3018, 0, 0, 0, -2}, {4290, 2391, 3, 0, -8, -1}, {4330, 2439, 17, 15, -44, -19}, {4508, 2962, 0, 0, -3, -4}, {4508, 3330, 0, 0, -3, -6}, }; static const ushort canon[][11] = { {1944, 1416, 0, 0, 48, 0}, {2144, 1560, 4, 8, 52, 2, 0, 0, 0, 25}, {2224, 1456, 48, 6, 0, 2}, {2376, 1728, 12, 6, 52, 2}, {2672, 1968, 12, 6, 44, 2}, {3152, 2068, 64, 12, 0, 0, 16}, {3160, 2344, 44, 12, 4, 4}, {3344, 2484, 4, 6, 52, 6}, {3516, 2328, 42, 14, 0, 0}, {3596, 2360, 74, 12, 0, 0}, {3744, 2784, 52, 12, 8, 12}, {3944, 2622, 30, 18, 6, 2}, {3948, 2622, 42, 18, 0, 2}, {3984, 2622, 76, 20, 0, 2, 14}, {4104, 3048, 48, 12, 24, 12}, {4116, 2178, 4, 2, 0, 0}, {4152, 2772, 192, 12, 0, 0}, {4160, 3124, 104, 11, 8, 65}, {4176, 3062, 96, 17, 8, 0, 0, 16, 0, 7, 0x49}, {4192, 3062, 96, 17, 24, 0, 0, 16, 0, 0, 0x49}, {4312, 2876, 22, 18, 0, 2}, {4352, 2874, 62, 18, 0, 0}, {4476, 2954, 90, 34, 0, 0}, {4480, 3348, 12, 10, 36, 12, 0, 0, 0, 18, 0x49}, {4480, 3366, 80, 50, 0, 0}, {4496, 3366, 80, 50, 12, 0}, {4768, 3516, 96, 16, 0, 0, 0, 16}, {4832, 3204, 62, 26, 0, 0}, {4832, 3228, 62, 51, 0, 0}, {5108, 3349, 98, 13, 0, 0}, {5120, 3318, 142, 45, 62, 0}, {5280, 3528, 72, 52, 0, 0}, /* EOS M */ {5344, 3516, 142, 51, 0, 0}, {5344, 3584, 126, 100, 0, 2}, {5360, 3516, 158, 51, 0, 0}, {5568, 3708, 72, 38, 0, 0}, {5632, 3710, 96, 17, 0, 0, 0, 16, 0, 0, 0x49}, {5712, 3774, 62, 20, 10, 2}, {5792, 3804, 158, 51, 0, 0}, {5920, 3950, 122, 80, 2, 0}, {6096, 4056, 72, 34, 0, 0}, /* EOS M3 */ {6288, 4056, 266, 36, 0, 0}, /* EOS 80D */ {6384, 4224, 120, 44, 0, 0}, /* 6D II */ {6880, 4544, 136, 42, 0, 0}, /* EOS 5D4 */ {8896, 5920, 160, 64, 0, 0}, }; static const struct { ushort id; char t_model[20]; } unique[] = { {0x001, "EOS-1D"}, {0x167, "EOS-1DS"}, {0x168, "EOS 10D"}, {0x169, "EOS-1D Mark III"}, {0x170, "EOS 300D"}, {0x174, "EOS-1D Mark II"}, {0x175, "EOS 20D"}, {0x176, "EOS 450D"}, {0x188, "EOS-1Ds Mark II"}, {0x189, "EOS 350D"}, {0x190, "EOS 40D"}, {0x213, "EOS 5D"}, {0x215, "EOS-1Ds Mark III"}, {0x218, "EOS 5D Mark II"}, {0x232, "EOS-1D Mark II N"}, {0x234, "EOS 30D"}, {0x236, "EOS 400D"}, {0x250, "EOS 7D"}, {0x252, "EOS 500D"}, {0x254, "EOS 1000D"}, {0x261, "EOS 50D"}, {0x269, "EOS-1D X"}, {0x270, "EOS 550D"}, {0x281, "EOS-1D Mark IV"}, {0x285, "EOS 5D Mark III"}, {0x286, "EOS 600D"}, {0x287, "EOS 60D"}, {0x288, "EOS 1100D"}, {0x289, "EOS 7D Mark II"}, {0x301, "EOS 650D"}, {0x302, "EOS 6D"}, {0x324, "EOS-1D C"}, {0x325, "EOS 70D"}, {0x326, "EOS 700D"}, {0x327, "EOS 1200D"}, {0x328, "EOS-1D X Mark II"}, {0x331, "EOS M"}, {0x335, "EOS M2"}, {0x374, "EOS M3"}, /* temp */ {0x384, "EOS M10"}, /* temp */ {0x394, "EOS M5"}, /* temp */ {0x346, "EOS 100D"}, {0x347, "EOS 760D"}, {0x349, "EOS 5D Mark IV"}, {0x350, "EOS 80D"}, {0x382, "EOS 5DS"}, {0x393, "EOS 750D"}, {0x401, "EOS 5DS R"}, {0x404, "EOS 1300D"}, {0x405, "EOS 800D"}, {0x406, "EOS 6D Mark II"}, {0x407, "EOS M6"}, {0x408, "EOS 77D"}, {0x417, "EOS 200D"}, }, sonique[] = { {0x002, "DSC-R1"}, {0x100, "DSLR-A100"}, {0x101, "DSLR-A900"}, {0x102, "DSLR-A700"}, {0x103, "DSLR-A200"}, {0x104, "DSLR-A350"}, {0x105, "DSLR-A300"}, {0x106, "DSLR-A900"}, {0x107, "DSLR-A380"}, {0x108, "DSLR-A330"}, {0x109, "DSLR-A230"}, {0x10a, "DSLR-A290"}, {0x10d, "DSLR-A850"}, {0x10e, "DSLR-A850"}, {0x111, "DSLR-A550"}, {0x112, "DSLR-A500"}, {0x113, "DSLR-A450"}, {0x116, "NEX-5"}, {0x117, "NEX-3"}, {0x118, "SLT-A33"}, {0x119, "SLT-A55V"}, {0x11a, "DSLR-A560"}, {0x11b, "DSLR-A580"}, {0x11c, "NEX-C3"}, {0x11d, "SLT-A35"}, {0x11e, "SLT-A65V"}, {0x11f, "SLT-A77V"}, {0x120, "NEX-5N"}, {0x121, "NEX-7"}, {0x122, "NEX-VG20E"}, {0x123, "SLT-A37"}, {0x124, "SLT-A57"}, {0x125, "NEX-F3"}, {0x126, "SLT-A99V"}, {0x127, "NEX-6"}, {0x128, "NEX-5R"}, {0x129, "DSC-RX100"}, {0x12a, "DSC-RX1"}, {0x12b, "NEX-VG900"}, {0x12c, "NEX-VG30E"}, {0x12e, "ILCE-3000"}, {0x12f, "SLT-A58"}, {0x131, "NEX-3N"}, {0x132, "ILCE-7"}, {0x133, "NEX-5T"}, {0x134, "DSC-RX100M2"}, {0x135, "DSC-RX10"}, {0x136, "DSC-RX1R"}, {0x137, "ILCE-7R"}, {0x138, "ILCE-6000"}, {0x139, "ILCE-5000"}, {0x13d, "DSC-RX100M3"}, {0x13e, "ILCE-7S"}, {0x13f, "ILCA-77M2"}, {0x153, "ILCE-5100"}, {0x154, "ILCE-7M2"}, {0x155, "DSC-RX100M4"}, {0x156, "DSC-RX10M2"}, {0x158, "DSC-RX1RM2"}, {0x15a, "ILCE-QX1"}, {0x15b, "ILCE-7RM2"}, {0x15e, "ILCE-7SM2"}, {0x161, "ILCA-68"}, {0x162, "ILCA-99M2"}, {0x163, "DSC-RX10M3"}, {0x164, "DSC-RX100M5"}, {0x165, "ILCE-6300"}, {0x166, "ILCE-9"}, {0x168, "ILCE-6500"}, }; #ifdef LIBRAW_LIBRARY_BUILD static const libraw_custom_camera_t const_table[] #else static const struct { unsigned fsize; ushort rw, rh; uchar lm, tm, rm, bm, lf, cf, max, flags; char t_make[10], t_model[20]; ushort offset; } table[] #endif = { {786432, 1024, 768, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-080C"}, {1447680, 1392, 1040, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-145C"}, {1920000, 1600, 1200, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-201C"}, {5067304, 2588, 1958, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-510C"}, {5067316, 2588, 1958, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-510C", 12}, {10134608, 2588, 1958, 0, 0, 0, 0, 9, 0x94, 0, 0, "AVT", "F-510C"}, {10134620, 2588, 1958, 0, 0, 0, 0, 9, 0x94, 0, 0, "AVT", "F-510C", 12}, {16157136, 3272, 2469, 0, 0, 0, 0, 9, 0x94, 0, 0, "AVT", "F-810C"}, {15980544, 3264, 2448, 0, 0, 0, 0, 8, 0x61, 0, 1, "AgfaPhoto", "DC-833m"}, {9631728, 2532, 1902, 0, 0, 0, 0, 96, 0x61, 0, 0, "Alcatel", "5035D"}, {31850496, 4608, 3456, 0, 0, 0, 0, 0, 0x94, 0, 0, "GITUP", "GIT2 4:3"}, {23887872, 4608, 2592, 0, 0, 0, 0, 0, 0x94, 0, 0, "GITUP", "GIT2 16:9"}, {32257024, 4624, 3488, 8, 2, 16, 2, 0, 0x94, 0, 0, "GITUP", "GIT2P 4:3"}, // Android Raw dumps id start // File Size in bytes Horizontal Res Vertical Flag then bayer order eg 0x16 bbgr 0x94 rggb {1540857, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "Samsung", "S3"}, {2658304, 1212, 1096, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3FrontMipi"}, {2842624, 1296, 1096, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3FrontQCOM"}, {2969600, 1976, 1200, 0, 0, 0, 0, 1, 0x16, 0, 0, "Xiaomi", "MI3wMipi"}, {3170304, 1976, 1200, 0, 0, 0, 0, 1, 0x16, 0, 0, "Xiaomi", "MI3wQCOM"}, {3763584, 1584, 1184, 0, 0, 0, 0, 96, 0x61, 0, 0, "I_Mobile", "I_StyleQ6"}, {5107712, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "UltraPixel1"}, {5382640, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "UltraPixel2"}, {5664912, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "4688"}, {5664912, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "4688"}, {5364240, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "4688"}, {6299648, 2592, 1944, 0, 0, 0, 0, 1, 0x16, 0, 0, "OmniVisi", "OV5648"}, {6721536, 2592, 1944, 0, 0, 0, 0, 0, 0x16, 0, 0, "OmniVisi", "OV56482"}, {6746112, 2592, 1944, 0, 0, 0, 0, 0, 0x16, 0, 0, "HTC", "OneSV"}, {9631728, 2532, 1902, 0, 0, 0, 0, 96, 0x61, 0, 0, "Sony", "5mp"}, {9830400, 2560, 1920, 0, 0, 0, 0, 96, 0x61, 0, 0, "NGM", "ForwardArt"}, {10186752, 3264, 2448, 0, 0, 0, 0, 1, 0x94, 0, 0, "Sony", "IMX219-mipi 8mp"}, {10223360, 2608, 1944, 0, 0, 0, 0, 96, 0x16, 0, 0, "Sony", "IMX"}, {10782464, 3282, 2448, 0, 0, 0, 0, 0, 0x16, 0, 0, "HTC", "MyTouch4GSlide"}, {10788864, 3282, 2448, 0, 0, 0, 0, 0, 0x16, 0, 0, "Xperia", "L"}, {15967488, 3264, 2446, 0, 0, 0, 0, 96, 0x16, 0, 0, "OmniVison", "OV8850"}, {16224256, 4208, 3082, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3MipiL"}, {16424960, 4208, 3120, 0, 0, 0, 0, 1, 0x16, 0, 0, "IMX135", "MipiL"}, {17326080, 4164, 3120, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3LQCom"}, {17522688, 4212, 3120, 0, 0, 0, 0, 0, 0x16, 0, 0, "Sony", "IMX135-QCOM"}, {19906560, 4608, 3456, 0, 0, 0, 0, 1, 0x16, 0, 0, "Gione", "E7mipi"}, {19976192, 5312, 2988, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G4"}, {20389888, 4632, 3480, 0, 0, 0, 0, 1, 0x16, 0, 0, "Xiaomi", "RedmiNote3Pro"}, {20500480, 4656, 3496, 0, 0, 0, 0, 1, 0x94, 0, 0, "Sony", "IMX298-mipi 16mp"}, {21233664, 4608, 3456, 0, 0, 0, 0, 1, 0x16, 0, 0, "Gione", "E7qcom"}, {26023936, 4192, 3104, 0, 0, 0, 0, 96, 0x94, 0, 0, "THL", "5000"}, {26257920, 4208, 3120, 0, 0, 0, 0, 96, 0x94, 0, 0, "Sony", "IMX214"}, {26357760, 4224, 3120, 0, 0, 0, 0, 96, 0x61, 0, 0, "OV", "13860"}, {41312256, 5248, 3936, 0, 0, 0, 0, 96, 0x61, 0, 0, "Meizu", "MX4"}, {42923008, 5344, 4016, 0, 0, 0, 0, 96, 0x61, 0, 0, "Sony", "IMX230"}, // Android Raw dumps id end {20137344, 3664, 2748, 0, 0, 0, 0, 0x40, 0x49, 0, 0, "Aptina", "MT9J003", 0xffff}, {2868726, 1384, 1036, 0, 0, 0, 0, 64, 0x49, 0, 8, "Baumer", "TXG14", 1078}, {5298000, 2400, 1766, 12, 12, 44, 2, 40, 0x94, 0, 2, "Canon", "PowerShot SD300"}, {6553440, 2664, 1968, 4, 4, 44, 4, 40, 0x94, 0, 2, "Canon", "PowerShot A460"}, {6573120, 2672, 1968, 12, 8, 44, 0, 40, 0x94, 0, 2, "Canon", "PowerShot A610"}, {6653280, 2672, 1992, 10, 6, 42, 2, 40, 0x94, 0, 2, "Canon", "PowerShot A530"}, {7710960, 2888, 2136, 44, 8, 4, 0, 40, 0x94, 0, 2, "Canon", "PowerShot S3 IS"}, {9219600, 3152, 2340, 36, 12, 4, 0, 40, 0x94, 0, 2, "Canon", "PowerShot A620"}, {9243240, 3152, 2346, 12, 7, 44, 13, 40, 0x49, 0, 2, "Canon", "PowerShot A470"}, {10341600, 3336, 2480, 6, 5, 32, 3, 40, 0x94, 0, 2, "Canon", "PowerShot A720 IS"}, {10383120, 3344, 2484, 12, 6, 44, 6, 40, 0x94, 0, 2, "Canon", "PowerShot A630"}, {12945240, 3736, 2772, 12, 6, 52, 6, 40, 0x94, 0, 2, "Canon", "PowerShot A640"}, {15636240, 4104, 3048, 48, 12, 24, 12, 40, 0x94, 0, 2, "Canon", "PowerShot A650"}, {15467760, 3720, 2772, 6, 12, 30, 0, 40, 0x94, 0, 2, "Canon", "PowerShot SX110 IS"}, {15534576, 3728, 2778, 12, 9, 44, 9, 40, 0x94, 0, 2, "Canon", "PowerShot SX120 IS"}, {18653760, 4080, 3048, 24, 12, 24, 12, 40, 0x94, 0, 2, "Canon", "PowerShot SX20 IS"}, {18763488, 4104, 3048, 10, 22, 82, 22, 8, 0x49, 0, 0, "Canon", "PowerShot D10"}, {19131120, 4168, 3060, 92, 16, 4, 1, 40, 0x94, 0, 2, "Canon", "PowerShot SX220 HS"}, {21936096, 4464, 3276, 25, 10, 73, 12, 40, 0x16, 0, 2, "Canon", "PowerShot SX30 IS"}, {24724224, 4704, 3504, 8, 16, 56, 8, 40, 0x49, 0, 2, "Canon", "PowerShot A3300 IS"}, {30858240, 5248, 3920, 8, 16, 56, 16, 40, 0x94, 0, 2, "Canon", "IXUS 160"}, {1976352, 1632, 1211, 0, 2, 0, 1, 0, 0x94, 0, 1, "Casio", "QV-2000UX"}, {3217760, 2080, 1547, 0, 0, 10, 1, 0, 0x94, 0, 1, "Casio", "QV-3*00EX"}, {6218368, 2585, 1924, 0, 0, 9, 0, 0, 0x94, 0, 1, "Casio", "QV-5700"}, {7816704, 2867, 2181, 0, 0, 34, 36, 0, 0x16, 0, 1, "Casio", "EX-Z60"}, {2937856, 1621, 1208, 0, 0, 1, 0, 0, 0x94, 7, 13, "Casio", "EX-S20"}, {4948608, 2090, 1578, 0, 0, 32, 34, 0, 0x94, 7, 1, "Casio", "EX-S100"}, {6054400, 2346, 1720, 2, 0, 32, 0, 0, 0x94, 7, 1, "Casio", "QV-R41"}, {7426656, 2568, 1928, 0, 0, 0, 0, 0, 0x94, 0, 1, "Casio", "EX-P505"}, {7530816, 2602, 1929, 0, 0, 22, 0, 0, 0x94, 7, 1, "Casio", "QV-R51"}, {7542528, 2602, 1932, 0, 0, 32, 0, 0, 0x94, 7, 1, "Casio", "EX-Z50"}, {7562048, 2602, 1937, 0, 0, 25, 0, 0, 0x16, 7, 1, "Casio", "EX-Z500"}, {7753344, 2602, 1986, 0, 0, 32, 26, 0, 0x94, 7, 1, "Casio", "EX-Z55"}, {9313536, 2858, 2172, 0, 0, 14, 30, 0, 0x94, 7, 1, "Casio", "EX-P600"}, {10834368, 3114, 2319, 0, 0, 27, 0, 0, 0x94, 0, 1, "Casio", "EX-Z750"}, {10843712, 3114, 2321, 0, 0, 25, 0, 0, 0x94, 0, 1, "Casio", "EX-Z75"}, {10979200, 3114, 2350, 0, 0, 32, 32, 0, 0x94, 7, 1, "Casio", "EX-P700"}, {12310144, 3285, 2498, 0, 0, 6, 30, 0, 0x94, 0, 1, "Casio", "EX-Z850"}, {12489984, 3328, 2502, 0, 0, 47, 35, 0, 0x94, 0, 1, "Casio", "EX-Z8"}, {15499264, 3754, 2752, 0, 0, 82, 0, 0, 0x94, 0, 1, "Casio", "EX-Z1050"}, {18702336, 4096, 3044, 0, 0, 24, 0, 80, 0x94, 7, 1, "Casio", "EX-ZR100"}, {7684000, 2260, 1700, 0, 0, 0, 0, 13, 0x94, 0, 1, "Casio", "QV-4000"}, {787456, 1024, 769, 0, 1, 0, 0, 0, 0x49, 0, 0, "Creative", "PC-CAM 600"}, {28829184, 4384, 3288, 0, 0, 0, 0, 36, 0x61, 0, 0, "DJI"}, {15151104, 4608, 3288, 0, 0, 0, 0, 0, 0x94, 0, 0, "Matrix"}, {3840000, 1600, 1200, 0, 0, 0, 0, 65, 0x49, 0, 0, "Foculus", "531C"}, {307200, 640, 480, 0, 0, 0, 0, 0, 0x94, 0, 0, "Generic"}, {62464, 256, 244, 1, 1, 6, 1, 0, 0x8d, 0, 0, "Kodak", "DC20"}, {124928, 512, 244, 1, 1, 10, 1, 0, 0x8d, 0, 0, "Kodak", "DC20"}, {1652736, 1536, 1076, 0, 52, 0, 0, 0, 0x61, 0, 0, "Kodak", "DCS200"}, {4159302, 2338, 1779, 1, 33, 1, 2, 0, 0x94, 0, 0, "Kodak", "C330"}, {4162462, 2338, 1779, 1, 33, 1, 2, 0, 0x94, 0, 0, "Kodak", "C330", 3160}, {2247168, 1232, 912, 0, 0, 16, 0, 0, 0x00, 0, 0, "Kodak", "C330"}, {3370752, 1232, 912, 0, 0, 16, 0, 0, 0x00, 0, 0, "Kodak", "C330"}, {6163328, 2864, 2152, 0, 0, 0, 0, 0, 0x94, 0, 0, "Kodak", "C603"}, {6166488, 2864, 2152, 0, 0, 0, 0, 0, 0x94, 0, 0, "Kodak", "C603", 3160}, {460800, 640, 480, 0, 0, 0, 0, 0, 0x00, 0, 0, "Kodak", "C603"}, {9116448, 2848, 2134, 0, 0, 0, 0, 0, 0x00, 0, 0, "Kodak", "C603"}, {12241200, 4040, 3030, 2, 0, 0, 13, 0, 0x49, 0, 0, "Kodak", "12MP"}, {12272756, 4040, 3030, 2, 0, 0, 13, 0, 0x49, 0, 0, "Kodak", "12MP", 31556}, {18000000, 4000, 3000, 0, 0, 0, 0, 0, 0x00, 0, 0, "Kodak", "12MP"}, {614400, 640, 480, 0, 3, 0, 0, 64, 0x94, 0, 0, "Kodak", "KAI-0340"}, {15360000, 3200, 2400, 0, 0, 0, 0, 96, 0x16, 0, 0, "Lenovo", "A820"}, {3884928, 1608, 1207, 0, 0, 0, 0, 96, 0x16, 0, 0, "Micron", "2010", 3212}, {1138688, 1534, 986, 0, 0, 0, 0, 0, 0x61, 0, 0, "Minolta", "RD175", 513}, {1581060, 1305, 969, 0, 0, 18, 6, 6, 0x1e, 4, 1, "Nikon", "E900"}, {2465792, 1638, 1204, 0, 0, 22, 1, 6, 0x4b, 5, 1, "Nikon", "E950"}, {2940928, 1616, 1213, 0, 0, 0, 7, 30, 0x94, 0, 1, "Nikon", "E2100"}, {4771840, 2064, 1541, 0, 0, 0, 1, 6, 0xe1, 0, 1, "Nikon", "E990"}, {4775936, 2064, 1542, 0, 0, 0, 0, 30, 0x94, 0, 1, "Nikon", "E3700"}, {5865472, 2288, 1709, 0, 0, 0, 1, 6, 0xb4, 0, 1, "Nikon", "E4500"}, {5869568, 2288, 1710, 0, 0, 0, 0, 6, 0x16, 0, 1, "Nikon", "E4300"}, {7438336, 2576, 1925, 0, 0, 0, 1, 6, 0xb4, 0, 1, "Nikon", "E5000"}, {8998912, 2832, 2118, 0, 0, 0, 0, 30, 0x94, 7, 1, "Nikon", "COOLPIX S6"}, {5939200, 2304, 1718, 0, 0, 0, 0, 30, 0x16, 0, 0, "Olympus", "C770UZ"}, {3178560, 2064, 1540, 0, 0, 0, 0, 0, 0x94, 0, 1, "Pentax", "Optio S"}, {4841984, 2090, 1544, 0, 0, 22, 0, 0, 0x94, 7, 1, "Pentax", "Optio S"}, {6114240, 2346, 1737, 0, 0, 22, 0, 0, 0x94, 7, 1, "Pentax", "Optio S4"}, {10702848, 3072, 2322, 0, 0, 0, 21, 30, 0x94, 0, 1, "Pentax", "Optio 750Z"}, {4147200, 1920, 1080, 0, 0, 0, 0, 0, 0x49, 0, 0, "Photron", "BC2-HD"}, {4151666, 1920, 1080, 0, 0, 0, 0, 0, 0x49, 0, 0, "Photron", "BC2-HD", 8}, {13248000, 2208, 3000, 0, 0, 0, 0, 13, 0x61, 0, 0, "Pixelink", "A782"}, {6291456, 2048, 1536, 0, 0, 0, 0, 96, 0x61, 0, 0, "RoverShot", "3320AF"}, {311696, 644, 484, 0, 0, 0, 0, 0, 0x16, 0, 8, "ST Micro", "STV680 VGA"}, {16098048, 3288, 2448, 0, 0, 24, 0, 9, 0x94, 0, 1, "Samsung", "S85"}, {16215552, 3312, 2448, 0, 0, 48, 0, 9, 0x94, 0, 1, "Samsung", "S85"}, {20487168, 3648, 2808, 0, 0, 0, 0, 13, 0x94, 5, 1, "Samsung", "WB550"}, {24000000, 4000, 3000, 0, 0, 0, 0, 13, 0x94, 5, 1, "Samsung", "WB550"}, {12582980, 3072, 2048, 0, 0, 0, 0, 33, 0x61, 0, 0, "Sinar", "", 68}, {33292868, 4080, 4080, 0, 0, 0, 0, 33, 0x61, 0, 0, "Sinar", "", 68}, {44390468, 4080, 5440, 0, 0, 0, 0, 33, 0x61, 0, 0, "Sinar", "", 68}, {1409024, 1376, 1024, 0, 0, 1, 0, 0, 0x49, 0, 0, "Sony", "XCD-SX910CR"}, {2818048, 1376, 1024, 0, 0, 1, 0, 97, 0x49, 0, 0, "Sony", "XCD-SX910CR"}, }; #ifdef LIBRAW_LIBRARY_BUILD libraw_custom_camera_t table[64 + sizeof(const_table) / sizeof(const_table[0])]; #endif static const char *corp[] = {"AgfaPhoto", "Canon", "Casio", "Epson", "Fujifilm", "Mamiya", "Minolta", "Motorola", "Kodak", "Konica", "Leica", "Nikon", "Nokia", "Olympus", "Pentax", "Phase One", "Ricoh", "Samsung", "Sigma", "Sinar", "Sony"}; #ifdef LIBRAW_LIBRARY_BUILD char head[64], *cp; #else char head[32], *cp; #endif int hlen, flen, fsize, zero_fsize = 1, i, c; struct jhead jh; #ifdef LIBRAW_LIBRARY_BUILD unsigned camera_count = parse_custom_cameras(64, table, imgdata.params.custom_camera_strings); for (int q = 0; q < sizeof(const_table) / sizeof(const_table[0]); q++) memmove(&table[q + camera_count], &const_table[q], sizeof(const_table[0])); camera_count += sizeof(const_table) / sizeof(const_table[0]); #endif tiff_flip = flip = filters = UINT_MAX; /* unknown */ raw_height = raw_width = fuji_width = fuji_layout = cr2_slice[0] = 0; maximum = height = width = top_margin = left_margin = 0; cdesc[0] = desc[0] = artist[0] = make[0] = model[0] = model2[0] = 0; iso_speed = shutter = aperture = focal_len = unique_id = 0; tiff_nifds = 0; memset(tiff_ifd, 0, sizeof tiff_ifd); #ifdef LIBRAW_LIBRARY_BUILD for (i = 0; i < LIBRAW_IFD_MAXCOUNT; i++) { tiff_ifd[i].dng_color[0].illuminant = tiff_ifd[i].dng_color[1].illuminant = 0xffff; for (int c = 0; c < 4; c++) tiff_ifd[i].dng_levels.analogbalance[c] = 1.0f; } #endif memset(gpsdata, 0, sizeof gpsdata); memset(cblack, 0, sizeof cblack); memset(white, 0, sizeof white); memset(mask, 0, sizeof mask); thumb_offset = thumb_length = thumb_width = thumb_height = 0; load_raw = thumb_load_raw = 0; write_thumb = &CLASS jpeg_thumb; data_offset = meta_offset = meta_length = tiff_bps = tiff_compress = 0; kodak_cbpp = zero_after_ff = dng_version = load_flags = 0; timestamp = shot_order = tiff_samples = black = is_foveon = 0; mix_green = profile_length = data_error = zero_is_bad = 0; pixel_aspect = is_raw = raw_color = 1; tile_width = tile_length = 0; for (i = 0; i < 4; i++) { cam_mul[i] = i == 1; pre_mul[i] = i < 3; FORC3 cmatrix[c][i] = 0; FORC3 rgb_cam[c][i] = c == i; } colors = 3; for (i = 0; i < 0x10000; i++) curve[i] = i; order = get2(); hlen = get4(); fseek(ifp, 0, SEEK_SET); #ifdef LIBRAW_LIBRARY_BUILD fread(head, 1, 64, ifp); libraw_internal_data.unpacker_data.lenRAFData = libraw_internal_data.unpacker_data.posRAFData = 0; #else fread(head, 1, 32, ifp); #endif fseek(ifp, 0, SEEK_END); flen = fsize = ftell(ifp); if ((cp = (char *)memmem(head, 32, (char *)"MMMM", 4)) || (cp = (char *)memmem(head, 32, (char *)"IIII", 4))) { parse_phase_one(cp - head); if (cp - head && parse_tiff(0)) apply_tiff(); } else if (order == 0x4949 || order == 0x4d4d) { if (!memcmp(head + 6, "HEAPCCDR", 8)) { data_offset = hlen; #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; #endif parse_ciff(hlen, flen - hlen, 0); load_raw = &CLASS canon_load_raw; } else if (parse_tiff(0)) apply_tiff(); } else if (!memcmp(head, "\xff\xd8\xff\xe1", 4) && !memcmp(head + 6, "Exif", 4)) { fseek(ifp, 4, SEEK_SET); data_offset = 4 + get2(); fseek(ifp, data_offset, SEEK_SET); if (fgetc(ifp) != 0xff) parse_tiff(12); thumb_offset = 0; } else if (!memcmp(head + 25, "ARECOYK", 7)) { strcpy(make, "Contax"); strcpy(model, "N Digital"); fseek(ifp, 33, SEEK_SET); get_timestamp(1); fseek(ifp, 52, SEEK_SET); switch (get4()) { case 7: iso_speed = 25; break; case 8: iso_speed = 32; break; case 9: iso_speed = 40; break; case 10: iso_speed = 50; break; case 11: iso_speed = 64; break; case 12: iso_speed = 80; break; case 13: iso_speed = 100; break; case 14: iso_speed = 125; break; case 15: iso_speed = 160; break; case 16: iso_speed = 200; break; case 17: iso_speed = 250; break; case 18: iso_speed = 320; break; case 19: iso_speed = 400; break; } shutter = powf64(2.0f, (((float)get4()) / 8.0f)) / 16000.0f; FORC4 cam_mul[c ^ (c >> 1)] = get4(); fseek(ifp, 88, SEEK_SET); aperture = powf64(2.0f, ((float)get4()) / 16.0f); fseek(ifp, 112, SEEK_SET); focal_len = get4(); #ifdef LIBRAW_LIBRARY_BUILD fseek(ifp, 104, SEEK_SET); imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, ((float)get4()) / 16.0f); fseek(ifp, 124, SEEK_SET); stmread(imgdata.lens.makernotes.Lens, 32, ifp); imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Contax_N; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Contax_N; #endif } else if (!strcmp(head, "PXN")) { strcpy(make, "Logitech"); strcpy(model, "Fotoman Pixtura"); } else if (!strcmp(head, "qktk")) { strcpy(make, "Apple"); strcpy(model, "QuickTake 100"); load_raw = &CLASS quicktake_100_load_raw; } else if (!strcmp(head, "qktn")) { strcpy(make, "Apple"); strcpy(model, "QuickTake 150"); load_raw = &CLASS kodak_radc_load_raw; } else if (!memcmp(head, "FUJIFILM", 8)) { #ifdef LIBRAW_LIBRARY_BUILD strcpy(model, head + 0x1c); memcpy(model2, head + 0x3c, 4); model2[4] = 0; #endif fseek(ifp, 84, SEEK_SET); thumb_offset = get4(); thumb_length = get4(); fseek(ifp, 92, SEEK_SET); parse_fuji(get4()); if (thumb_offset > 120) { fseek(ifp, 120, SEEK_SET); is_raw += (i = get4()) ? 1 : 0; if (is_raw == 2 && shot_select) parse_fuji(i); } load_raw = &CLASS unpacked_load_raw; fseek(ifp, 100 + 28 * (shot_select > 0), SEEK_SET); parse_tiff(data_offset = get4()); parse_tiff(thumb_offset + 12); apply_tiff(); } else if (!memcmp(head, "RIFF", 4)) { fseek(ifp, 0, SEEK_SET); parse_riff(); } else if (!memcmp(head + 4, "ftypqt ", 9)) { fseek(ifp, 0, SEEK_SET); parse_qt(fsize); is_raw = 0; } else if (!memcmp(head, "\0\001\0\001\0@", 6)) { fseek(ifp, 6, SEEK_SET); fread(make, 1, 8, ifp); fread(model, 1, 8, ifp); fread(model2, 1, 16, ifp); data_offset = get2(); get2(); raw_width = get2(); raw_height = get2(); load_raw = &CLASS nokia_load_raw; filters = 0x61616161; } else if (!memcmp(head, "NOKIARAW", 8)) { strcpy(make, "NOKIA"); order = 0x4949; fseek(ifp, 300, SEEK_SET); data_offset = get4(); i = get4(); width = get2(); height = get2(); switch (tiff_bps = i * 8 / (width * height)) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 10: load_raw = &CLASS nokia_load_raw; } raw_height = height + (top_margin = i / (width * tiff_bps / 8) - height); mask[0][3] = 1; filters = 0x61616161; } else if (!memcmp(head, "ARRI", 4)) { order = 0x4949; fseek(ifp, 20, SEEK_SET); width = get4(); height = get4(); strcpy(make, "ARRI"); fseek(ifp, 668, SEEK_SET); fread(model, 1, 64, ifp); data_offset = 4096; load_raw = &CLASS packed_load_raw; load_flags = 88; filters = 0x61616161; } else if (!memcmp(head, "XPDS", 4)) { order = 0x4949; fseek(ifp, 0x800, SEEK_SET); fread(make, 1, 41, ifp); raw_height = get2(); raw_width = get2(); fseek(ifp, 56, SEEK_CUR); fread(model, 1, 30, ifp); data_offset = 0x10000; load_raw = &CLASS canon_rmf_load_raw; gamma_curve(0, 12.25, 1, 1023); } else if (!memcmp(head + 4, "RED1", 4)) { strcpy(make, "Red"); strcpy(model, "One"); parse_redcine(); load_raw = &CLASS redcine_load_raw; gamma_curve(1 / 2.4, 12.92, 1, 4095); filters = 0x49494949; } else if (!memcmp(head, "DSC-Image", 9)) parse_rollei(); else if (!memcmp(head, "PWAD", 4)) parse_sinar_ia(); else if (!memcmp(head, "\0MRM", 4)) parse_minolta(0); else if (!memcmp(head, "FOVb", 4)) { #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_DEMOSAIC_PACK_GPL2 if (!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_FORCE_FOVEON_X3F)) parse_foveon(); else #endif parse_x3f(); #else #ifdef LIBRAW_DEMOSAIC_PACK_GPL2 parse_foveon(); #endif #endif } else if (!memcmp(head, "CI", 2)) parse_cine(); if (make[0] == 0) #ifdef LIBRAW_LIBRARY_BUILD for (zero_fsize = i = 0; i < camera_count; i++) #else for (zero_fsize = i = 0; i < sizeof table / sizeof *table; i++) #endif if (fsize == table[i].fsize) { strcpy(make, table[i].t_make); #ifdef LIBRAW_LIBRARY_BUILD if (!strncmp(make, "Canon", 5)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } #endif strcpy(model, table[i].t_model); flip = table[i].flags >> 2; zero_is_bad = table[i].flags & 2; if (table[i].flags & 1) parse_external_jpeg(); data_offset = table[i].offset == 0xffff ? 0 : table[i].offset; raw_width = table[i].rw; raw_height = table[i].rh; left_margin = table[i].lm; top_margin = table[i].tm; width = raw_width - left_margin - table[i].rm; height = raw_height - top_margin - table[i].bm; filters = 0x1010101 * table[i].cf; colors = 4 - !((filters & filters >> 1) & 0x5555); load_flags = table[i].lf; switch (tiff_bps = (fsize - data_offset) * 8 / (raw_width * raw_height)) { case 6: load_raw = &CLASS minolta_rd175_load_raw; break; case 8: load_raw = &CLASS eight_bit_load_raw; break; case 10: if ((fsize - data_offset) / raw_height * 3 >= raw_width * 4) { load_raw = &CLASS android_loose_load_raw; break; } else if (load_flags & 1) { load_raw = &CLASS android_tight_load_raw; break; } case 12: load_flags |= 128; load_raw = &CLASS packed_load_raw; break; case 16: order = 0x4949 | 0x404 * (load_flags & 1); tiff_bps -= load_flags >> 4; tiff_bps -= load_flags = load_flags >> 1 & 7; load_raw = table[i].offset == 0xffff ? &CLASS unpacked_load_raw_reversed : &CLASS unpacked_load_raw; } maximum = (1 << tiff_bps) - (1 << table[i].max); } if (zero_fsize) fsize = 0; if (make[0] == 0) parse_smal(0, flen); if (make[0] == 0) { parse_jpeg(0); fseek(ifp, 0, SEEK_END); int sz = ftell(ifp); #ifdef LIBRAW_LIBRARY_BUILD if (!strncmp(model, "RP_imx219", 9) && sz >= 0x9cb600 && !fseek(ifp, -0x9cb600, SEEK_END) && fread(head, 1, 0x20, ifp) && !strncmp(head, "BRCM", 4)) { strcpy(make, "Broadcom"); strcpy(model, "RPi IMX219"); if (raw_height > raw_width) flip = 5; data_offset = ftell(ifp) + 0x8000 - 0x20; parse_broadcom(); black = 66; maximum = 0x3ff; load_raw = &CLASS broadcom_load_raw; thumb_offset = 0; thumb_length = sz - 0x9cb600 - 1; } else if (!(strncmp(model, "ov5647", 6) && strncmp(model, "RP_OV5647", 9)) && sz >= 0x61b800 && !fseek(ifp, -0x61b800, SEEK_END) && fread(head, 1, 0x20, ifp) && !strncmp(head, "BRCM", 4)) { strcpy(make, "Broadcom"); if (!strncmp(model, "ov5647", 6)) strcpy(model, "RPi OV5647 v.1"); else strcpy(model, "RPi OV5647 v.2"); if (raw_height > raw_width) flip = 5; data_offset = ftell(ifp) + 0x8000 - 0x20; parse_broadcom(); black = 16; maximum = 0x3ff; load_raw = &CLASS broadcom_load_raw; thumb_offset = 0; thumb_length = sz - 0x61b800 - 1; #else if (!(strncmp(model, "ov", 2) && strncmp(model, "RP_OV", 5)) && sz >= 6404096 && !fseek(ifp, -6404096, SEEK_END) && fread(head, 1, 32, ifp) && !strcmp(head, "BRCMn")) { strcpy(make, "OmniVision"); data_offset = ftell(ifp) + 0x8000 - 32; width = raw_width; raw_width = 2611; load_raw = &CLASS nokia_load_raw; filters = 0x16161616; #endif } else is_raw = 0; } #ifdef LIBRAW_LIBRARY_BUILD // make sure strings are terminated desc[511] = artist[63] = make[63] = model[63] = model2[63] = 0; #endif for (i = 0; i < sizeof corp / sizeof *corp; i++) if (strcasestr(make, corp[i])) /* Simplify company names */ strcpy(make, corp[i]); if ((!strncmp(make, "Kodak", 5) || !strncmp(make, "Leica", 5)) && ((cp = strcasestr(model, " DIGITAL CAMERA")) || (cp = strstr(model, "FILE VERSION")))) *cp = 0; if (!strncasecmp(model, "PENTAX", 6)) strcpy(make, "Pentax"); #ifdef LIBRAW_LIBRARY_BUILD remove_trailing_spaces(make, sizeof(make)); remove_trailing_spaces(model, sizeof(model)); #else cp = make + strlen(make); /* Remove trailing spaces */ while (*--cp == ' ') *cp = 0; cp = model + strlen(model); while (*--cp == ' ') *cp = 0; #endif i = strbuflen(make); /* Remove make from model */ if (!strncasecmp(model, make, i) && model[i++] == ' ') memmove(model, model + i, 64 - i); if (!strncmp(model, "FinePix ", 8)) strcpy(model, model + 8); if (!strncmp(model, "Digital Camera ", 15)) strcpy(model, model + 15); desc[511] = artist[63] = make[63] = model[63] = model2[63] = 0; if (!is_raw) goto notraw; if (!height) height = raw_height; if (!width) width = raw_width; if (height == 2624 && width == 3936) /* Pentax K10D and Samsung GX10 */ { height = 2616; width = 3896; } if (height == 3136 && width == 4864) /* Pentax K20D and Samsung GX20 */ { height = 3124; width = 4688; filters = 0x16161616; } if (width == 4352 && (!strcmp(model, "K-r") || !strcmp(model, "K-x"))) { width = 4309; filters = 0x16161616; } if (width >= 4960 && !strncmp(model, "K-5", 3)) { left_margin = 10; width = 4950; filters = 0x16161616; } if (width == 6080 && !strcmp(model, "K-70")) { height = 4016; top_margin = 32; width = 6020; left_margin = 60; } if (width == 4736 && !strcmp(model, "K-7")) { height = 3122; width = 4684; filters = 0x16161616; top_margin = 2; } if (width == 6080 && !strcmp(model, "K-3 II")) /* moved back */ { left_margin = 4; width = 6040; } if (width == 6112 && !strcmp(model, "KP")) { /* From DNG, maybe too strict */ left_margin = 54; top_margin = 28; width = 6028; height = raw_height - top_margin; } if (width == 6080 && !strcmp(model, "K-3")) { left_margin = 4; width = 6040; } if (width == 7424 && !strcmp(model, "645D")) { height = 5502; width = 7328; filters = 0x61616161; top_margin = 29; left_margin = 48; } if (height == 3014 && width == 4096) /* Ricoh GX200 */ width = 4014; if (dng_version) { if (filters == UINT_MAX) filters = 0; if (filters) is_raw *= tiff_samples; else colors = tiff_samples; switch (tiff_compress) { case 0: /* Compression not set, assuming uncompressed */ case 1: load_raw = &CLASS packed_dng_load_raw; break; case 7: load_raw = &CLASS lossless_dng_load_raw; break; #ifdef LIBRAW_LIBRARY_BUILD case 8: load_raw = &CLASS deflate_dng_load_raw; break; #endif case 34892: load_raw = &CLASS lossy_dng_load_raw; break; default: load_raw = 0; } if (!strncmp(make, "Canon", 5) && unique_id) { for (i = 0; i < sizeof unique / sizeof *unique; i++) if (unique_id == 0x80000000 + unique[i].id) { strcpy(model, unique[i].t_model); break; } } if (!strncasecmp(make, "Sony", 4) && unique_id) { for (i = 0; i < sizeof sonique / sizeof *sonique; i++) if (unique_id == sonique[i].id) { strcpy(model, sonique[i].t_model); break; } } goto dng_skip; } if (!strncmp(make, "Canon", 5) && !fsize && tiff_bps != 15) { if (!load_raw) load_raw = &CLASS lossless_jpeg_load_raw; for (i = 0; i < sizeof canon / sizeof *canon; i++) if (raw_width == canon[i][0] && raw_height == canon[i][1]) { width = raw_width - (left_margin = canon[i][2]); height = raw_height - (top_margin = canon[i][3]); width -= canon[i][4]; height -= canon[i][5]; mask[0][1] = canon[i][6]; mask[0][3] = -canon[i][7]; mask[1][1] = canon[i][8]; mask[1][3] = -canon[i][9]; if (canon[i][10]) filters = canon[i][10] * 0x01010101; } if ((unique_id | 0x20000) == 0x2720000) { left_margin = 8; top_margin = 16; } } if (!strncmp(make, "Canon", 5) && unique_id) { for (i = 0; i < sizeof unique / sizeof *unique; i++) if (unique_id == 0x80000000 + unique[i].id) { adobe_coeff("Canon", unique[i].t_model); strcpy(model, unique[i].t_model); } } if (!strncasecmp(make, "Sony", 4) && unique_id) { for (i = 0; i < sizeof sonique / sizeof *sonique; i++) if (unique_id == sonique[i].id) { adobe_coeff("Sony", sonique[i].t_model); strcpy(model, sonique[i].t_model); } } if (!strncmp(make, "Nikon", 5)) { if (!load_raw) load_raw = &CLASS packed_load_raw; if (model[0] == 'E') load_flags |= !data_offset << 2 | 2; } /* Set parameters based on camera name (for non-DNG files). */ if (!strcmp(model, "KAI-0340") && find_green(16, 16, 3840, 5120) < 25) { height = 480; top_margin = filters = 0; strcpy(model, "C603"); } #ifndef LIBRAW_LIBRARY_BUILD if (!strcmp(make, "Sony") && raw_width > 3888 && !black && !cblack[0]) black = 128 << (tiff_bps - 12); #else /* Always 512 for arw2_load_raw */ if (!strcmp(make, "Sony") && raw_width > 3888 && !black && !cblack[0]) black = (load_raw == &LibRaw::sony_arw2_load_raw) ? 512 : (128 << (tiff_bps - 12)); #endif if (is_foveon) { if (height * 2 < width) pixel_aspect = 0.5; if (height > width) pixel_aspect = 2; filters = 0; #ifdef LIBRAW_DEMOSAIC_PACK_GPL2 if (!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_FORCE_FOVEON_X3F)) simple_coeff(0); #endif } else if (!strncmp(make, "Pentax", 6) && !strncmp(model, "K-1", 3)) { top_margin = 18; height = raw_height - top_margin; if (raw_width == 7392) { left_margin = 6; width = 7376; } } else if (!strncmp(make, "Canon", 5) && tiff_bps == 15) { switch (width) { case 3344: width -= 66; case 3872: width -= 6; } if (height > width) { SWAP(height, width); SWAP(raw_height, raw_width); } if (width == 7200 && height == 3888) { raw_width = width = 6480; raw_height = height = 4320; } filters = 0; tiff_samples = colors = 3; load_raw = &CLASS canon_sraw_load_raw; } else if (!strcmp(model, "PowerShot 600")) { height = 613; width = 854; raw_width = 896; colors = 4; filters = 0xe1e4e1e4; load_raw = &CLASS canon_600_load_raw; } else if (!strcmp(model, "PowerShot A5") || !strcmp(model, "PowerShot A5 Zoom")) { height = 773; width = 960; raw_width = 992; pixel_aspect = 256 / 235.0; filters = 0x1e4e1e4e; goto canon_a5; } else if (!strcmp(model, "PowerShot A50")) { height = 968; width = 1290; raw_width = 1320; filters = 0x1b4e4b1e; goto canon_a5; } else if (!strcmp(model, "PowerShot Pro70")) { height = 1024; width = 1552; filters = 0x1e4b4e1b; canon_a5: colors = 4; tiff_bps = 10; load_raw = &CLASS packed_load_raw; load_flags = 40; } else if (!strcmp(model, "PowerShot Pro90 IS") || !strcmp(model, "PowerShot G1")) { colors = 4; filters = 0xb4b4b4b4; } else if (!strcmp(model, "PowerShot A610")) { if (canon_s2is()) strcpy(model + 10, "S2 IS"); } else if (!strcmp(model, "PowerShot SX220 HS")) { mask[1][3] = -4; top_margin = 16; left_margin = 92; } else if (!strcmp(model, "PowerShot S120")) { raw_width = 4192; raw_height = 3062; width = 4022; height = 3016; mask[0][0] = top_margin = 31; mask[0][2] = top_margin + height; left_margin = 120; mask[0][1] = 23; mask[0][3] = 72; } else if (!strcmp(model, "PowerShot G16")) { mask[0][0] = 0; mask[0][2] = 80; mask[0][1] = 0; mask[0][3] = 16; top_margin = 29; left_margin = 120; width = raw_width - left_margin - 48; height = raw_height - top_margin - 14; } else if (!strcmp(model, "PowerShot SX50 HS")) { top_margin = 17; } else if (!strcmp(model, "EOS D2000C")) { filters = 0x61616161; if (!black) black = curve[200]; } else if (!strcmp(model, "D1")) { cam_mul[0] *= 256 / 527.0; cam_mul[2] *= 256 / 317.0; } else if (!strcmp(model, "D1X")) { width -= 4; pixel_aspect = 0.5; } else if (!strcmp(model, "D40X") || !strcmp(model, "D60") || !strcmp(model, "D80") || !strcmp(model, "D3000")) { height -= 3; width -= 4; } else if (!strcmp(model, "D3") || !strcmp(model, "D3S") || !strcmp(model, "D700")) { width -= 4; left_margin = 2; } else if (!strcmp(model, "D3100")) { width -= 28; left_margin = 6; } else if (!strcmp(model, "D5000") || !strcmp(model, "D90")) { width -= 42; } else if (!strcmp(model, "D5100") || !strcmp(model, "D7000") || !strcmp(model, "COOLPIX A")) { width -= 44; } else if (!strcmp(model, "D3200") || !strncmp(model, "D6", 2) || !strncmp(model, "D800", 4)) { width -= 46; } else if (!strcmp(model, "D4") || !strcmp(model, "Df")) { width -= 52; left_margin = 2; } else if (!strcmp(model, "D500")) { // Empty - to avoid width-1 below } else if (!strncmp(model, "D40", 3) || !strncmp(model, "D50", 3) || !strncmp(model, "D70", 3)) { width--; } else if (!strcmp(model, "D100")) { if (load_flags) raw_width = (width += 3) + 3; } else if (!strcmp(model, "D200")) { left_margin = 1; width -= 4; filters = 0x94949494; } else if (!strncmp(model, "D2H", 3)) { left_margin = 6; width -= 14; } else if (!strncmp(model, "D2X", 3)) { if (width == 3264) width -= 32; else width -= 8; } else if (!strncmp(model, "D300", 4)) { width -= 32; } else if (!strncmp(make, "Nikon", 5) && raw_width == 4032) { if (!strcmp(model, "COOLPIX P7700")) { adobe_coeff("Nikon", "COOLPIX P7700"); maximum = 65504; load_flags = 0; } else if (!strcmp(model, "COOLPIX P7800")) { adobe_coeff("Nikon", "COOLPIX P7800"); maximum = 65504; load_flags = 0; } else if (!strcmp(model, "COOLPIX P340")) load_flags = 0; } else if (!strncmp(model, "COOLPIX P", 9) && raw_width != 4032) { load_flags = 24; filters = 0x94949494; if (model[9] == '7' && (iso_speed >= 400 || iso_speed == 0) && !strstr(software, "V1.2")) black = 255; } else if (!strncmp(model, "COOLPIX B700", 12)) { load_flags = 24; black = 200; } else if (!strncmp(model, "1 ", 2)) { height -= 2; } else if (fsize == 1581060) { simple_coeff(3); pre_mul[0] = 1.2085; pre_mul[1] = 1.0943; pre_mul[3] = 1.1103; } else if (fsize == 3178560) { cam_mul[0] *= 4; cam_mul[2] *= 4; } else if (fsize == 4771840) { if (!timestamp && nikon_e995()) strcpy(model, "E995"); if (strcmp(model, "E995")) { filters = 0xb4b4b4b4; simple_coeff(3); pre_mul[0] = 1.196; pre_mul[1] = 1.246; pre_mul[2] = 1.018; } } else if (fsize == 2940928) { if (!timestamp && !nikon_e2100()) strcpy(model, "E2500"); if (!strcmp(model, "E2500")) { height -= 2; load_flags = 6; colors = 4; filters = 0x4b4b4b4b; } } else if (fsize == 4775936) { if (!timestamp) nikon_3700(); if (model[0] == 'E' && atoi(model + 1) < 3700) filters = 0x49494949; if (!strcmp(model, "Optio 33WR")) { flip = 1; filters = 0x16161616; } if (make[0] == 'O') { i = find_green(12, 32, 1188864, 3576832); c = find_green(12, 32, 2383920, 2387016); if (abs(i) < abs(c)) { SWAP(i, c); load_flags = 24; } if (i < 0) filters = 0x61616161; } } else if (fsize == 5869568) { if (!timestamp && minolta_z2()) { strcpy(make, "Minolta"); strcpy(model, "DiMAGE Z2"); } load_flags = 6 + 24 * (make[0] == 'M'); } else if (fsize == 6291456) { fseek(ifp, 0x300000, SEEK_SET); if ((order = guess_byte_order(0x10000)) == 0x4d4d) { height -= (top_margin = 16); width -= (left_margin = 28); maximum = 0xf5c0; strcpy(make, "ISG"); model[0] = 0; } } else if (!strncmp(make, "Fujifilm", 8)) { if (!strcmp(model, "X-A3") || !strcmp(model, "X-A10")) { left_margin = 0; top_margin = 0; width = raw_width; height = raw_height; } if (!strcmp(model + 7, "S2Pro")) { strcpy(model, "S2Pro"); height = 2144; width = 2880; flip = 6; } else if (load_raw != &CLASS packed_load_raw && strncmp(model, "X-", 2)) maximum = (is_raw == 2 && shot_select) ? 0x2f00 : 0x3e00; top_margin = (raw_height - height) >> 2 << 1; left_margin = (raw_width - width) >> 2 << 1; if (width == 2848 || width == 3664) filters = 0x16161616; if (width == 4032 || width == 4952) left_margin = 0; if (width == 3328 && (width -= 66)) left_margin = 34; if (width == 4936) left_margin = 4; if (width == 6032) left_margin = 0; if (!strcmp(model, "HS50EXR") || !strcmp(model, "F900EXR")) { width += 2; left_margin = 0; filters = 0x16161616; } if (!strcmp(model, "GFX 50S")) { left_margin = 0; top_margin = 0; } if (!strcmp(model, "S5500")) { height -= (top_margin = 6); } if (fuji_layout) raw_width *= is_raw; if (filters == 9) FORC(36)((char *)xtrans)[c] = xtrans_abs[(c / 6 + top_margin) % 6][(c + left_margin) % 6]; } else if (!strcmp(model, "KD-400Z")) { height = 1712; width = 2312; raw_width = 2336; goto konica_400z; } else if (!strcmp(model, "KD-510Z")) { goto konica_510z; } else if (!strncasecmp(make, "Minolta", 7)) { if (!load_raw && (maximum = 0xfff)) load_raw = &CLASS unpacked_load_raw; if (!strncmp(model, "DiMAGE A", 8)) { if (!strcmp(model, "DiMAGE A200")) filters = 0x49494949; tiff_bps = 12; load_raw = &CLASS packed_load_raw; } else if (!strncmp(model, "ALPHA", 5) || !strncmp(model, "DYNAX", 5) || !strncmp(model, "MAXXUM", 6)) { sprintf(model + 20, "DYNAX %-10s", model + 6 + (model[0] == 'M')); adobe_coeff(make, model + 20); load_raw = &CLASS packed_load_raw; } else if (!strncmp(model, "DiMAGE G", 8)) { if (model[8] == '4') { height = 1716; width = 2304; } else if (model[8] == '5') { konica_510z: height = 1956; width = 2607; raw_width = 2624; } else if (model[8] == '6') { height = 2136; width = 2848; } data_offset += 14; filters = 0x61616161; konica_400z: load_raw = &CLASS unpacked_load_raw; maximum = 0x3df; order = 0x4d4d; } } else if (!strcmp(model, "*ist D")) { load_raw = &CLASS unpacked_load_raw; data_error = -1; } else if (!strcmp(model, "*ist DS")) { height -= 2; } else if (!strncmp(make, "Samsung", 7) && raw_width == 4704) { height -= top_margin = 8; width -= 2 * (left_margin = 8); load_flags = 32; } else if (!strncmp(make, "Samsung", 7) && !strcmp(model, "NX3000")) { top_margin = 38; left_margin = 92; width = 5456; height = 3634; filters = 0x61616161; colors = 3; } else if (!strncmp(make, "Samsung", 7) && raw_height == 3714) { height -= top_margin = 18; left_margin = raw_width - (width = 5536); if (raw_width != 5600) left_margin = top_margin = 0; filters = 0x61616161; colors = 3; } else if (!strncmp(make, "Samsung", 7) && raw_width == 5632) { order = 0x4949; height = 3694; top_margin = 2; width = 5574 - (left_margin = 32 + tiff_bps); if (tiff_bps == 12) load_flags = 80; } else if (!strncmp(make, "Samsung", 7) && raw_width == 5664) { height -= top_margin = 17; left_margin = 96; width = 5544; filters = 0x49494949; } else if (!strncmp(make, "Samsung", 7) && raw_width == 6496) { filters = 0x61616161; #ifdef LIBRAW_LIBRARY_BUILD if (!black && !cblack[0] && !cblack[1] && !cblack[2] && !cblack[3]) #endif black = 1 << (tiff_bps - 7); } else if (!strcmp(model, "EX1")) { order = 0x4949; height -= 20; top_margin = 2; if ((width -= 6) > 3682) { height -= 10; width -= 46; top_margin = 8; } } else if (!strcmp(model, "WB2000")) { order = 0x4949; height -= 3; top_margin = 2; if ((width -= 10) > 3718) { height -= 28; width -= 56; top_margin = 8; } } else if (strstr(model, "WB550")) { strcpy(model, "WB550"); } else if (!strcmp(model, "EX2F")) { height = 3030; width = 4040; top_margin = 15; left_margin = 24; order = 0x4949; filters = 0x49494949; load_raw = &CLASS unpacked_load_raw; } else if (!strcmp(model, "STV680 VGA")) { black = 16; } else if (!strcmp(model, "N95")) { height = raw_height - (top_margin = 2); } else if (!strcmp(model, "640x480")) { gamma_curve(0.45, 4.5, 1, 255); } else if (!strncmp(make, "Hasselblad", 10)) { if (load_raw == &CLASS lossless_jpeg_load_raw) load_raw = &CLASS hasselblad_load_raw; if (raw_width == 7262) { height = 5444; width = 7248; top_margin = 4; left_margin = 7; filters = 0x61616161; if (!strncasecmp(model, "H3D", 3)) { adobe_coeff("Hasselblad", "H3DII-39"); strcpy(model, "H3DII-39"); } } else if (raw_width == 12000) // H6D 100c { left_margin = 64; width = 11608; top_margin = 108; height = raw_height - top_margin; adobe_coeff("Hasselblad", "H6D-100c"); } else if (raw_width == 7410 || raw_width == 8282) { height -= 84; width -= 82; top_margin = 4; left_margin = 41; filters = 0x61616161; adobe_coeff("Hasselblad", "H4D-40"); strcpy(model, "H4D-40"); } else if (raw_width == 8384) // X1D { top_margin = 96; height -= 96; left_margin = 48; width -= 106; adobe_coeff("Hasselblad", "X1D"); maximum = 0xffff; tiff_bps = 16; } else if (raw_width == 9044) { if (black > 500) { top_margin = 12; left_margin = 44; width = 8956; height = 6708; memset(cblack, 0, sizeof(cblack)); adobe_coeff("Hasselblad", "H4D-60"); strcpy(model, "H4D-60"); black = 512; } else { height = 6716; width = 8964; top_margin = 8; left_margin = 40; black += load_flags = 256; maximum = 0x8101; strcpy(model, "H3DII-60"); } } else if (raw_width == 4090) { strcpy(model, "V96C"); height -= (top_margin = 6); width -= (left_margin = 3) + 7; filters = 0x61616161; } else if (raw_width == 8282 && raw_height == 6240) { if (!strncasecmp(model, "H5D", 3)) { /* H5D 50*/ left_margin = 54; top_margin = 16; width = 8176; height = 6132; black = 256; strcpy(model, "H5D-50"); } else if (!strncasecmp(model, "H3D", 3)) { black = 0; left_margin = 54; top_margin = 16; width = 8176; height = 6132; memset(cblack, 0, sizeof(cblack)); adobe_coeff("Hasselblad", "H3D-50"); strcpy(model, "H3D-50"); } } else if (raw_width == 8374 && raw_height == 6304) { /* H5D 50c*/ left_margin = 52; top_margin = 100; width = 8272; height = 6200; black = 256; strcpy(model, "H5D-50c"); } if (tiff_samples > 1) { is_raw = tiff_samples + 1; if (!shot_select && !half_size) filters = 0; } } else if (!strncmp(make, "Sinar", 5)) { if (!load_raw) load_raw = &CLASS unpacked_load_raw; if (is_raw > 1 && !shot_select && !half_size) filters = 0; maximum = 0x3fff; } else if (!strncmp(make, "Leaf", 4)) { maximum = 0x3fff; fseek(ifp, data_offset, SEEK_SET); if (ljpeg_start(&jh, 1) && jh.bits == 15) maximum = 0x1fff; if (tiff_samples > 1) filters = 0; if (tiff_samples > 1 || tile_length < raw_height) { load_raw = &CLASS leaf_hdr_load_raw; raw_width = tile_width; } if ((width | height) == 2048) { if (tiff_samples == 1) { filters = 1; strcpy(cdesc, "RBTG"); strcpy(model, "CatchLight"); top_margin = 8; left_margin = 18; height = 2032; width = 2016; } else { strcpy(model, "DCB2"); top_margin = 10; left_margin = 16; height = 2028; width = 2022; } } else if (width + height == 3144 + 2060) { if (!model[0]) strcpy(model, "Cantare"); if (width > height) { top_margin = 6; left_margin = 32; height = 2048; width = 3072; filters = 0x61616161; } else { left_margin = 6; top_margin = 32; width = 2048; height = 3072; filters = 0x16161616; } if (!cam_mul[0] || model[0] == 'V') filters = 0; else is_raw = tiff_samples; } else if (width == 2116) { strcpy(model, "Valeo 6"); height -= 2 * (top_margin = 30); width -= 2 * (left_margin = 55); filters = 0x49494949; } else if (width == 3171) { strcpy(model, "Valeo 6"); height -= 2 * (top_margin = 24); width -= 2 * (left_margin = 24); filters = 0x16161616; } } else if (!strncmp(make, "Leica", 5) || !strncmp(make, "Panasonic", 9) || !strncasecmp(make, "YUNEEC", 6)) { if (raw_width > 0 && ((flen - data_offset) / (raw_width * 8 / 7) == raw_height)) load_raw = &CLASS panasonic_load_raw; if (!load_raw) { load_raw = &CLASS unpacked_load_raw; load_flags = 4; } zero_is_bad = 1; if ((height += 12) > raw_height) height = raw_height; for (i = 0; i < sizeof pana / sizeof *pana; i++) if (raw_width == pana[i][0] && raw_height == pana[i][1]) { left_margin = pana[i][2]; top_margin = pana[i][3]; width += pana[i][4]; height += pana[i][5]; } filters = 0x01010101 * (uchar) "\x94\x61\x49\x16"[((filters - 1) ^ (left_margin & 1) ^ (top_margin << 1)) & 3]; } else if (!strcmp(model, "C770UZ")) { height = 1718; width = 2304; filters = 0x16161616; load_raw = &CLASS packed_load_raw; load_flags = 30; } else if (!strncmp(make, "Olympus", 7)) { height += height & 1; if (exif_cfa) filters = exif_cfa; if (width == 4100) width -= 4; if (width == 4080) width -= 24; if (width == 9280) { width -= 6; height -= 6; } if (load_raw == &CLASS unpacked_load_raw) load_flags = 4; tiff_bps = 12; if (!strcmp(model, "E-300") || !strcmp(model, "E-500")) { width -= 20; if (load_raw == &CLASS unpacked_load_raw) { maximum = 0xfc3; memset(cblack, 0, sizeof cblack); } } else if (!strcmp(model, "STYLUS1")) { width -= 14; maximum = 0xfff; } else if (!strcmp(model, "E-330")) { width -= 30; if (load_raw == &CLASS unpacked_load_raw) maximum = 0xf79; } else if (!strcmp(model, "SP550UZ")) { thumb_length = flen - (thumb_offset = 0xa39800); thumb_height = 480; thumb_width = 640; } else if (!strcmp(model, "TG-4")) { width -= 16; } else if (!strcmp(model, "TG-5")) { width -= 26; } } else if (!strcmp(model, "N Digital")) { height = 2047; width = 3072; filters = 0x61616161; data_offset = 0x1a00; load_raw = &CLASS packed_load_raw; } else if (!strcmp(model, "DSC-F828")) { width = 3288; left_margin = 5; mask[1][3] = -17; data_offset = 862144; load_raw = &CLASS sony_load_raw; filters = 0x9c9c9c9c; colors = 4; strcpy(cdesc, "RGBE"); } else if (!strcmp(model, "DSC-V3")) { width = 3109; left_margin = 59; mask[0][1] = 9; data_offset = 787392; load_raw = &CLASS sony_load_raw; } else if (!strncmp(make, "Sony", 4) && raw_width == 3984) { width = 3925; order = 0x4d4d; } else if (!strncmp(make, "Sony", 4) && raw_width == 4288) { width -= 32; } else if (!strcmp(make, "Sony") && raw_width == 4600) { if (!strcmp(model, "DSLR-A350")) height -= 4; black = 0; } else if (!strncmp(make, "Sony", 4) && raw_width == 4928) { if (height < 3280) width -= 8; } else if (!strncmp(make, "Sony", 4) && raw_width == 5504) { // ILCE-3000//5000 width -= height > 3664 ? 8 : 32; } else if (!strncmp(make, "Sony", 4) && raw_width == 6048) { width -= 24; if (strstr(model, "RX1") || strstr(model, "A99")) width -= 6; } else if (!strncmp(make, "Sony", 4) && raw_width == 7392) { width -= 30; } else if (!strncmp(make, "Sony", 4) && raw_width == 8000) { width -= 32; } else if (!strcmp(model, "DSLR-A100")) { if (width == 3880) { height--; width = ++raw_width; } else { height -= 4; width -= 4; order = 0x4d4d; load_flags = 2; } filters = 0x61616161; } else if (!strcmp(model, "PIXL")) { height -= top_margin = 4; width -= left_margin = 32; gamma_curve(0, 7, 1, 255); } else if (!strcmp(model, "C603") || !strcmp(model, "C330") || !strcmp(model, "12MP")) { order = 0x4949; if (filters && data_offset) { fseek(ifp, data_offset < 4096 ? 168 : 5252, SEEK_SET); read_shorts(curve, 256); } else gamma_curve(0, 3.875, 1, 255); load_raw = filters ? &CLASS eight_bit_load_raw : strcmp(model, "C330") ? &CLASS kodak_c603_load_raw : &CLASS kodak_c330_load_raw; load_flags = tiff_bps > 16; tiff_bps = 8; } else if (!strncasecmp(model, "EasyShare", 9)) { data_offset = data_offset < 0x15000 ? 0x15000 : 0x17000; load_raw = &CLASS packed_load_raw; } else if (!strncasecmp(make, "Kodak", 5)) { if (filters == UINT_MAX) filters = 0x61616161; if (!strncmp(model, "NC2000", 6) || !strncmp(model, "EOSDCS", 6) || !strncmp(model, "DCS4", 4)) { width -= 4; left_margin = 2; if (model[6] == ' ') model[6] = 0; if (!strcmp(model, "DCS460A")) goto bw; } else if (!strcmp(model, "DCS660M")) { black = 214; goto bw; } else if (!strcmp(model, "DCS760M")) { bw: colors = 1; filters = 0; } if (!strcmp(model + 4, "20X")) strcpy(cdesc, "MYCY"); if (strstr(model, "DC25")) { strcpy(model, "DC25"); data_offset = 15424; } if (!strncmp(model, "DC2", 3)) { raw_height = 2 + (height = 242); if (!strncmp(model, "DC290", 5)) iso_speed = 100; if (!strncmp(model, "DC280", 5)) iso_speed = 70; if (flen < 100000) { raw_width = 256; width = 249; pixel_aspect = (4.0 * height) / (3.0 * width); } else { raw_width = 512; width = 501; pixel_aspect = (493.0 * height) / (373.0 * width); } top_margin = left_margin = 1; colors = 4; filters = 0x8d8d8d8d; simple_coeff(1); pre_mul[1] = 1.179; pre_mul[2] = 1.209; pre_mul[3] = 1.036; load_raw = &CLASS eight_bit_load_raw; } else if (!strcmp(model, "40")) { strcpy(model, "DC40"); height = 512; width = 768; data_offset = 1152; load_raw = &CLASS kodak_radc_load_raw; tiff_bps = 12; } else if (strstr(model, "DC50")) { strcpy(model, "DC50"); height = 512; width = 768; iso_speed = 84; data_offset = 19712; load_raw = &CLASS kodak_radc_load_raw; } else if (strstr(model, "DC120")) { strcpy(model, "DC120"); raw_height = height = 976; raw_width = width = 848; iso_speed = 160; pixel_aspect = height / 0.75 / width; load_raw = tiff_compress == 7 ? &CLASS kodak_jpeg_load_raw : &CLASS kodak_dc120_load_raw; } else if (!strcmp(model, "DCS200")) { thumb_height = 128; thumb_width = 192; thumb_offset = 6144; thumb_misc = 360; iso_speed = 140; write_thumb = &CLASS layer_thumb; black = 17; } } else if (!strcmp(model, "Fotoman Pixtura")) { height = 512; width = 768; data_offset = 3632; load_raw = &CLASS kodak_radc_load_raw; filters = 0x61616161; simple_coeff(2); } else if (!strncmp(model, "QuickTake", 9)) { if (head[5]) strcpy(model + 10, "200"); fseek(ifp, 544, SEEK_SET); height = get2(); width = get2(); data_offset = (get4(), get2()) == 30 ? 738 : 736; if (height > width) { SWAP(height, width); fseek(ifp, data_offset - 6, SEEK_SET); flip = ~get2() & 3 ? 5 : 6; } filters = 0x61616161; } else if (!strncmp(make, "Rollei", 6) && !load_raw) { switch (raw_width) { case 1316: height = 1030; width = 1300; top_margin = 1; left_margin = 6; break; case 2568: height = 1960; width = 2560; top_margin = 2; left_margin = 8; } filters = 0x16161616; load_raw = &CLASS rollei_load_raw; } else if (!strcmp(model, "GRAS-50S5C")) { height = 2048; width = 2440; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x49494949; order = 0x4949; maximum = 0xfffC; } else if (!strcmp(model, "BB-500CL")) { height = 2058; width = 2448; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x3fff; } else if (!strcmp(model, "BB-500GE")) { height = 2058; width = 2456; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x3fff; } else if (!strcmp(model, "SVS625CL")) { height = 2050; width = 2448; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x0fff; } /* Early reject for damaged images */ if (!load_raw || height < 22 || width < 22 || #ifdef LIBRAW_LIBRARY_BUILD (tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw) #else tiff_bps > 16 #endif || tiff_samples > 4 || colors > 4 || colors < 1) { is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY, 1, 2); #endif return; } if (!model[0]) sprintf(model, "%dx%d", width, height); if (filters == UINT_MAX) filters = 0x94949494; if (thumb_offset && !thumb_height) { fseek(ifp, thumb_offset, SEEK_SET); if (ljpeg_start(&jh, 1)) { thumb_width = jh.wide; thumb_height = jh.high; } } dng_skip: #ifdef LIBRAW_LIBRARY_BUILD if (dng_version) /* Override black level by DNG tags */ { /* copy DNG data from per-IFD field to color.dng */ int iifd = 0; // Active IFD we'll show to user. for (; iifd < tiff_nifds; iifd++) if (tiff_ifd[iifd].offset == data_offset) // found break; int pifd = -1; for (int ii = 0; ii < tiff_nifds; ii++) if (tiff_ifd[ii].offset == thumb_offset) // found { pifd = ii; break; } #define CFAROUND(value, filters) filters ? (filters >= 1000 ? ((value + 1) / 2) * 2 : ((value + 5) / 6) * 6) : value #define IFDCOLORINDEX(ifd, subset, bit) \ (tiff_ifd[ifd].dng_color[subset].parsedfields & bit) ? ifd \ : ((tiff_ifd[0].dng_color[subset].parsedfields & bit) ? 0 : -1) #define IFDLEVELINDEX(ifd, bit) \ (tiff_ifd[ifd].dng_levels.parsedfields & bit) ? ifd : ((tiff_ifd[0].dng_levels.parsedfields & bit) ? 0 : -1) #define COPYARR(to, from) memmove(&to, &from, sizeof(from)) if (iifd < tiff_nifds) { int sidx; // Per field, not per structure if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_USE_DNG_DEFAULT_CROP) { sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_CROPORIGIN); int sidx2 = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_CROPSIZE); if (sidx >= 0 && sidx == sidx2) { int lm = tiff_ifd[sidx].dng_levels.default_crop[0]; int lmm = CFAROUND(lm, filters); int tm = tiff_ifd[sidx].dng_levels.default_crop[1]; int tmm = CFAROUND(tm, filters); int ww = tiff_ifd[sidx].dng_levels.default_crop[2]; int hh = tiff_ifd[sidx].dng_levels.default_crop[3]; if (lmm > lm) ww -= (lmm - lm); if (tmm > tm) hh -= (tmm - tm); if (left_margin + lm + ww <= raw_width && top_margin + tm + hh <= raw_height) { left_margin += lmm; top_margin += tmm; width = ww; height = hh; } } } if (!(imgdata.color.dng_color[0].parsedfields & LIBRAW_DNGFM_FORWARDMATRIX)) // Not set already (Leica makernotes) { sidx = IFDCOLORINDEX(iifd, 0, LIBRAW_DNGFM_FORWARDMATRIX); if (sidx >= 0) COPYARR(imgdata.color.dng_color[0].forwardmatrix, tiff_ifd[sidx].dng_color[0].forwardmatrix); } if (!(imgdata.color.dng_color[1].parsedfields & LIBRAW_DNGFM_FORWARDMATRIX)) // Not set already (Leica makernotes) { sidx = IFDCOLORINDEX(iifd, 1, LIBRAW_DNGFM_FORWARDMATRIX); if (sidx >= 0) COPYARR(imgdata.color.dng_color[1].forwardmatrix, tiff_ifd[sidx].dng_color[1].forwardmatrix); } for (int ss = 0; ss < 2; ss++) { sidx = IFDCOLORINDEX(iifd, ss, LIBRAW_DNGFM_COLORMATRIX); if (sidx >= 0) COPYARR(imgdata.color.dng_color[ss].colormatrix, tiff_ifd[sidx].dng_color[ss].colormatrix); sidx = IFDCOLORINDEX(iifd, ss, LIBRAW_DNGFM_CALIBRATION); if (sidx >= 0) COPYARR(imgdata.color.dng_color[ss].calibration, tiff_ifd[sidx].dng_color[ss].calibration); sidx = IFDCOLORINDEX(iifd, ss, LIBRAW_DNGFM_ILLUMINANT); if (sidx >= 0) imgdata.color.dng_color[ss].illuminant = tiff_ifd[sidx].dng_color[ss].illuminant; } // Levels sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_ANALOGBALANCE); if (sidx >= 0) COPYARR(imgdata.color.dng_levels.analogbalance, tiff_ifd[sidx].dng_levels.analogbalance); sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_WHITE); if (sidx >= 0) COPYARR(imgdata.color.dng_levels.dng_whitelevel, tiff_ifd[sidx].dng_levels.dng_whitelevel); sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_BLACK); if (sidx >= 0) { imgdata.color.dng_levels.dng_black = tiff_ifd[sidx].dng_levels.dng_black; COPYARR(imgdata.color.dng_levels.dng_cblack, tiff_ifd[sidx].dng_levels.dng_cblack); } if (pifd >= 0) { sidx = IFDLEVELINDEX(pifd, LIBRAW_DNGFM_PREVIEWCS); if (sidx >= 0) imgdata.color.dng_levels.preview_colorspace = tiff_ifd[sidx].dng_levels.preview_colorspace; } sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_OPCODE2); if (sidx >= 0) meta_offset = tiff_ifd[sidx].opcode2_offset; sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_LINTABLE); INT64 linoff = -1; int linlen = 0; if (sidx >= 0) { linoff = tiff_ifd[sidx].lineartable_offset; linlen = tiff_ifd[sidx].lineartable_len; } if (linoff >= 0 && linlen > 0) { INT64 pos = ftell(ifp); fseek(ifp, linoff, SEEK_SET); linear_table(linlen); fseek(ifp, pos, SEEK_SET); } // Need to add curve too } /* Copy DNG black level to LibRaw's */ maximum = imgdata.color.dng_levels.dng_whitelevel[0]; black = imgdata.color.dng_levels.dng_black; int ll = LIM(0, (sizeof(cblack) / sizeof(cblack[0])), (sizeof(imgdata.color.dng_levels.dng_cblack) / sizeof(imgdata.color.dng_levels.dng_cblack[0]))); for (int i = 0; i < ll; i++) cblack[i] = imgdata.color.dng_levels.dng_cblack[i]; } #endif /* Early reject for damaged images */ if (!load_raw || height < 22 || width < 22 || #ifdef LIBRAW_LIBRARY_BUILD (tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw) #else tiff_bps > 16 #endif || tiff_samples > 4 || colors > 4 || colors < 1) { is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY, 1, 2); #endif return; } if ((use_camera_matrix & ((use_camera_wb || dng_version) | 0x2)) && cmatrix[0][0] > 0.125) { memcpy(rgb_cam, cmatrix, sizeof cmatrix); raw_color = 0; } if (raw_color) adobe_coeff(make, model); #ifdef LIBRAW_LIBRARY_BUILD else if (imgdata.color.cam_xyz[0][0] < 0.01) adobe_coeff(make, model, 1); #endif if (load_raw == &CLASS kodak_radc_load_raw) if (raw_color) adobe_coeff("Apple", "Quicktake"); #ifdef LIBRAW_LIBRARY_BUILD // Clear erorneus fuji_width if not set through parse_fuji or for DNG if(fuji_width && !dng_version && !(imgdata.process_warnings & LIBRAW_WARN_PARSEFUJI_PROCESSED )) fuji_width = 0; #endif if (fuji_width) { fuji_width = width >> !fuji_layout; filters = fuji_width & 1 ? 0x94949494 : 0x49494949; width = (height >> fuji_layout) + fuji_width; height = width - 1; pixel_aspect = 1; } else { if (raw_height < height) raw_height = height; if (raw_width < width) raw_width = width; } if (!tiff_bps) tiff_bps = 12; if (!maximum) { maximum = (1 << tiff_bps) - 1; if (maximum < 0x10000 && curve[maximum] > 0 && load_raw == &CLASS sony_arw2_load_raw) maximum = curve[maximum]; } if (!load_raw || height < 22 || width < 22 || #ifdef LIBRAW_LIBRARY_BUILD (tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw) #else tiff_bps > 16 #endif || tiff_samples > 6 || colors > 4) is_raw = 0; if (raw_width < 22 || raw_width > 64000 || raw_height < 22 || raw_height > 64000) is_raw = 0; #ifdef NO_JASPER if (load_raw == &CLASS redcine_load_raw) { #ifdef DCRAW_VERBOSE fprintf(stderr, _("%s: You must link dcraw with %s!!\n"), ifname, "libjasper"); #endif is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_JASPER; #endif } #endif #ifdef NO_JPEG if (load_raw == &CLASS kodak_jpeg_load_raw || load_raw == &CLASS lossy_dng_load_raw) { #ifdef DCRAW_VERBOSE fprintf(stderr, _("%s: You must link dcraw with %s!!\n"), ifname, "libjpeg"); #endif is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_JPEGLIB; #endif } #endif if (!cdesc[0]) strcpy(cdesc, colors == 3 ? "RGBG" : "GMCY"); if (!raw_height) raw_height = height; if (!raw_width) raw_width = width; if (filters > 999 && colors == 3) filters |= ((filters >> 2 & 0x22222222) | (filters << 2 & 0x88888888)) & filters << 1; notraw: if (flip == UINT_MAX) flip = tiff_flip; if (flip == UINT_MAX) flip = 0; // Convert from degrees to bit-field if needed if (flip > 89 || flip < -89) { switch ((flip + 3600) % 360) { case 270: flip = 5; break; case 180: flip = 3; break; case 90: flip = 6; break; } } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY, 1, 2); #endif } //@end COMMON //@out FILEIO #ifndef NO_LCMS void CLASS apply_profile(const char *input, const char *output) { char *prof; cmsHPROFILE hInProfile = 0, hOutProfile = 0; cmsHTRANSFORM hTransform; FILE *fp; unsigned size; if (strcmp(input, "embed")) hInProfile = cmsOpenProfileFromFile(input, "r"); else if (profile_length) { #ifndef LIBRAW_LIBRARY_BUILD prof = (char *)malloc(profile_length); merror(prof, "apply_profile()"); fseek(ifp, profile_offset, SEEK_SET); fread(prof, 1, profile_length, ifp); hInProfile = cmsOpenProfileFromMem(prof, profile_length); free(prof); #else hInProfile = cmsOpenProfileFromMem(imgdata.color.profile, profile_length); #endif } else { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_EMBEDDED_PROFILE; #endif #ifdef DCRAW_VERBOSE fprintf(stderr, _("%s has no embedded profile.\n"), ifname); #endif } if (!hInProfile) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_INPUT_PROFILE; #endif return; } if (!output) hOutProfile = cmsCreate_sRGBProfile(); else if ((fp = fopen(output, "rb"))) { fread(&size, 4, 1, fp); fseek(fp, 0, SEEK_SET); oprof = (unsigned *)malloc(size = ntohl(size)); merror(oprof, "apply_profile()"); fread(oprof, 1, size, fp); fclose(fp); if (!(hOutProfile = cmsOpenProfileFromMem(oprof, size))) { free(oprof); oprof = 0; } } #ifdef DCRAW_VERBOSE else fprintf(stderr, _("Cannot open file %s!\n"), output); #endif if (!hOutProfile) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_BAD_OUTPUT_PROFILE; #endif goto quit; } #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Applying color profile...\n")); #endif #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_APPLY_PROFILE, 0, 2); #endif hTransform = cmsCreateTransform(hInProfile, TYPE_RGBA_16, hOutProfile, TYPE_RGBA_16, INTENT_PERCEPTUAL, 0); cmsDoTransform(hTransform, image, image, width * height); raw_color = 1; /* Don't use rgb_cam with a profile */ cmsDeleteTransform(hTransform); cmsCloseProfile(hOutProfile); quit: cmsCloseProfile(hInProfile); #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_APPLY_PROFILE, 1, 2); #endif } #endif //@end FILEIO //@out COMMON void CLASS convert_to_rgb() { #ifndef LIBRAW_LIBRARY_BUILD int row, col, c; #endif int i, j, k; #ifndef LIBRAW_LIBRARY_BUILD ushort *img; float out[3]; #endif float out_cam[3][4]; double num, inverse[3][3]; static const double xyzd50_srgb[3][3] = { {0.436083, 0.385083, 0.143055}, {0.222507, 0.716888, 0.060608}, {0.013930, 0.097097, 0.714022}}; static const double rgb_rgb[3][3] = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}; static const double adobe_rgb[3][3] = { {0.715146, 0.284856, 0.000000}, {0.000000, 1.000000, 0.000000}, {0.000000, 0.041166, 0.958839}}; static const double wide_rgb[3][3] = { {0.593087, 0.404710, 0.002206}, {0.095413, 0.843149, 0.061439}, {0.011621, 0.069091, 0.919288}}; static const double prophoto_rgb[3][3] = { {0.529317, 0.330092, 0.140588}, {0.098368, 0.873465, 0.028169}, {0.016879, 0.117663, 0.865457}}; static const double aces_rgb[3][3] = { {0.432996, 0.375380, 0.189317}, {0.089427, 0.816523, 0.102989}, {0.019165, 0.118150, 0.941914}}; static const double(*out_rgb[])[3] = {rgb_rgb, adobe_rgb, wide_rgb, prophoto_rgb, xyz_rgb, aces_rgb}; static const char *name[] = {"sRGB", "Adobe RGB (1998)", "WideGamut D65", "ProPhoto D65", "XYZ", "ACES"}; static const unsigned phead[] = {1024, 0, 0x2100000, 0x6d6e7472, 0x52474220, 0x58595a20, 0, 0, 0, 0x61637370, 0, 0, 0x6e6f6e65, 0, 0, 0, 0, 0xf6d6, 0x10000, 0xd32d}; unsigned pbody[] = {10, 0x63707274, 0, 36, /* cprt */ 0x64657363, 0, 40, /* desc */ 0x77747074, 0, 20, /* wtpt */ 0x626b7074, 0, 20, /* bkpt */ 0x72545243, 0, 14, /* rTRC */ 0x67545243, 0, 14, /* gTRC */ 0x62545243, 0, 14, /* bTRC */ 0x7258595a, 0, 20, /* rXYZ */ 0x6758595a, 0, 20, /* gXYZ */ 0x6258595a, 0, 20}; /* bXYZ */ static const unsigned pwhite[] = {0xf351, 0x10000, 0x116cc}; unsigned pcurve[] = {0x63757276, 0, 1, 0x1000000}; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_CONVERT_RGB, 0, 2); #endif gamma_curve(gamm[0], gamm[1], 0, 0); memcpy(out_cam, rgb_cam, sizeof out_cam); #ifndef LIBRAW_LIBRARY_BUILD raw_color |= colors == 1 || document_mode || output_color < 1 || output_color > 6; #else raw_color |= colors == 1 || output_color < 1 || output_color > 6; #endif if (!raw_color) { oprof = (unsigned *)calloc(phead[0], 1); merror(oprof, "convert_to_rgb()"); memcpy(oprof, phead, sizeof phead); if (output_color == 5) oprof[4] = oprof[5]; oprof[0] = 132 + 12 * pbody[0]; for (i = 0; i < pbody[0]; i++) { oprof[oprof[0] / 4] = i ? (i > 1 ? 0x58595a20 : 0x64657363) : 0x74657874; pbody[i * 3 + 2] = oprof[0]; oprof[0] += (pbody[i * 3 + 3] + 3) & -4; } memcpy(oprof + 32, pbody, sizeof pbody); oprof[pbody[5] / 4 + 2] = strlen(name[output_color - 1]) + 1; memcpy((char *)oprof + pbody[8] + 8, pwhite, sizeof pwhite); pcurve[3] = (short)(256 / gamm[5] + 0.5) << 16; for (i = 4; i < 7; i++) memcpy((char *)oprof + pbody[i * 3 + 2], pcurve, sizeof pcurve); pseudoinverse((double(*)[3])out_rgb[output_color - 1], inverse, 3); for (i = 0; i < 3; i++) for (j = 0; j < 3; j++) { for (num = k = 0; k < 3; k++) num += xyzd50_srgb[i][k] * inverse[j][k]; oprof[pbody[j * 3 + 23] / 4 + i + 2] = num * 0x10000 + 0.5; } for (i = 0; i < phead[0] / 4; i++) oprof[i] = htonl(oprof[i]); strcpy((char *)oprof + pbody[2] + 8, "auto-generated by dcraw"); strcpy((char *)oprof + pbody[5] + 12, name[output_color - 1]); for (i = 0; i < 3; i++) for (j = 0; j < colors; j++) for (out_cam[i][j] = k = 0; k < 3; k++) out_cam[i][j] += out_rgb[output_color - 1][i][k] * rgb_cam[k][j]; } #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, raw_color ? _("Building histograms...\n") : _("Converting to %s colorspace...\n"), name[output_color - 1]); #endif #ifdef LIBRAW_LIBRARY_BUILD convert_to_rgb_loop(out_cam); #else memset(histogram, 0, sizeof histogram); for (img = image[0], row = 0; row < height; row++) for (col = 0; col < width; col++, img += 4) { if (!raw_color) { out[0] = out[1] = out[2] = 0; FORCC { out[0] += out_cam[0][c] * img[c]; out[1] += out_cam[1][c] * img[c]; out[2] += out_cam[2][c] * img[c]; } FORC3 img[c] = CLIP((int)out[c]); } else if (document_mode) img[0] = img[fcol(row, col)]; FORCC histogram[c][img[c] >> 3]++; } #endif if (colors == 4 && output_color) colors = 3; #ifndef LIBRAW_LIBRARY_BUILD if (document_mode && filters) colors = 1; #endif #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_CONVERT_RGB, 1, 2); #endif } void CLASS fuji_rotate() { int i, row, col; double step; float r, c, fr, fc; unsigned ur, uc; ushort wide, high, (*img)[4], (*pix)[4]; if (!fuji_width) return; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Rotating image 45 degrees...\n")); #endif fuji_width = (fuji_width - 1 + shrink) >> shrink; step = sqrt(0.5); wide = fuji_width / step; high = (height - fuji_width) / step; img = (ushort(*)[4])calloc(high, wide * sizeof *img); merror(img, "fuji_rotate()"); #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_FUJI_ROTATE, 0, 2); #endif for (row = 0; row < high; row++) for (col = 0; col < wide; col++) { ur = r = fuji_width + (row - col) * step; uc = c = (row + col) * step; if (ur > height - 2 || uc > width - 2) continue; fr = r - ur; fc = c - uc; pix = image + ur * width + uc; for (i = 0; i < colors; i++) img[row * wide + col][i] = (pix[0][i] * (1 - fc) + pix[1][i] * fc) * (1 - fr) + (pix[width][i] * (1 - fc) + pix[width + 1][i] * fc) * fr; } free(image); width = wide; height = high; image = img; fuji_width = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_FUJI_ROTATE, 1, 2); #endif } void CLASS stretch() { ushort newdim, (*img)[4], *pix0, *pix1; int row, col, c; double rc, frac; if (pixel_aspect == 1) return; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_STRETCH, 0, 2); #endif #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Stretching the image...\n")); #endif if (pixel_aspect < 1) { newdim = height / pixel_aspect + 0.5; img = (ushort(*)[4])calloc(width, newdim * sizeof *img); merror(img, "stretch()"); for (rc = row = 0; row < newdim; row++, rc += pixel_aspect) { frac = rc - (c = rc); pix0 = pix1 = image[c * width]; if (c + 1 < height) pix1 += width * 4; for (col = 0; col < width; col++, pix0 += 4, pix1 += 4) FORCC img[row * width + col][c] = pix0[c] * (1 - frac) + pix1[c] * frac + 0.5; } height = newdim; } else { newdim = width * pixel_aspect + 0.5; img = (ushort(*)[4])calloc(height, newdim * sizeof *img); merror(img, "stretch()"); for (rc = col = 0; col < newdim; col++, rc += 1 / pixel_aspect) { frac = rc - (c = rc); pix0 = pix1 = image[c]; if (c + 1 < width) pix1 += 4; for (row = 0; row < height; row++, pix0 += width * 4, pix1 += width * 4) FORCC img[row * newdim + col][c] = pix0[c] * (1 - frac) + pix1[c] * frac + 0.5; } width = newdim; } free(image); image = img; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_STRETCH, 1, 2); #endif } int CLASS flip_index(int row, int col) { if (flip & 4) SWAP(row, col); if (flip & 2) row = iheight - 1 - row; if (flip & 1) col = iwidth - 1 - col; return row * iwidth + col; } //@end COMMON struct tiff_tag { ushort tag, type; int count; union { char c[4]; short s[2]; int i; } val; }; struct tiff_hdr { ushort t_order, magic; int ifd; ushort pad, ntag; struct tiff_tag tag[23]; int nextifd; ushort pad2, nexif; struct tiff_tag exif[4]; ushort pad3, ngps; struct tiff_tag gpst[10]; short bps[4]; int rat[10]; unsigned gps[26]; char t_desc[512], t_make[64], t_model[64], soft[32], date[20], t_artist[64]; }; //@out COMMON void CLASS tiff_set(struct tiff_hdr *th, ushort *ntag, ushort tag, ushort type, int count, int val) { struct tiff_tag *tt; int c; tt = (struct tiff_tag *)(ntag + 1) + (*ntag)++; tt->val.i = val; if (type == 1 && count <= 4) FORC(4) tt->val.c[c] = val >> (c << 3); else if (type == 2) { count = strnlen((char *)th + val, count - 1) + 1; if (count <= 4) FORC(4) tt->val.c[c] = ((char *)th)[val + c]; } else if (type == 3 && count <= 2) FORC(2) tt->val.s[c] = val >> (c << 4); tt->count = count; tt->type = type; tt->tag = tag; } #define TOFF(ptr) ((char *)(&(ptr)) - (char *)th) void CLASS tiff_head(struct tiff_hdr *th, int full) { int c, psize = 0; struct tm *t; memset(th, 0, sizeof *th); th->t_order = htonl(0x4d4d4949) >> 16; th->magic = 42; th->ifd = 10; th->rat[0] = th->rat[2] = 300; th->rat[1] = th->rat[3] = 1; FORC(6) th->rat[4 + c] = 1000000; th->rat[4] *= shutter; th->rat[6] *= aperture; th->rat[8] *= focal_len; strncpy(th->t_desc, desc, 512); strncpy(th->t_make, make, 64); strncpy(th->t_model, model, 64); strcpy(th->soft, "dcraw v" DCRAW_VERSION); t = localtime(&timestamp); sprintf(th->date, "%04d:%02d:%02d %02d:%02d:%02d", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec); strncpy(th->t_artist, artist, 64); if (full) { tiff_set(th, &th->ntag, 254, 4, 1, 0); tiff_set(th, &th->ntag, 256, 4, 1, width); tiff_set(th, &th->ntag, 257, 4, 1, height); tiff_set(th, &th->ntag, 258, 3, colors, output_bps); if (colors > 2) th->tag[th->ntag - 1].val.i = TOFF(th->bps); FORC4 th->bps[c] = output_bps; tiff_set(th, &th->ntag, 259, 3, 1, 1); tiff_set(th, &th->ntag, 262, 3, 1, 1 + (colors > 1)); } tiff_set(th, &th->ntag, 270, 2, 512, TOFF(th->t_desc)); tiff_set(th, &th->ntag, 271, 2, 64, TOFF(th->t_make)); tiff_set(th, &th->ntag, 272, 2, 64, TOFF(th->t_model)); if (full) { if (oprof) psize = ntohl(oprof[0]); tiff_set(th, &th->ntag, 273, 4, 1, sizeof *th + psize); tiff_set(th, &th->ntag, 277, 3, 1, colors); tiff_set(th, &th->ntag, 278, 4, 1, height); tiff_set(th, &th->ntag, 279, 4, 1, height * width * colors * output_bps / 8); } else tiff_set(th, &th->ntag, 274, 3, 1, "12435867"[flip] - '0'); tiff_set(th, &th->ntag, 282, 5, 1, TOFF(th->rat[0])); tiff_set(th, &th->ntag, 283, 5, 1, TOFF(th->rat[2])); tiff_set(th, &th->ntag, 284, 3, 1, 1); tiff_set(th, &th->ntag, 296, 3, 1, 2); tiff_set(th, &th->ntag, 305, 2, 32, TOFF(th->soft)); tiff_set(th, &th->ntag, 306, 2, 20, TOFF(th->date)); tiff_set(th, &th->ntag, 315, 2, 64, TOFF(th->t_artist)); tiff_set(th, &th->ntag, 34665, 4, 1, TOFF(th->nexif)); if (psize) tiff_set(th, &th->ntag, 34675, 7, psize, sizeof *th); tiff_set(th, &th->nexif, 33434, 5, 1, TOFF(th->rat[4])); tiff_set(th, &th->nexif, 33437, 5, 1, TOFF(th->rat[6])); tiff_set(th, &th->nexif, 34855, 3, 1, iso_speed); tiff_set(th, &th->nexif, 37386, 5, 1, TOFF(th->rat[8])); if (gpsdata[1]) { tiff_set(th, &th->ntag, 34853, 4, 1, TOFF(th->ngps)); tiff_set(th, &th->ngps, 0, 1, 4, 0x202); tiff_set(th, &th->ngps, 1, 2, 2, gpsdata[29]); tiff_set(th, &th->ngps, 2, 5, 3, TOFF(th->gps[0])); tiff_set(th, &th->ngps, 3, 2, 2, gpsdata[30]); tiff_set(th, &th->ngps, 4, 5, 3, TOFF(th->gps[6])); tiff_set(th, &th->ngps, 5, 1, 1, gpsdata[31]); tiff_set(th, &th->ngps, 6, 5, 1, TOFF(th->gps[18])); tiff_set(th, &th->ngps, 7, 5, 3, TOFF(th->gps[12])); tiff_set(th, &th->ngps, 18, 2, 12, TOFF(th->gps[20])); tiff_set(th, &th->ngps, 29, 2, 12, TOFF(th->gps[23])); memcpy(th->gps, gpsdata, sizeof th->gps); } } #ifdef LIBRAW_LIBRARY_BUILD void CLASS jpeg_thumb_writer(FILE *tfp, char *t_humb, int t_humb_length) { ushort exif[5]; struct tiff_hdr th; fputc(0xff, tfp); fputc(0xd8, tfp); if (strcmp(t_humb + 6, "Exif")) { memcpy(exif, "\xff\xe1 Exif\0\0", 10); exif[1] = htons(8 + sizeof th); fwrite(exif, 1, sizeof exif, tfp); tiff_head(&th, 0); fwrite(&th, 1, sizeof th, tfp); } fwrite(t_humb + 2, 1, t_humb_length - 2, tfp); } void CLASS jpeg_thumb() { char *thumb; thumb = (char *)malloc(thumb_length); merror(thumb, "jpeg_thumb()"); fread(thumb, 1, thumb_length, ifp); jpeg_thumb_writer(ofp, thumb, thumb_length); free(thumb); } #else void CLASS jpeg_thumb() { char *thumb; ushort exif[5]; struct tiff_hdr th; thumb = (char *)malloc(thumb_length); merror(thumb, "jpeg_thumb()"); fread(thumb, 1, thumb_length, ifp); fputc(0xff, ofp); fputc(0xd8, ofp); if (strcmp(thumb + 6, "Exif")) { memcpy(exif, "\xff\xe1 Exif\0\0", 10); exif[1] = htons(8 + sizeof th); fwrite(exif, 1, sizeof exif, ofp); tiff_head(&th, 0); fwrite(&th, 1, sizeof th, ofp); } fwrite(thumb + 2, 1, thumb_length - 2, ofp); free(thumb); } #endif void CLASS write_ppm_tiff() { struct tiff_hdr th; uchar *ppm; ushort *ppm2; int c, row, col, soff, rstep, cstep; int perc, val, total, t_white = 0x2000; #ifdef LIBRAW_LIBRARY_BUILD perc = width * height * auto_bright_thr; #else perc = width * height * 0.01; /* 99th percentile white level */ #endif if (fuji_width) perc /= 2; if (!((highlight & ~2) || no_auto_bright)) for (t_white = c = 0; c < colors; c++) { for (val = 0x2000, total = 0; --val > 32;) if ((total += histogram[c][val]) > perc) break; if (t_white < val) t_white = val; } gamma_curve(gamm[0], gamm[1], 2, (t_white << 3) / bright); iheight = height; iwidth = width; if (flip & 4) SWAP(height, width); ppm = (uchar *)calloc(width, colors * output_bps / 8); ppm2 = (ushort *)ppm; merror(ppm, "write_ppm_tiff()"); if (output_tiff) { tiff_head(&th, 1); fwrite(&th, sizeof th, 1, ofp); if (oprof) fwrite(oprof, ntohl(oprof[0]), 1, ofp); } else if (colors > 3) fprintf(ofp, "P7\nWIDTH %d\nHEIGHT %d\nDEPTH %d\nMAXVAL %d\nTUPLTYPE %s\nENDHDR\n", width, height, colors, (1 << output_bps) - 1, cdesc); else fprintf(ofp, "P%d\n%d %d\n%d\n", colors / 2 + 5, width, height, (1 << output_bps) - 1); soff = flip_index(0, 0); cstep = flip_index(0, 1) - soff; rstep = flip_index(1, 0) - flip_index(0, width); for (row = 0; row < height; row++, soff += rstep) { for (col = 0; col < width; col++, soff += cstep) if (output_bps == 8) FORCC ppm[col * colors + c] = curve[image[soff][c]] >> 8; else FORCC ppm2[col * colors + c] = curve[image[soff][c]]; if (output_bps == 16 && !output_tiff && htons(0x55aa) != 0x55aa) swab((char *)ppm2, (char *)ppm2, width * colors * 2); fwrite(ppm, colors * output_bps / 8, width, ofp); } free(ppm); } //@end COMMON int CLASS main(int argc, const char **argv) { int arg, status = 0, quality, i, c; int timestamp_only = 0, thumbnail_only = 0, identify_only = 0; int user_qual = -1, user_black = -1, user_sat = -1, user_flip = -1; int use_fuji_rotate = 1, write_to_stdout = 0, read_from_stdin = 0; const char *sp, *bpfile = 0, *dark_frame = 0, *write_ext; char opm, opt, *ofname, *cp; struct utimbuf ut; #ifndef NO_LCMS const char *cam_profile = 0, *out_profile = 0; #endif #ifndef LOCALTIME putenv((char *)"TZ=UTC"); #endif #ifdef LOCALEDIR setlocale(LC_CTYPE, ""); setlocale(LC_MESSAGES, ""); bindtextdomain("dcraw", LOCALEDIR); textdomain("dcraw"); #endif if (argc == 1) { printf(_("\nRaw photo decoder \"dcraw\" v%s"), DCRAW_VERSION); printf(_("\nby Dave Coffin, dcoffin a cybercom o net\n")); printf(_("\nUsage: %s [OPTION]... [FILE]...\n\n"), argv[0]); puts(_("-v Print verbose messages")); puts(_("-c Write image data to standard output")); puts(_("-e Extract embedded thumbnail image")); puts(_("-i Identify files without decoding them")); puts(_("-i -v Identify files and show metadata")); puts(_("-z Change file dates to camera timestamp")); puts(_("-w Use camera white balance, if possible")); puts(_("-a Average the whole image for white balance")); puts(_("-A <x y w h> Average a grey box for white balance")); puts(_("-r <r g b g> Set custom white balance")); puts(_("+M/-M Use/don't use an embedded color matrix")); puts(_("-C <r b> Correct chromatic aberration")); puts(_("-P <file> Fix the dead pixels listed in this file")); puts(_("-K <file> Subtract dark frame (16-bit raw PGM)")); puts(_("-k <num> Set the darkness level")); puts(_("-S <num> Set the saturation level")); puts(_("-n <num> Set threshold for wavelet denoising")); puts(_("-H [0-9] Highlight mode (0=clip, 1=unclip, 2=blend, 3+=rebuild)")); puts(_("-t [0-7] Flip image (0=none, 3=180, 5=90CCW, 6=90CW)")); puts(_("-o [0-5] Output colorspace (raw,sRGB,Adobe,Wide,ProPhoto,XYZ)")); #ifndef NO_LCMS puts(_("-o <file> Apply output ICC profile from file")); puts(_("-p <file> Apply camera ICC profile from file or \"embed\"")); #endif puts(_("-d Document mode (no color, no interpolation)")); puts(_("-D Document mode without scaling (totally raw)")); puts(_("-j Don't stretch or rotate raw pixels")); puts(_("-W Don't automatically brighten the image")); puts(_("-b <num> Adjust brightness (default = 1.0)")); puts(_("-g <p ts> Set custom gamma curve (default = 2.222 4.5)")); puts(_("-q [0-3] Set the interpolation quality")); puts(_("-h Half-size color image (twice as fast as \"-q 0\")")); puts(_("-f Interpolate RGGB as four colors")); puts(_("-m <num> Apply a 3x3 median filter to R-G and B-G")); puts(_("-s [0..N-1] Select one raw image or \"all\" from each file")); puts(_("-6 Write 16-bit instead of 8-bit")); puts(_("-4 Linear 16-bit, same as \"-6 -W -g 1 1\"")); puts(_("-T Write TIFF instead of PPM")); puts(""); return 1; } argv[argc] = ""; for (arg = 1; (((opm = argv[arg][0]) - 2) | 2) == '+';) { opt = argv[arg++][1]; if ((cp = (char *)strchr(sp = "nbrkStqmHACg", opt))) for (i = 0; i < "114111111422"[cp - sp] - '0'; i++) if (!isdigit(argv[arg + i][0])) { fprintf(stderr, _("Non-numeric argument to \"-%c\"\n"), opt); return 1; } switch (opt) { case 'n': threshold = atof(argv[arg++]); break; case 'b': bright = atof(argv[arg++]); break; case 'r': FORC4 user_mul[c] = atof(argv[arg++]); break; case 'C': aber[0] = 1 / atof(argv[arg++]); aber[2] = 1 / atof(argv[arg++]); break; case 'g': gamm[0] = atof(argv[arg++]); gamm[1] = atof(argv[arg++]); if (gamm[0]) gamm[0] = 1 / gamm[0]; break; case 'k': user_black = atoi(argv[arg++]); break; case 'S': user_sat = atoi(argv[arg++]); break; case 't': user_flip = atoi(argv[arg++]); break; case 'q': user_qual = atoi(argv[arg++]); break; case 'm': med_passes = atoi(argv[arg++]); break; case 'H': highlight = atoi(argv[arg++]); break; case 's': shot_select = abs(atoi(argv[arg])); multi_out = !strcmp(argv[arg++], "all"); break; case 'o': if (isdigit(argv[arg][0]) && !argv[arg][1]) output_color = atoi(argv[arg++]); #ifndef NO_LCMS else out_profile = argv[arg++]; break; case 'p': cam_profile = argv[arg++]; #endif break; case 'P': bpfile = argv[arg++]; break; case 'K': dark_frame = argv[arg++]; break; case 'z': timestamp_only = 1; break; case 'e': thumbnail_only = 1; break; case 'i': identify_only = 1; break; case 'c': write_to_stdout = 1; break; case 'v': verbose = 1; break; case 'h': half_size = 1; break; case 'f': four_color_rgb = 1; break; case 'A': FORC4 greybox[c] = atoi(argv[arg++]); case 'a': use_auto_wb = 1; break; case 'w': use_camera_wb = 1; break; case 'M': use_camera_matrix = 3 * (opm == '+'); break; case 'I': read_from_stdin = 1; break; case 'E': document_mode++; case 'D': document_mode++; case 'd': document_mode++; case 'j': use_fuji_rotate = 0; break; case 'W': no_auto_bright = 1; break; case 'T': output_tiff = 1; break; case '4': gamm[0] = gamm[1] = no_auto_bright = 1; case '6': output_bps = 16; break; default: fprintf(stderr, _("Unknown option \"-%c\".\n"), opt); return 1; } } if (arg == argc) { fprintf(stderr, _("No files to process.\n")); return 1; } if (write_to_stdout) { if (isatty(1)) { fprintf(stderr, _("Will not write an image to the terminal!\n")); return 1; } #if defined(WIN32) || defined(DJGPP) || defined(__CYGWIN__) if (setmode(1, O_BINARY) < 0) { perror("setmode()"); return 1; } #endif } for (; arg < argc; arg++) { status = 1; raw_image = 0; image = 0; oprof = 0; meta_data = ofname = 0; ofp = stdout; if (setjmp(failure)) { if (fileno(ifp) > 2) fclose(ifp); if (fileno(ofp) > 2) fclose(ofp); status = 1; goto cleanup; } ifname = argv[arg]; if (!(ifp = fopen(ifname, "rb"))) { perror(ifname); continue; } status = (identify(), !is_raw); if (user_flip >= 0) flip = user_flip; switch ((flip + 3600) % 360) { case 270: flip = 5; break; case 180: flip = 3; break; case 90: flip = 6; } if (timestamp_only) { if ((status = !timestamp)) fprintf(stderr, _("%s has no timestamp.\n"), ifname); else if (identify_only) printf("%10ld%10d %s\n", (long)timestamp, shot_order, ifname); else { if (verbose) fprintf(stderr, _("%s time set to %d.\n"), ifname, (int)timestamp); ut.actime = ut.modtime = timestamp; utime(ifname, &ut); } goto next; } write_fun = &CLASS write_ppm_tiff; if (thumbnail_only) { if ((status = !thumb_offset)) { fprintf(stderr, _("%s has no thumbnail.\n"), ifname); goto next; } else if (thumb_load_raw) { load_raw = thumb_load_raw; data_offset = thumb_offset; height = thumb_height; width = thumb_width; filters = 0; colors = 3; } else { fseek(ifp, thumb_offset, SEEK_SET); write_fun = write_thumb; goto thumbnail; } } if (load_raw == &CLASS kodak_ycbcr_load_raw) { height += height & 1; width += width & 1; } if (identify_only && verbose && make[0]) { printf(_("\nFilename: %s\n"), ifname); printf(_("Timestamp: %s"), ctime(&timestamp)); printf(_("Camera: %s %s\n"), make, model); if (artist[0]) printf(_("Owner: %s\n"), artist); if (dng_version) { printf(_("DNG Version: ")); for (i = 24; i >= 0; i -= 8) printf("%d%c", dng_version >> i & 255, i ? '.' : '\n'); } printf(_("ISO speed: %d\n"), (int)iso_speed); printf(_("Shutter: ")); if (shutter > 0 && shutter < 1) shutter = (printf("1/"), 1 / shutter); printf(_("%0.1f sec\n"), shutter); printf(_("Aperture: f/%0.1f\n"), aperture); printf(_("Focal length: %0.1f mm\n"), focal_len); printf(_("Embedded ICC profile: %s\n"), profile_length ? _("yes") : _("no")); printf(_("Number of raw images: %d\n"), is_raw); if (pixel_aspect != 1) printf(_("Pixel Aspect Ratio: %0.6f\n"), pixel_aspect); if (thumb_offset) printf(_("Thumb size: %4d x %d\n"), thumb_width, thumb_height); printf(_("Full size: %4d x %d\n"), raw_width, raw_height); } else if (!is_raw) fprintf(stderr, _("Cannot decode file %s\n"), ifname); if (!is_raw) goto next; shrink = filters && (half_size || (!identify_only && (threshold || aber[0] != 1 || aber[2] != 1))); iheight = (height + shrink) >> shrink; iwidth = (width + shrink) >> shrink; if (identify_only) { if (verbose) { if (document_mode == 3) { top_margin = left_margin = fuji_width = 0; height = raw_height; width = raw_width; } iheight = (height + shrink) >> shrink; iwidth = (width + shrink) >> shrink; if (use_fuji_rotate) { if (fuji_width) { fuji_width = (fuji_width - 1 + shrink) >> shrink; iwidth = fuji_width / sqrt(0.5); iheight = (iheight - fuji_width) / sqrt(0.5); } else { if (pixel_aspect < 1) iheight = iheight / pixel_aspect + 0.5; if (pixel_aspect > 1) iwidth = iwidth * pixel_aspect + 0.5; } } if (flip & 4) SWAP(iheight, iwidth); printf(_("Image size: %4d x %d\n"), width, height); printf(_("Output size: %4d x %d\n"), iwidth, iheight); printf(_("Raw colors: %d"), colors); if (filters) { int fhigh = 2, fwide = 2; if ((filters ^ (filters >> 8)) & 0xff) fhigh = 4; if ((filters ^ (filters >> 16)) & 0xffff) fhigh = 8; if (filters == 1) fhigh = fwide = 16; if (filters == 9) fhigh = fwide = 6; printf(_("\nFilter pattern: ")); for (i = 0; i < fhigh; i++) for (c = i && putchar('/') && 0; c < fwide; c++) putchar(cdesc[fcol(i, c)]); } printf(_("\nDaylight multipliers:")); FORCC printf(" %f", pre_mul[c]); if (cam_mul[0] > 0) { printf(_("\nCamera multipliers:")); FORC4 printf(" %f", cam_mul[c]); } putchar('\n'); } else printf(_("%s is a %s %s image.\n"), ifname, make, model); next: fclose(ifp); continue; } if (meta_length) { meta_data = (char *)malloc(meta_length); merror(meta_data, "main()"); } if (filters || colors == 1) { raw_image = (ushort *)calloc((raw_height + 7), raw_width * 2); merror(raw_image, "main()"); } else { image = (ushort(*)[4])calloc(iheight, iwidth * sizeof *image); merror(image, "main()"); } if (verbose) fprintf(stderr, _("Loading %s %s image from %s ...\n"), make, model, ifname); if (shot_select >= is_raw) fprintf(stderr, _("%s: \"-s %d\" requests a nonexistent image!\n"), ifname, shot_select); fseeko(ifp, data_offset, SEEK_SET); if (raw_image && read_from_stdin) fread(raw_image, 2, raw_height * raw_width, stdin); else (*load_raw)(); if (document_mode == 3) { top_margin = left_margin = fuji_width = 0; height = raw_height; width = raw_width; } iheight = (height + shrink) >> shrink; iwidth = (width + shrink) >> shrink; if (raw_image) { image = (ushort(*)[4])calloc(iheight, iwidth * sizeof *image); merror(image, "main()"); crop_masked_pixels(); free(raw_image); } if (zero_is_bad) remove_zeroes(); bad_pixels(bpfile); if (dark_frame) subtract(dark_frame); quality = 2 + !fuji_width; if (user_qual >= 0) quality = user_qual; i = cblack[3]; FORC3 if (i > cblack[c]) i = cblack[c]; FORC4 cblack[c] -= i; black += i; i = cblack[6]; FORC(cblack[4] * cblack[5]) if (i > cblack[6 + c]) i = cblack[6 + c]; FORC(cblack[4] * cblack[5]) cblack[6 + c] -= i; black += i; if (user_black >= 0) black = user_black; FORC4 cblack[c] += black; if (user_sat > 0) maximum = user_sat; #ifdef COLORCHECK colorcheck(); #endif if (is_foveon) { if (document_mode || load_raw == &CLASS foveon_dp_load_raw) { for (i = 0; i < height * width * 4; i++) if ((short)image[0][i] < 0) image[0][i] = 0; } else foveon_interpolate(); } else if (document_mode < 2) scale_colors(); pre_interpolate(); if (filters && !document_mode) { if (quality == 0) lin_interpolate(); else if (quality == 1 || colors > 3) vng_interpolate(); else if (quality == 2 && filters > 1000) ppg_interpolate(); else if (filters == 9) xtrans_interpolate(quality * 2 - 3); else ahd_interpolate(); } if (mix_green) for (colors = 3, i = 0; i < height * width; i++) image[i][1] = (image[i][1] + image[i][3]) >> 1; if (!is_foveon && colors == 3) median_filter(); if (!is_foveon && highlight == 2) blend_highlights(); if (!is_foveon && highlight > 2) recover_highlights(); if (use_fuji_rotate) fuji_rotate(); #ifndef NO_LCMS if (cam_profile) apply_profile(cam_profile, out_profile); #endif convert_to_rgb(); if (use_fuji_rotate) stretch(); thumbnail: if (write_fun == &CLASS jpeg_thumb) write_ext = ".jpg"; else if (output_tiff && write_fun == &CLASS write_ppm_tiff) write_ext = ".tiff"; else write_ext = ".pgm\0.ppm\0.ppm\0.pam" + colors * 5 - 5; ofname = (char *)malloc(strlen(ifname) + 64); merror(ofname, "main()"); if (write_to_stdout) strcpy(ofname, _("standard output")); else { strcpy(ofname, ifname); if ((cp = strrchr(ofname, '.'))) *cp = 0; if (multi_out) sprintf(ofname + strlen(ofname), "_%0*d", snprintf(0, 0, "%d", is_raw - 1), shot_select); if (thumbnail_only) strcat(ofname, ".thumb"); strcat(ofname, write_ext); ofp = fopen(ofname, "wb"); if (!ofp) { status = 1; perror(ofname); goto cleanup; } } if (verbose) fprintf(stderr, _("Writing data to %s ...\n"), ofname); (*write_fun)(); fclose(ifp); if (ofp != stdout) fclose(ofp); cleanup: if (meta_data) free(meta_data); if (ofname) free(ofname); if (oprof) free(oprof); if (image) free(image); if (multi_out) { if (++shot_select < is_raw) arg--; else shot_select = 0; } } return status; } #endif
./CrossVul/dataset_final_sorted/CWE-119/c/bad_578_1
crossvul-cpp_data_good_2511_0
/* * Copyright 2015, Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ #define _GNU_SOURCE #include <errno.h> #include <assert.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <scsi/scsi.h> #include <glusterfs/api/glfs.h> #include "darray.h" #include "tcmu-runner.h" #define ALLOWED_BSOFLAGS (O_SYNC | O_DIRECT | O_RDWR | O_LARGEFILE) #define GLUSTER_PORT "24007" #define TCMU_GLFS_LOG_FILENAME "tcmu-runner-glfs.log" /* MAX 32 CHAR */ #define TCMU_GLFS_DEBUG_LEVEL 4 /* tcmu log dir path */ extern char *tcmu_log_dir; typedef enum gluster_transport { GLUSTER_TRANSPORT_TCP, GLUSTER_TRANSPORT_UNIX, GLUSTER_TRANSPORT_RDMA, GLUSTER_TRANSPORT__MAX, } gluster_transport; typedef struct unix_sockaddr { char *socket; } unix_sockaddr; typedef struct inet_sockaddr { char *addr; char *port; } inet_sockaddr; typedef struct gluster_hostdef { gluster_transport type; union { /* union tag is @type */ unix_sockaddr uds; inet_sockaddr inet; } u; } gluster_hostdef; typedef struct gluster_server { char *volname; /* volume name*/ char *path; /* path of file in the volume */ gluster_hostdef *server; /* gluster server definition */ } gluster_server; struct glfs_state { glfs_t *fs; glfs_fd_t *gfd; gluster_server *hosts; /* * Current tcmu helper API reports WCE=1, but doesn't * implement inquiry VPD 0xb2, so clients will not know UNMAP * or WRITE_SAME are supported. TODO: fix this */ }; typedef struct glfs_cbk_cookie { struct tcmu_device *dev; struct tcmulib_cmd *cmd; size_t length; enum { TCMU_GLFS_READ = 1, TCMU_GLFS_WRITE = 2, TCMU_GLFS_FLUSH = 3 } op; } glfs_cbk_cookie; struct gluster_cacheconn { char *volname; gluster_hostdef *server; glfs_t *fs; darray(char *) cfgstring; } gluster_cacheconn; static darray(struct gluster_cacheconn *) cache = darray_new(); const char *const gluster_transport_lookup[] = { [GLUSTER_TRANSPORT_TCP] = "tcp", [GLUSTER_TRANSPORT_UNIX] = "unix", [GLUSTER_TRANSPORT_RDMA] = "rdma", [GLUSTER_TRANSPORT__MAX] = NULL, }; static void gluster_free_host(gluster_hostdef *host) { if(!host) return; switch (host->type) { case GLUSTER_TRANSPORT_UNIX: free(host->u.uds.socket); break; case GLUSTER_TRANSPORT_TCP: case GLUSTER_TRANSPORT_RDMA: free(host->u.inet.addr); free(host->u.inet.port); break; case GLUSTER_TRANSPORT__MAX: break; } } static bool gluster_compare_hosts(gluster_hostdef *src_server, gluster_hostdef *dst_server) { if (src_server->type != dst_server->type) return false; switch (src_server->type) { case GLUSTER_TRANSPORT_UNIX: if (!strcmp(src_server->u.uds.socket, dst_server->u.uds.socket)) return true; break; case GLUSTER_TRANSPORT_TCP: case GLUSTER_TRANSPORT_RDMA: if (!strcmp(src_server->u.inet.addr, dst_server->u.inet.addr) && !strcmp(src_server->u.inet.port, dst_server->u.inet.port)) return true; break; case GLUSTER_TRANSPORT__MAX: break; } return false; } static int gluster_cache_add(gluster_server *dst, glfs_t *fs, char* cfgstring) { struct gluster_cacheconn *entry; char* cfg_copy = NULL; entry = calloc(1, sizeof(gluster_cacheconn)); if (!entry) goto error; entry->volname = strdup(dst->volname); entry->server = calloc(1, sizeof(gluster_hostdef)); if (!entry->server) goto error; entry->server->type = dst->server->type; if (entry->server->type == GLUSTER_TRANSPORT_UNIX) { entry->server->u.uds.socket = strdup(dst->server->u.uds.socket); } else { entry->server->u.inet.addr = strdup(dst->server->u.inet.addr); entry->server->u.inet.port = strdup(dst->server->u.inet.port); } entry->fs = fs; cfg_copy = strdup(cfgstring); darray_init(entry->cfgstring); darray_append(entry->cfgstring, cfg_copy); darray_append(cache, entry); return 0; error: return -1; } static glfs_t* gluster_cache_query(gluster_server *dst, char *cfgstring) { struct gluster_cacheconn **entry; char** config; char* cfg_copy = NULL; bool cfgmatch = false; darray_foreach(entry, cache) { if (strcmp((*entry)->volname, dst->volname)) continue; if (gluster_compare_hosts((*entry)->server, dst->server)) { darray_foreach(config, (*entry)->cfgstring) { if (!strcmp(*config, cfgstring)) { cfgmatch = true; break; } } if (!cfgmatch) { cfg_copy = strdup(cfgstring); darray_append((*entry)->cfgstring, cfg_copy); } return (*entry)->fs; } } return NULL; } static void gluster_cache_refresh(glfs_t *fs, const char *cfgstring) { struct gluster_cacheconn **entry; char** config; size_t i = 0; size_t j = 0; if (!fs) return; darray_foreach(entry, cache) { if ((*entry)->fs == fs) { if (cfgstring) { darray_foreach(config, (*entry)->cfgstring) { if (!strcmp(*config, cfgstring)) { free(*config); darray_remove((*entry)->cfgstring, j); break; } j++; } } if (darray_size((*entry)->cfgstring)) return; free((*entry)->volname); glfs_fini((*entry)->fs); (*entry)->fs = NULL; gluster_free_host((*entry)->server); free((*entry)->server); (*entry)->server = NULL; free((*entry)); darray_remove(cache, i); return; } else { i++; } } } static void gluster_free_server(gluster_server **hosts) { if (!*hosts) return; free((*hosts)->volname); free((*hosts)->path); gluster_free_host((*hosts)->server); free((*hosts)->server); (*hosts)->server = NULL; free(*hosts); *hosts = NULL; } /* * Break image string into server, volume, and path components. * Returns -1 on failure. */ static int parse_imagepath(char *cfgstring, gluster_server **hosts) { gluster_server *entry = NULL; char *origp = strdup(cfgstring); char *p, *sep; if (!origp) goto fail; /* part before '@' is the volume name */ p = origp; sep = strchr(p, '@'); if (!sep) goto fail; *hosts = calloc(1, sizeof(gluster_server)); if (!hosts) goto fail; entry = *hosts; entry->server = calloc(1, sizeof(gluster_hostdef)); if (!entry->server) goto fail; *sep = '\0'; entry->volname = strdup(p); if (!entry->volname) goto fail; /* part between '@' and 1st '/' is the server name */ p = sep + 1; sep = strchr(p, '/'); if (!sep) goto fail; *sep = '\0'; entry->server->type = GLUSTER_TRANSPORT_TCP; /* FIXME: Get type dynamically */ entry->server->u.inet.addr = strdup(p); if (!entry->server->u.inet.addr) goto fail; entry->server->u.inet.port = strdup(GLUSTER_PORT); /* FIXME: Get port dynamically */ /* The rest is the path name */ p = sep + 1; entry->path = strdup(p); if (!entry->path) goto fail; if (entry->server->type == GLUSTER_TRANSPORT_UNIX) { if (!strlen(entry->server->u.uds.socket) || !strlen(entry->volname) || !strlen(entry->path)) goto fail; } else { if (!strlen(entry->server->u.inet.addr) || !strlen(entry->volname) || !strlen(entry->path)) goto fail; } free(origp); return 0; fail: gluster_free_server(hosts); free(origp); return -1; } static glfs_t* tcmu_create_glfs_object(char *config, gluster_server **hosts) { gluster_server *entry = NULL; char logfilepath[PATH_MAX]; glfs_t *fs = NULL; int ret = -1; if (parse_imagepath(config, hosts) == -1) { tcmu_err("hostaddr, volname, or path missing\n"); goto fail; } entry = *hosts; fs = gluster_cache_query(entry, config); if (fs) return fs; fs = glfs_new(entry->volname); if (!fs) { tcmu_err("glfs_new failed\n"); goto fail; } ret = gluster_cache_add(entry, fs, config); if (ret) { tcmu_err("gluster_cache_add failed: %m\n"); goto fail; } ret = glfs_set_volfile_server(fs, gluster_transport_lookup[entry->server->type], entry->server->u.inet.addr, atoi(entry->server->u.inet.port)); if (ret) { tcmu_err("glfs_set_volfile_server failed: %m\n"); goto unref; } ret = tcmu_make_absolute_logfile(logfilepath, TCMU_GLFS_LOG_FILENAME); if (ret < 0) { tcmu_err("tcmu_make_absolute_logfile failed: %m\n"); goto unref; } ret = glfs_set_logging(fs, logfilepath, TCMU_GLFS_DEBUG_LEVEL); if (ret < 0) { tcmu_err("glfs_set_logging failed: %m\n"); goto unref; } ret = glfs_init(fs); if (ret) { tcmu_err("glfs_init failed: %m\n"); goto unref; } return fs; unref: gluster_cache_refresh(fs, config); fail: gluster_free_server(hosts); return NULL; } static char* tcmu_get_path( struct tcmu_device *dev) { char *config; config = strchr(tcmu_get_dev_cfgstring(dev), '/'); if (!config) { tcmu_err("no configuration found in cfgstring\n"); return NULL; } config += 1; /* get past '/' */ return config; } static int tcmu_glfs_open(struct tcmu_device *dev) { struct glfs_state *gfsp; int ret = 0; char *config; struct stat st; gfsp = calloc(1, sizeof(*gfsp)); if (!gfsp) return -ENOMEM; tcmu_set_dev_private(dev, gfsp); config = tcmu_get_path(dev); if (!config) { goto fail; } gfsp->fs = tcmu_create_glfs_object(config, &gfsp->hosts); if (!gfsp->fs) { tcmu_err("tcmu_create_glfs_object failed\n"); goto fail; } gfsp->gfd = glfs_open(gfsp->fs, gfsp->hosts->path, ALLOWED_BSOFLAGS); if (!gfsp->gfd) { tcmu_err("glfs_open failed: %m\n"); goto unref; } ret = glfs_lstat(gfsp->fs, gfsp->hosts->path, &st); if (ret) { tcmu_err("glfs_lstat failed: %m\n"); goto unref; } if (st.st_size != tcmu_get_device_size(dev)) { tcmu_err("device size and backing size disagree: " "device %lld backing %lld\n", tcmu_get_device_size(dev), (long long) st.st_size); goto unref; } return 0; unref: gluster_cache_refresh(gfsp->fs, tcmu_get_path(dev)); fail: if (gfsp->gfd) glfs_close(gfsp->gfd); gluster_free_server(&gfsp->hosts); free(gfsp); return -EIO; } static void tcmu_glfs_close(struct tcmu_device *dev) { struct glfs_state *gfsp = tcmu_get_dev_private(dev); glfs_close(gfsp->gfd); gluster_cache_refresh(gfsp->fs, tcmu_get_path(dev)); gluster_free_server(&gfsp->hosts); free(gfsp); } static void glfs_async_cbk(glfs_fd_t *fd, ssize_t ret, void *data) { glfs_cbk_cookie *cookie = data; struct tcmu_device *dev = cookie->dev; struct tcmulib_cmd *cmd = cookie->cmd; size_t length = cookie->length; if (ret < 0 || ret != length) { /* Read/write/flush failed */ switch (cookie->op) { case TCMU_GLFS_READ: ret = tcmu_set_sense_data(cmd->sense_buf, MEDIUM_ERROR, ASC_READ_ERROR, NULL); break; case TCMU_GLFS_WRITE: case TCMU_GLFS_FLUSH: ret = tcmu_set_sense_data(cmd->sense_buf, MEDIUM_ERROR, ASC_WRITE_ERROR, NULL); break; } } else { ret = SAM_STAT_GOOD; } cmd->done(dev, cmd, ret); free(cookie); } static int tcmu_glfs_read(struct tcmu_device *dev, struct tcmulib_cmd *cmd, struct iovec *iov, size_t iov_cnt, size_t length, off_t offset) { struct glfs_state *state = tcmu_get_dev_private(dev); glfs_cbk_cookie *cookie; cookie = calloc(1, sizeof(*cookie)); if (!cookie) { tcmu_err("Could not allocate cookie: %m\n"); goto out; } cookie->dev = dev; cookie->cmd = cmd; cookie->length = length; cookie->op = TCMU_GLFS_READ; if (glfs_preadv_async(state->gfd, iov, iov_cnt, offset, SEEK_SET, glfs_async_cbk, cookie) < 0) { tcmu_err("glfs_preadv_async failed: %m\n"); goto out; } return 0; out: free(cookie); return SAM_STAT_TASK_SET_FULL; } static int tcmu_glfs_write(struct tcmu_device *dev, struct tcmulib_cmd *cmd, struct iovec *iov, size_t iov_cnt, size_t length, off_t offset) { struct glfs_state *state = tcmu_get_dev_private(dev); glfs_cbk_cookie *cookie; cookie = calloc(1, sizeof(*cookie)); if (!cookie) { tcmu_err("Could not allocate cookie: %m\n"); goto out; } cookie->dev = dev; cookie->cmd = cmd; cookie->length = length; cookie->op = TCMU_GLFS_WRITE; if (glfs_pwritev_async(state->gfd, iov, iov_cnt, offset, ALLOWED_BSOFLAGS, glfs_async_cbk, cookie) < 0) { tcmu_err("glfs_pwritev_async failed: %m\n"); goto out; } return 0; out: free(cookie); return SAM_STAT_TASK_SET_FULL; } static int tcmu_glfs_flush(struct tcmu_device *dev, struct tcmulib_cmd *cmd) { struct glfs_state *state = tcmu_get_dev_private(dev); glfs_cbk_cookie *cookie; cookie = calloc(1, sizeof(*cookie)); if (!cookie) { tcmu_err("Could not allocate cookie: %m\n"); goto out; } cookie->dev = dev; cookie->cmd = cmd; cookie->length = 0; cookie->op = TCMU_GLFS_FLUSH; if (glfs_fdatasync_async(state->gfd, glfs_async_cbk, cookie) < 0) { tcmu_err("glfs_fdatasync_async failed: %m\n"); goto out; } return 0; out: free(cookie); return SAM_STAT_TASK_SET_FULL; } static const char glfs_cfg_desc[] = "glfs config string is of the form:\n" "\"volume@hostname/filename\"\n" "where:\n" " volume: The volume on the Gluster server\n" " hostname: The server's hostname\n" " filename: The backing file"; struct tcmur_handler glfs_handler = { .name = "Gluster glfs handler", .subtype = "glfs", .cfg_desc = glfs_cfg_desc, .open = tcmu_glfs_open, .close = tcmu_glfs_close, .read = tcmu_glfs_read, .write = tcmu_glfs_write, .flush = tcmu_glfs_flush, }; /* Entry point must be named "handler_init". */ int handler_init(void) { return tcmur_register_handler(&glfs_handler); }
./CrossVul/dataset_final_sorted/CWE-119/c/good_2511_0
crossvul-cpp_data_bad_544_0
/* * Copyright (c) 2013-2015, Mellanox Technologies. All rights reserved. * * This software is available to you under a choice of one of two * licenses. You may choose to be licensed under the terms of the GNU * General Public License (GPL) Version 2, available from the file * COPYING in the main directory of this source tree, or the * OpenIB.org BSD license below: * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. * * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <linux/module.h> #include <rdma/ib_umem.h> #include <rdma/ib_cache.h> #include <rdma/ib_user_verbs.h> #include <linux/mlx5/fs.h> #include "mlx5_ib.h" #include "ib_rep.h" /* not supported currently */ static int wq_signature; enum { MLX5_IB_ACK_REQ_FREQ = 8, }; enum { MLX5_IB_DEFAULT_SCHED_QUEUE = 0x83, MLX5_IB_DEFAULT_QP0_SCHED_QUEUE = 0x3f, MLX5_IB_LINK_TYPE_IB = 0, MLX5_IB_LINK_TYPE_ETH = 1 }; enum { MLX5_IB_SQ_STRIDE = 6, MLX5_IB_SQ_UMR_INLINE_THRESHOLD = 64, }; static const u32 mlx5_ib_opcode[] = { [IB_WR_SEND] = MLX5_OPCODE_SEND, [IB_WR_LSO] = MLX5_OPCODE_LSO, [IB_WR_SEND_WITH_IMM] = MLX5_OPCODE_SEND_IMM, [IB_WR_RDMA_WRITE] = MLX5_OPCODE_RDMA_WRITE, [IB_WR_RDMA_WRITE_WITH_IMM] = MLX5_OPCODE_RDMA_WRITE_IMM, [IB_WR_RDMA_READ] = MLX5_OPCODE_RDMA_READ, [IB_WR_ATOMIC_CMP_AND_SWP] = MLX5_OPCODE_ATOMIC_CS, [IB_WR_ATOMIC_FETCH_AND_ADD] = MLX5_OPCODE_ATOMIC_FA, [IB_WR_SEND_WITH_INV] = MLX5_OPCODE_SEND_INVAL, [IB_WR_LOCAL_INV] = MLX5_OPCODE_UMR, [IB_WR_REG_MR] = MLX5_OPCODE_UMR, [IB_WR_MASKED_ATOMIC_CMP_AND_SWP] = MLX5_OPCODE_ATOMIC_MASKED_CS, [IB_WR_MASKED_ATOMIC_FETCH_AND_ADD] = MLX5_OPCODE_ATOMIC_MASKED_FA, [MLX5_IB_WR_UMR] = MLX5_OPCODE_UMR, }; struct mlx5_wqe_eth_pad { u8 rsvd0[16]; }; enum raw_qp_set_mask_map { MLX5_RAW_QP_MOD_SET_RQ_Q_CTR_ID = 1UL << 0, MLX5_RAW_QP_RATE_LIMIT = 1UL << 1, }; struct mlx5_modify_raw_qp_param { u16 operation; u32 set_mask; /* raw_qp_set_mask_map */ struct mlx5_rate_limit rl; u8 rq_q_ctr_id; }; static void get_cqs(enum ib_qp_type qp_type, struct ib_cq *ib_send_cq, struct ib_cq *ib_recv_cq, struct mlx5_ib_cq **send_cq, struct mlx5_ib_cq **recv_cq); static int is_qp0(enum ib_qp_type qp_type) { return qp_type == IB_QPT_SMI; } static int is_sqp(enum ib_qp_type qp_type) { return is_qp0(qp_type) || is_qp1(qp_type); } static void *get_wqe(struct mlx5_ib_qp *qp, int offset) { return mlx5_buf_offset(&qp->buf, offset); } static void *get_recv_wqe(struct mlx5_ib_qp *qp, int n) { return get_wqe(qp, qp->rq.offset + (n << qp->rq.wqe_shift)); } void *mlx5_get_send_wqe(struct mlx5_ib_qp *qp, int n) { return get_wqe(qp, qp->sq.offset + (n << MLX5_IB_SQ_STRIDE)); } /** * mlx5_ib_read_user_wqe() - Copy a user-space WQE to kernel space. * * @qp: QP to copy from. * @send: copy from the send queue when non-zero, use the receive queue * otherwise. * @wqe_index: index to start copying from. For send work queues, the * wqe_index is in units of MLX5_SEND_WQE_BB. * For receive work queue, it is the number of work queue * element in the queue. * @buffer: destination buffer. * @length: maximum number of bytes to copy. * * Copies at least a single WQE, but may copy more data. * * Return: the number of bytes copied, or an error code. */ int mlx5_ib_read_user_wqe(struct mlx5_ib_qp *qp, int send, int wqe_index, void *buffer, u32 length, struct mlx5_ib_qp_base *base) { struct ib_device *ibdev = qp->ibqp.device; struct mlx5_ib_dev *dev = to_mdev(ibdev); struct mlx5_ib_wq *wq = send ? &qp->sq : &qp->rq; size_t offset; size_t wq_end; struct ib_umem *umem = base->ubuffer.umem; u32 first_copy_length; int wqe_length; int ret; if (wq->wqe_cnt == 0) { mlx5_ib_dbg(dev, "mlx5_ib_read_user_wqe for a QP with wqe_cnt == 0. qp_type: 0x%x\n", qp->ibqp.qp_type); return -EINVAL; } offset = wq->offset + ((wqe_index % wq->wqe_cnt) << wq->wqe_shift); wq_end = wq->offset + (wq->wqe_cnt << wq->wqe_shift); if (send && length < sizeof(struct mlx5_wqe_ctrl_seg)) return -EINVAL; if (offset > umem->length || (send && offset + sizeof(struct mlx5_wqe_ctrl_seg) > umem->length)) return -EINVAL; first_copy_length = min_t(u32, offset + length, wq_end) - offset; ret = ib_umem_copy_from(buffer, umem, offset, first_copy_length); if (ret) return ret; if (send) { struct mlx5_wqe_ctrl_seg *ctrl = buffer; int ds = be32_to_cpu(ctrl->qpn_ds) & MLX5_WQE_CTRL_DS_MASK; wqe_length = ds * MLX5_WQE_DS_UNITS; } else { wqe_length = 1 << wq->wqe_shift; } if (wqe_length <= first_copy_length) return first_copy_length; ret = ib_umem_copy_from(buffer + first_copy_length, umem, wq->offset, wqe_length - first_copy_length); if (ret) return ret; return wqe_length; } static void mlx5_ib_qp_event(struct mlx5_core_qp *qp, int type) { struct ib_qp *ibqp = &to_mibqp(qp)->ibqp; struct ib_event event; if (type == MLX5_EVENT_TYPE_PATH_MIG) { /* This event is only valid for trans_qps */ to_mibqp(qp)->port = to_mibqp(qp)->trans_qp.alt_port; } if (ibqp->event_handler) { event.device = ibqp->device; event.element.qp = ibqp; switch (type) { case MLX5_EVENT_TYPE_PATH_MIG: event.event = IB_EVENT_PATH_MIG; break; case MLX5_EVENT_TYPE_COMM_EST: event.event = IB_EVENT_COMM_EST; break; case MLX5_EVENT_TYPE_SQ_DRAINED: event.event = IB_EVENT_SQ_DRAINED; break; case MLX5_EVENT_TYPE_SRQ_LAST_WQE: event.event = IB_EVENT_QP_LAST_WQE_REACHED; break; case MLX5_EVENT_TYPE_WQ_CATAS_ERROR: event.event = IB_EVENT_QP_FATAL; break; case MLX5_EVENT_TYPE_PATH_MIG_FAILED: event.event = IB_EVENT_PATH_MIG_ERR; break; case MLX5_EVENT_TYPE_WQ_INVAL_REQ_ERROR: event.event = IB_EVENT_QP_REQ_ERR; break; case MLX5_EVENT_TYPE_WQ_ACCESS_ERROR: event.event = IB_EVENT_QP_ACCESS_ERR; break; default: pr_warn("mlx5_ib: Unexpected event type %d on QP %06x\n", type, qp->qpn); return; } ibqp->event_handler(&event, ibqp->qp_context); } } static int set_rq_size(struct mlx5_ib_dev *dev, struct ib_qp_cap *cap, int has_rq, struct mlx5_ib_qp *qp, struct mlx5_ib_create_qp *ucmd) { int wqe_size; int wq_size; /* Sanity check RQ size before proceeding */ if (cap->max_recv_wr > (1 << MLX5_CAP_GEN(dev->mdev, log_max_qp_sz))) return -EINVAL; if (!has_rq) { qp->rq.max_gs = 0; qp->rq.wqe_cnt = 0; qp->rq.wqe_shift = 0; cap->max_recv_wr = 0; cap->max_recv_sge = 0; } else { if (ucmd) { qp->rq.wqe_cnt = ucmd->rq_wqe_count; if (ucmd->rq_wqe_shift > BITS_PER_BYTE * sizeof(ucmd->rq_wqe_shift)) return -EINVAL; qp->rq.wqe_shift = ucmd->rq_wqe_shift; if ((1 << qp->rq.wqe_shift) / sizeof(struct mlx5_wqe_data_seg) < qp->wq_sig) return -EINVAL; qp->rq.max_gs = (1 << qp->rq.wqe_shift) / sizeof(struct mlx5_wqe_data_seg) - qp->wq_sig; qp->rq.max_post = qp->rq.wqe_cnt; } else { wqe_size = qp->wq_sig ? sizeof(struct mlx5_wqe_signature_seg) : 0; wqe_size += cap->max_recv_sge * sizeof(struct mlx5_wqe_data_seg); wqe_size = roundup_pow_of_two(wqe_size); wq_size = roundup_pow_of_two(cap->max_recv_wr) * wqe_size; wq_size = max_t(int, wq_size, MLX5_SEND_WQE_BB); qp->rq.wqe_cnt = wq_size / wqe_size; if (wqe_size > MLX5_CAP_GEN(dev->mdev, max_wqe_sz_rq)) { mlx5_ib_dbg(dev, "wqe_size %d, max %d\n", wqe_size, MLX5_CAP_GEN(dev->mdev, max_wqe_sz_rq)); return -EINVAL; } qp->rq.wqe_shift = ilog2(wqe_size); qp->rq.max_gs = (1 << qp->rq.wqe_shift) / sizeof(struct mlx5_wqe_data_seg) - qp->wq_sig; qp->rq.max_post = qp->rq.wqe_cnt; } } return 0; } static int sq_overhead(struct ib_qp_init_attr *attr) { int size = 0; switch (attr->qp_type) { case IB_QPT_XRC_INI: size += sizeof(struct mlx5_wqe_xrc_seg); /* fall through */ case IB_QPT_RC: size += sizeof(struct mlx5_wqe_ctrl_seg) + max(sizeof(struct mlx5_wqe_atomic_seg) + sizeof(struct mlx5_wqe_raddr_seg), sizeof(struct mlx5_wqe_umr_ctrl_seg) + sizeof(struct mlx5_mkey_seg) + MLX5_IB_SQ_UMR_INLINE_THRESHOLD / MLX5_IB_UMR_OCTOWORD); break; case IB_QPT_XRC_TGT: return 0; case IB_QPT_UC: size += sizeof(struct mlx5_wqe_ctrl_seg) + max(sizeof(struct mlx5_wqe_raddr_seg), sizeof(struct mlx5_wqe_umr_ctrl_seg) + sizeof(struct mlx5_mkey_seg)); break; case IB_QPT_UD: if (attr->create_flags & IB_QP_CREATE_IPOIB_UD_LSO) size += sizeof(struct mlx5_wqe_eth_pad) + sizeof(struct mlx5_wqe_eth_seg); /* fall through */ case IB_QPT_SMI: case MLX5_IB_QPT_HW_GSI: size += sizeof(struct mlx5_wqe_ctrl_seg) + sizeof(struct mlx5_wqe_datagram_seg); break; case MLX5_IB_QPT_REG_UMR: size += sizeof(struct mlx5_wqe_ctrl_seg) + sizeof(struct mlx5_wqe_umr_ctrl_seg) + sizeof(struct mlx5_mkey_seg); break; default: return -EINVAL; } return size; } static int calc_send_wqe(struct ib_qp_init_attr *attr) { int inl_size = 0; int size; size = sq_overhead(attr); if (size < 0) return size; if (attr->cap.max_inline_data) { inl_size = size + sizeof(struct mlx5_wqe_inline_seg) + attr->cap.max_inline_data; } size += attr->cap.max_send_sge * sizeof(struct mlx5_wqe_data_seg); if (attr->create_flags & IB_QP_CREATE_SIGNATURE_EN && ALIGN(max_t(int, inl_size, size), MLX5_SEND_WQE_BB) < MLX5_SIG_WQE_SIZE) return MLX5_SIG_WQE_SIZE; else return ALIGN(max_t(int, inl_size, size), MLX5_SEND_WQE_BB); } static int get_send_sge(struct ib_qp_init_attr *attr, int wqe_size) { int max_sge; if (attr->qp_type == IB_QPT_RC) max_sge = (min_t(int, wqe_size, 512) - sizeof(struct mlx5_wqe_ctrl_seg) - sizeof(struct mlx5_wqe_raddr_seg)) / sizeof(struct mlx5_wqe_data_seg); else if (attr->qp_type == IB_QPT_XRC_INI) max_sge = (min_t(int, wqe_size, 512) - sizeof(struct mlx5_wqe_ctrl_seg) - sizeof(struct mlx5_wqe_xrc_seg) - sizeof(struct mlx5_wqe_raddr_seg)) / sizeof(struct mlx5_wqe_data_seg); else max_sge = (wqe_size - sq_overhead(attr)) / sizeof(struct mlx5_wqe_data_seg); return min_t(int, max_sge, wqe_size - sq_overhead(attr) / sizeof(struct mlx5_wqe_data_seg)); } static int calc_sq_size(struct mlx5_ib_dev *dev, struct ib_qp_init_attr *attr, struct mlx5_ib_qp *qp) { int wqe_size; int wq_size; if (!attr->cap.max_send_wr) return 0; wqe_size = calc_send_wqe(attr); mlx5_ib_dbg(dev, "wqe_size %d\n", wqe_size); if (wqe_size < 0) return wqe_size; if (wqe_size > MLX5_CAP_GEN(dev->mdev, max_wqe_sz_sq)) { mlx5_ib_dbg(dev, "wqe_size(%d) > max_sq_desc_sz(%d)\n", wqe_size, MLX5_CAP_GEN(dev->mdev, max_wqe_sz_sq)); return -EINVAL; } qp->max_inline_data = wqe_size - sq_overhead(attr) - sizeof(struct mlx5_wqe_inline_seg); attr->cap.max_inline_data = qp->max_inline_data; if (attr->create_flags & IB_QP_CREATE_SIGNATURE_EN) qp->signature_en = true; wq_size = roundup_pow_of_two(attr->cap.max_send_wr * wqe_size); qp->sq.wqe_cnt = wq_size / MLX5_SEND_WQE_BB; if (qp->sq.wqe_cnt > (1 << MLX5_CAP_GEN(dev->mdev, log_max_qp_sz))) { mlx5_ib_dbg(dev, "send queue size (%d * %d / %d -> %d) exceeds limits(%d)\n", attr->cap.max_send_wr, wqe_size, MLX5_SEND_WQE_BB, qp->sq.wqe_cnt, 1 << MLX5_CAP_GEN(dev->mdev, log_max_qp_sz)); return -ENOMEM; } qp->sq.wqe_shift = ilog2(MLX5_SEND_WQE_BB); qp->sq.max_gs = get_send_sge(attr, wqe_size); if (qp->sq.max_gs < attr->cap.max_send_sge) return -ENOMEM; attr->cap.max_send_sge = qp->sq.max_gs; qp->sq.max_post = wq_size / wqe_size; attr->cap.max_send_wr = qp->sq.max_post; return wq_size; } static int set_user_buf_size(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *qp, struct mlx5_ib_create_qp *ucmd, struct mlx5_ib_qp_base *base, struct ib_qp_init_attr *attr) { int desc_sz = 1 << qp->sq.wqe_shift; if (desc_sz > MLX5_CAP_GEN(dev->mdev, max_wqe_sz_sq)) { mlx5_ib_warn(dev, "desc_sz %d, max_sq_desc_sz %d\n", desc_sz, MLX5_CAP_GEN(dev->mdev, max_wqe_sz_sq)); return -EINVAL; } if (ucmd->sq_wqe_count && ((1 << ilog2(ucmd->sq_wqe_count)) != ucmd->sq_wqe_count)) { mlx5_ib_warn(dev, "sq_wqe_count %d, sq_wqe_count %d\n", ucmd->sq_wqe_count, ucmd->sq_wqe_count); return -EINVAL; } qp->sq.wqe_cnt = ucmd->sq_wqe_count; if (qp->sq.wqe_cnt > (1 << MLX5_CAP_GEN(dev->mdev, log_max_qp_sz))) { mlx5_ib_warn(dev, "wqe_cnt %d, max_wqes %d\n", qp->sq.wqe_cnt, 1 << MLX5_CAP_GEN(dev->mdev, log_max_qp_sz)); return -EINVAL; } if (attr->qp_type == IB_QPT_RAW_PACKET || qp->flags & MLX5_IB_QP_UNDERLAY) { base->ubuffer.buf_size = qp->rq.wqe_cnt << qp->rq.wqe_shift; qp->raw_packet_qp.sq.ubuffer.buf_size = qp->sq.wqe_cnt << 6; } else { base->ubuffer.buf_size = (qp->rq.wqe_cnt << qp->rq.wqe_shift) + (qp->sq.wqe_cnt << 6); } return 0; } static int qp_has_rq(struct ib_qp_init_attr *attr) { if (attr->qp_type == IB_QPT_XRC_INI || attr->qp_type == IB_QPT_XRC_TGT || attr->srq || attr->qp_type == MLX5_IB_QPT_REG_UMR || !attr->cap.max_recv_wr) return 0; return 1; } enum { /* this is the first blue flame register in the array of bfregs assigned * to a processes. Since we do not use it for blue flame but rather * regular 64 bit doorbells, we do not need a lock for maintaiing * "odd/even" order */ NUM_NON_BLUE_FLAME_BFREGS = 1, }; static int max_bfregs(struct mlx5_ib_dev *dev, struct mlx5_bfreg_info *bfregi) { return get_num_static_uars(dev, bfregi) * MLX5_NON_FP_BFREGS_PER_UAR; } static int num_med_bfreg(struct mlx5_ib_dev *dev, struct mlx5_bfreg_info *bfregi) { int n; n = max_bfregs(dev, bfregi) - bfregi->num_low_latency_bfregs - NUM_NON_BLUE_FLAME_BFREGS; return n >= 0 ? n : 0; } static int first_med_bfreg(struct mlx5_ib_dev *dev, struct mlx5_bfreg_info *bfregi) { return num_med_bfreg(dev, bfregi) ? 1 : -ENOMEM; } static int first_hi_bfreg(struct mlx5_ib_dev *dev, struct mlx5_bfreg_info *bfregi) { int med; med = num_med_bfreg(dev, bfregi); return ++med; } static int alloc_high_class_bfreg(struct mlx5_ib_dev *dev, struct mlx5_bfreg_info *bfregi) { int i; for (i = first_hi_bfreg(dev, bfregi); i < max_bfregs(dev, bfregi); i++) { if (!bfregi->count[i]) { bfregi->count[i]++; return i; } } return -ENOMEM; } static int alloc_med_class_bfreg(struct mlx5_ib_dev *dev, struct mlx5_bfreg_info *bfregi) { int minidx = first_med_bfreg(dev, bfregi); int i; if (minidx < 0) return minidx; for (i = minidx; i < first_hi_bfreg(dev, bfregi); i++) { if (bfregi->count[i] < bfregi->count[minidx]) minidx = i; if (!bfregi->count[minidx]) break; } bfregi->count[minidx]++; return minidx; } static int alloc_bfreg(struct mlx5_ib_dev *dev, struct mlx5_bfreg_info *bfregi) { int bfregn = -ENOMEM; mutex_lock(&bfregi->lock); if (bfregi->ver >= 2) { bfregn = alloc_high_class_bfreg(dev, bfregi); if (bfregn < 0) bfregn = alloc_med_class_bfreg(dev, bfregi); } if (bfregn < 0) { BUILD_BUG_ON(NUM_NON_BLUE_FLAME_BFREGS != 1); bfregn = 0; bfregi->count[bfregn]++; } mutex_unlock(&bfregi->lock); return bfregn; } void mlx5_ib_free_bfreg(struct mlx5_ib_dev *dev, struct mlx5_bfreg_info *bfregi, int bfregn) { mutex_lock(&bfregi->lock); bfregi->count[bfregn]--; mutex_unlock(&bfregi->lock); } static enum mlx5_qp_state to_mlx5_state(enum ib_qp_state state) { switch (state) { case IB_QPS_RESET: return MLX5_QP_STATE_RST; case IB_QPS_INIT: return MLX5_QP_STATE_INIT; case IB_QPS_RTR: return MLX5_QP_STATE_RTR; case IB_QPS_RTS: return MLX5_QP_STATE_RTS; case IB_QPS_SQD: return MLX5_QP_STATE_SQD; case IB_QPS_SQE: return MLX5_QP_STATE_SQER; case IB_QPS_ERR: return MLX5_QP_STATE_ERR; default: return -1; } } static int to_mlx5_st(enum ib_qp_type type) { switch (type) { case IB_QPT_RC: return MLX5_QP_ST_RC; case IB_QPT_UC: return MLX5_QP_ST_UC; case IB_QPT_UD: return MLX5_QP_ST_UD; case MLX5_IB_QPT_REG_UMR: return MLX5_QP_ST_REG_UMR; case IB_QPT_XRC_INI: case IB_QPT_XRC_TGT: return MLX5_QP_ST_XRC; case IB_QPT_SMI: return MLX5_QP_ST_QP0; case MLX5_IB_QPT_HW_GSI: return MLX5_QP_ST_QP1; case MLX5_IB_QPT_DCI: return MLX5_QP_ST_DCI; case IB_QPT_RAW_IPV6: return MLX5_QP_ST_RAW_IPV6; case IB_QPT_RAW_PACKET: case IB_QPT_RAW_ETHERTYPE: return MLX5_QP_ST_RAW_ETHERTYPE; case IB_QPT_MAX: default: return -EINVAL; } } static void mlx5_ib_lock_cqs(struct mlx5_ib_cq *send_cq, struct mlx5_ib_cq *recv_cq); static void mlx5_ib_unlock_cqs(struct mlx5_ib_cq *send_cq, struct mlx5_ib_cq *recv_cq); int bfregn_to_uar_index(struct mlx5_ib_dev *dev, struct mlx5_bfreg_info *bfregi, u32 bfregn, bool dyn_bfreg) { unsigned int bfregs_per_sys_page; u32 index_of_sys_page; u32 offset; bfregs_per_sys_page = get_uars_per_sys_page(dev, bfregi->lib_uar_4k) * MLX5_NON_FP_BFREGS_PER_UAR; index_of_sys_page = bfregn / bfregs_per_sys_page; if (dyn_bfreg) { index_of_sys_page += bfregi->num_static_sys_pages; if (index_of_sys_page >= bfregi->num_sys_pages) return -EINVAL; if (bfregn > bfregi->num_dyn_bfregs || bfregi->sys_pages[index_of_sys_page] == MLX5_IB_INVALID_UAR_INDEX) { mlx5_ib_dbg(dev, "Invalid dynamic uar index\n"); return -EINVAL; } } offset = bfregn % bfregs_per_sys_page / MLX5_NON_FP_BFREGS_PER_UAR; return bfregi->sys_pages[index_of_sys_page] + offset; } static int mlx5_ib_umem_get(struct mlx5_ib_dev *dev, struct ib_pd *pd, unsigned long addr, size_t size, struct ib_umem **umem, int *npages, int *page_shift, int *ncont, u32 *offset) { int err; *umem = ib_umem_get(pd->uobject->context, addr, size, 0, 0); if (IS_ERR(*umem)) { mlx5_ib_dbg(dev, "umem_get failed\n"); return PTR_ERR(*umem); } mlx5_ib_cont_pages(*umem, addr, 0, npages, page_shift, ncont, NULL); err = mlx5_ib_get_buf_offset(addr, *page_shift, offset); if (err) { mlx5_ib_warn(dev, "bad offset\n"); goto err_umem; } mlx5_ib_dbg(dev, "addr 0x%lx, size %zu, npages %d, page_shift %d, ncont %d, offset %d\n", addr, size, *npages, *page_shift, *ncont, *offset); return 0; err_umem: ib_umem_release(*umem); *umem = NULL; return err; } static void destroy_user_rq(struct mlx5_ib_dev *dev, struct ib_pd *pd, struct mlx5_ib_rwq *rwq) { struct mlx5_ib_ucontext *context; if (rwq->create_flags & MLX5_IB_WQ_FLAGS_DELAY_DROP) atomic_dec(&dev->delay_drop.rqs_cnt); context = to_mucontext(pd->uobject->context); mlx5_ib_db_unmap_user(context, &rwq->db); if (rwq->umem) ib_umem_release(rwq->umem); } static int create_user_rq(struct mlx5_ib_dev *dev, struct ib_pd *pd, struct mlx5_ib_rwq *rwq, struct mlx5_ib_create_wq *ucmd) { struct mlx5_ib_ucontext *context; int page_shift = 0; int npages; u32 offset = 0; int ncont = 0; int err; if (!ucmd->buf_addr) return -EINVAL; context = to_mucontext(pd->uobject->context); rwq->umem = ib_umem_get(pd->uobject->context, ucmd->buf_addr, rwq->buf_size, 0, 0); if (IS_ERR(rwq->umem)) { mlx5_ib_dbg(dev, "umem_get failed\n"); err = PTR_ERR(rwq->umem); return err; } mlx5_ib_cont_pages(rwq->umem, ucmd->buf_addr, 0, &npages, &page_shift, &ncont, NULL); err = mlx5_ib_get_buf_offset(ucmd->buf_addr, page_shift, &rwq->rq_page_offset); if (err) { mlx5_ib_warn(dev, "bad offset\n"); goto err_umem; } rwq->rq_num_pas = ncont; rwq->page_shift = page_shift; rwq->log_page_size = page_shift - MLX5_ADAPTER_PAGE_SHIFT; rwq->wq_sig = !!(ucmd->flags & MLX5_WQ_FLAG_SIGNATURE); mlx5_ib_dbg(dev, "addr 0x%llx, size %zd, npages %d, page_shift %d, ncont %d, offset %d\n", (unsigned long long)ucmd->buf_addr, rwq->buf_size, npages, page_shift, ncont, offset); err = mlx5_ib_db_map_user(context, ucmd->db_addr, &rwq->db); if (err) { mlx5_ib_dbg(dev, "map failed\n"); goto err_umem; } rwq->create_type = MLX5_WQ_USER; return 0; err_umem: ib_umem_release(rwq->umem); return err; } static int adjust_bfregn(struct mlx5_ib_dev *dev, struct mlx5_bfreg_info *bfregi, int bfregn) { return bfregn / MLX5_NON_FP_BFREGS_PER_UAR * MLX5_BFREGS_PER_UAR + bfregn % MLX5_NON_FP_BFREGS_PER_UAR; } static int create_user_qp(struct mlx5_ib_dev *dev, struct ib_pd *pd, struct mlx5_ib_qp *qp, struct ib_udata *udata, struct ib_qp_init_attr *attr, u32 **in, struct mlx5_ib_create_qp_resp *resp, int *inlen, struct mlx5_ib_qp_base *base) { struct mlx5_ib_ucontext *context; struct mlx5_ib_create_qp ucmd; struct mlx5_ib_ubuffer *ubuffer = &base->ubuffer; int page_shift = 0; int uar_index = 0; int npages; u32 offset = 0; int bfregn; int ncont = 0; __be64 *pas; void *qpc; int err; err = ib_copy_from_udata(&ucmd, udata, sizeof(ucmd)); if (err) { mlx5_ib_dbg(dev, "copy failed\n"); return err; } context = to_mucontext(pd->uobject->context); if (ucmd.flags & MLX5_QP_FLAG_BFREG_INDEX) { uar_index = bfregn_to_uar_index(dev, &context->bfregi, ucmd.bfreg_index, true); if (uar_index < 0) return uar_index; bfregn = MLX5_IB_INVALID_BFREG; } else if (qp->flags & MLX5_IB_QP_CROSS_CHANNEL) { /* * TBD: should come from the verbs when we have the API */ /* In CROSS_CHANNEL CQ and QP must use the same UAR */ bfregn = MLX5_CROSS_CHANNEL_BFREG; } else { bfregn = alloc_bfreg(dev, &context->bfregi); if (bfregn < 0) return bfregn; } mlx5_ib_dbg(dev, "bfregn 0x%x, uar_index 0x%x\n", bfregn, uar_index); if (bfregn != MLX5_IB_INVALID_BFREG) uar_index = bfregn_to_uar_index(dev, &context->bfregi, bfregn, false); qp->rq.offset = 0; qp->sq.wqe_shift = ilog2(MLX5_SEND_WQE_BB); qp->sq.offset = qp->rq.wqe_cnt << qp->rq.wqe_shift; err = set_user_buf_size(dev, qp, &ucmd, base, attr); if (err) goto err_bfreg; if (ucmd.buf_addr && ubuffer->buf_size) { ubuffer->buf_addr = ucmd.buf_addr; err = mlx5_ib_umem_get(dev, pd, ubuffer->buf_addr, ubuffer->buf_size, &ubuffer->umem, &npages, &page_shift, &ncont, &offset); if (err) goto err_bfreg; } else { ubuffer->umem = NULL; } *inlen = MLX5_ST_SZ_BYTES(create_qp_in) + MLX5_FLD_SZ_BYTES(create_qp_in, pas[0]) * ncont; *in = kvzalloc(*inlen, GFP_KERNEL); if (!*in) { err = -ENOMEM; goto err_umem; } pas = (__be64 *)MLX5_ADDR_OF(create_qp_in, *in, pas); if (ubuffer->umem) mlx5_ib_populate_pas(dev, ubuffer->umem, page_shift, pas, 0); qpc = MLX5_ADDR_OF(create_qp_in, *in, qpc); MLX5_SET(qpc, qpc, log_page_size, page_shift - MLX5_ADAPTER_PAGE_SHIFT); MLX5_SET(qpc, qpc, page_offset, offset); MLX5_SET(qpc, qpc, uar_page, uar_index); if (bfregn != MLX5_IB_INVALID_BFREG) resp->bfreg_index = adjust_bfregn(dev, &context->bfregi, bfregn); else resp->bfreg_index = MLX5_IB_INVALID_BFREG; qp->bfregn = bfregn; err = mlx5_ib_db_map_user(context, ucmd.db_addr, &qp->db); if (err) { mlx5_ib_dbg(dev, "map failed\n"); goto err_free; } err = ib_copy_to_udata(udata, resp, min(udata->outlen, sizeof(*resp))); if (err) { mlx5_ib_dbg(dev, "copy failed\n"); goto err_unmap; } qp->create_type = MLX5_QP_USER; return 0; err_unmap: mlx5_ib_db_unmap_user(context, &qp->db); err_free: kvfree(*in); err_umem: if (ubuffer->umem) ib_umem_release(ubuffer->umem); err_bfreg: if (bfregn != MLX5_IB_INVALID_BFREG) mlx5_ib_free_bfreg(dev, &context->bfregi, bfregn); return err; } static void destroy_qp_user(struct mlx5_ib_dev *dev, struct ib_pd *pd, struct mlx5_ib_qp *qp, struct mlx5_ib_qp_base *base) { struct mlx5_ib_ucontext *context; context = to_mucontext(pd->uobject->context); mlx5_ib_db_unmap_user(context, &qp->db); if (base->ubuffer.umem) ib_umem_release(base->ubuffer.umem); /* * Free only the BFREGs which are handled by the kernel. * BFREGs of UARs allocated dynamically are handled by user. */ if (qp->bfregn != MLX5_IB_INVALID_BFREG) mlx5_ib_free_bfreg(dev, &context->bfregi, qp->bfregn); } static int create_kernel_qp(struct mlx5_ib_dev *dev, struct ib_qp_init_attr *init_attr, struct mlx5_ib_qp *qp, u32 **in, int *inlen, struct mlx5_ib_qp_base *base) { int uar_index; void *qpc; int err; if (init_attr->create_flags & ~(IB_QP_CREATE_SIGNATURE_EN | IB_QP_CREATE_BLOCK_MULTICAST_LOOPBACK | IB_QP_CREATE_IPOIB_UD_LSO | IB_QP_CREATE_NETIF_QP | mlx5_ib_create_qp_sqpn_qp1())) return -EINVAL; if (init_attr->qp_type == MLX5_IB_QPT_REG_UMR) qp->bf.bfreg = &dev->fp_bfreg; else qp->bf.bfreg = &dev->bfreg; /* We need to divide by two since each register is comprised of * two buffers of identical size, namely odd and even */ qp->bf.buf_size = (1 << MLX5_CAP_GEN(dev->mdev, log_bf_reg_size)) / 2; uar_index = qp->bf.bfreg->index; err = calc_sq_size(dev, init_attr, qp); if (err < 0) { mlx5_ib_dbg(dev, "err %d\n", err); return err; } qp->rq.offset = 0; qp->sq.offset = qp->rq.wqe_cnt << qp->rq.wqe_shift; base->ubuffer.buf_size = err + (qp->rq.wqe_cnt << qp->rq.wqe_shift); err = mlx5_buf_alloc(dev->mdev, base->ubuffer.buf_size, &qp->buf); if (err) { mlx5_ib_dbg(dev, "err %d\n", err); return err; } qp->sq.qend = mlx5_get_send_wqe(qp, qp->sq.wqe_cnt); *inlen = MLX5_ST_SZ_BYTES(create_qp_in) + MLX5_FLD_SZ_BYTES(create_qp_in, pas[0]) * qp->buf.npages; *in = kvzalloc(*inlen, GFP_KERNEL); if (!*in) { err = -ENOMEM; goto err_buf; } qpc = MLX5_ADDR_OF(create_qp_in, *in, qpc); MLX5_SET(qpc, qpc, uar_page, uar_index); MLX5_SET(qpc, qpc, log_page_size, qp->buf.page_shift - MLX5_ADAPTER_PAGE_SHIFT); /* Set "fast registration enabled" for all kernel QPs */ MLX5_SET(qpc, qpc, fre, 1); MLX5_SET(qpc, qpc, rlky, 1); if (init_attr->create_flags & mlx5_ib_create_qp_sqpn_qp1()) { MLX5_SET(qpc, qpc, deth_sqpn, 1); qp->flags |= MLX5_IB_QP_SQPN_QP1; } mlx5_fill_page_array(&qp->buf, (__be64 *)MLX5_ADDR_OF(create_qp_in, *in, pas)); err = mlx5_db_alloc(dev->mdev, &qp->db); if (err) { mlx5_ib_dbg(dev, "err %d\n", err); goto err_free; } qp->sq.wrid = kvmalloc_array(qp->sq.wqe_cnt, sizeof(*qp->sq.wrid), GFP_KERNEL); qp->sq.wr_data = kvmalloc_array(qp->sq.wqe_cnt, sizeof(*qp->sq.wr_data), GFP_KERNEL); qp->rq.wrid = kvmalloc_array(qp->rq.wqe_cnt, sizeof(*qp->rq.wrid), GFP_KERNEL); qp->sq.w_list = kvmalloc_array(qp->sq.wqe_cnt, sizeof(*qp->sq.w_list), GFP_KERNEL); qp->sq.wqe_head = kvmalloc_array(qp->sq.wqe_cnt, sizeof(*qp->sq.wqe_head), GFP_KERNEL); if (!qp->sq.wrid || !qp->sq.wr_data || !qp->rq.wrid || !qp->sq.w_list || !qp->sq.wqe_head) { err = -ENOMEM; goto err_wrid; } qp->create_type = MLX5_QP_KERNEL; return 0; err_wrid: kvfree(qp->sq.wqe_head); kvfree(qp->sq.w_list); kvfree(qp->sq.wrid); kvfree(qp->sq.wr_data); kvfree(qp->rq.wrid); mlx5_db_free(dev->mdev, &qp->db); err_free: kvfree(*in); err_buf: mlx5_buf_free(dev->mdev, &qp->buf); return err; } static void destroy_qp_kernel(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *qp) { kvfree(qp->sq.wqe_head); kvfree(qp->sq.w_list); kvfree(qp->sq.wrid); kvfree(qp->sq.wr_data); kvfree(qp->rq.wrid); mlx5_db_free(dev->mdev, &qp->db); mlx5_buf_free(dev->mdev, &qp->buf); } static u32 get_rx_type(struct mlx5_ib_qp *qp, struct ib_qp_init_attr *attr) { if (attr->srq || (attr->qp_type == IB_QPT_XRC_TGT) || (attr->qp_type == MLX5_IB_QPT_DCI) || (attr->qp_type == IB_QPT_XRC_INI)) return MLX5_SRQ_RQ; else if (!qp->has_rq) return MLX5_ZERO_LEN_RQ; else return MLX5_NON_ZERO_RQ; } static int is_connected(enum ib_qp_type qp_type) { if (qp_type == IB_QPT_RC || qp_type == IB_QPT_UC) return 1; return 0; } static int create_raw_packet_qp_tis(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *qp, struct mlx5_ib_sq *sq, u32 tdn) { u32 in[MLX5_ST_SZ_DW(create_tis_in)] = {0}; void *tisc = MLX5_ADDR_OF(create_tis_in, in, ctx); MLX5_SET(tisc, tisc, transport_domain, tdn); if (qp->flags & MLX5_IB_QP_UNDERLAY) MLX5_SET(tisc, tisc, underlay_qpn, qp->underlay_qpn); return mlx5_core_create_tis(dev->mdev, in, sizeof(in), &sq->tisn); } static void destroy_raw_packet_qp_tis(struct mlx5_ib_dev *dev, struct mlx5_ib_sq *sq) { mlx5_core_destroy_tis(dev->mdev, sq->tisn); } static void destroy_flow_rule_vport_sq(struct mlx5_ib_dev *dev, struct mlx5_ib_sq *sq) { if (sq->flow_rule) mlx5_del_flow_rules(sq->flow_rule); } static int create_raw_packet_qp_sq(struct mlx5_ib_dev *dev, struct mlx5_ib_sq *sq, void *qpin, struct ib_pd *pd) { struct mlx5_ib_ubuffer *ubuffer = &sq->ubuffer; __be64 *pas; void *in; void *sqc; void *qpc = MLX5_ADDR_OF(create_qp_in, qpin, qpc); void *wq; int inlen; int err; int page_shift = 0; int npages; int ncont = 0; u32 offset = 0; err = mlx5_ib_umem_get(dev, pd, ubuffer->buf_addr, ubuffer->buf_size, &sq->ubuffer.umem, &npages, &page_shift, &ncont, &offset); if (err) return err; inlen = MLX5_ST_SZ_BYTES(create_sq_in) + sizeof(u64) * ncont; in = kvzalloc(inlen, GFP_KERNEL); if (!in) { err = -ENOMEM; goto err_umem; } sqc = MLX5_ADDR_OF(create_sq_in, in, ctx); MLX5_SET(sqc, sqc, flush_in_error_en, 1); if (MLX5_CAP_ETH(dev->mdev, multi_pkt_send_wqe)) MLX5_SET(sqc, sqc, allow_multi_pkt_send_wqe, 1); MLX5_SET(sqc, sqc, state, MLX5_SQC_STATE_RST); MLX5_SET(sqc, sqc, user_index, MLX5_GET(qpc, qpc, user_index)); MLX5_SET(sqc, sqc, cqn, MLX5_GET(qpc, qpc, cqn_snd)); MLX5_SET(sqc, sqc, tis_lst_sz, 1); MLX5_SET(sqc, sqc, tis_num_0, sq->tisn); if (MLX5_CAP_GEN(dev->mdev, eth_net_offloads) && MLX5_CAP_ETH(dev->mdev, swp)) MLX5_SET(sqc, sqc, allow_swp, 1); wq = MLX5_ADDR_OF(sqc, sqc, wq); MLX5_SET(wq, wq, wq_type, MLX5_WQ_TYPE_CYCLIC); MLX5_SET(wq, wq, pd, MLX5_GET(qpc, qpc, pd)); MLX5_SET(wq, wq, uar_page, MLX5_GET(qpc, qpc, uar_page)); MLX5_SET64(wq, wq, dbr_addr, MLX5_GET64(qpc, qpc, dbr_addr)); MLX5_SET(wq, wq, log_wq_stride, ilog2(MLX5_SEND_WQE_BB)); MLX5_SET(wq, wq, log_wq_sz, MLX5_GET(qpc, qpc, log_sq_size)); MLX5_SET(wq, wq, log_wq_pg_sz, page_shift - MLX5_ADAPTER_PAGE_SHIFT); MLX5_SET(wq, wq, page_offset, offset); pas = (__be64 *)MLX5_ADDR_OF(wq, wq, pas); mlx5_ib_populate_pas(dev, sq->ubuffer.umem, page_shift, pas, 0); err = mlx5_core_create_sq_tracked(dev->mdev, in, inlen, &sq->base.mqp); kvfree(in); if (err) goto err_umem; err = create_flow_rule_vport_sq(dev, sq); if (err) goto err_flow; return 0; err_flow: mlx5_core_destroy_sq_tracked(dev->mdev, &sq->base.mqp); err_umem: ib_umem_release(sq->ubuffer.umem); sq->ubuffer.umem = NULL; return err; } static void destroy_raw_packet_qp_sq(struct mlx5_ib_dev *dev, struct mlx5_ib_sq *sq) { destroy_flow_rule_vport_sq(dev, sq); mlx5_core_destroy_sq_tracked(dev->mdev, &sq->base.mqp); ib_umem_release(sq->ubuffer.umem); } static size_t get_rq_pas_size(void *qpc) { u32 log_page_size = MLX5_GET(qpc, qpc, log_page_size) + 12; u32 log_rq_stride = MLX5_GET(qpc, qpc, log_rq_stride); u32 log_rq_size = MLX5_GET(qpc, qpc, log_rq_size); u32 page_offset = MLX5_GET(qpc, qpc, page_offset); u32 po_quanta = 1 << (log_page_size - 6); u32 rq_sz = 1 << (log_rq_size + 4 + log_rq_stride); u32 page_size = 1 << log_page_size; u32 rq_sz_po = rq_sz + (page_offset * po_quanta); u32 rq_num_pas = (rq_sz_po + page_size - 1) / page_size; return rq_num_pas * sizeof(u64); } static int create_raw_packet_qp_rq(struct mlx5_ib_dev *dev, struct mlx5_ib_rq *rq, void *qpin, size_t qpinlen) { struct mlx5_ib_qp *mqp = rq->base.container_mibqp; __be64 *pas; __be64 *qp_pas; void *in; void *rqc; void *wq; void *qpc = MLX5_ADDR_OF(create_qp_in, qpin, qpc); size_t rq_pas_size = get_rq_pas_size(qpc); size_t inlen; int err; if (qpinlen < rq_pas_size + MLX5_BYTE_OFF(create_qp_in, pas)) return -EINVAL; inlen = MLX5_ST_SZ_BYTES(create_rq_in) + rq_pas_size; in = kvzalloc(inlen, GFP_KERNEL); if (!in) return -ENOMEM; rqc = MLX5_ADDR_OF(create_rq_in, in, ctx); if (!(rq->flags & MLX5_IB_RQ_CVLAN_STRIPPING)) MLX5_SET(rqc, rqc, vsd, 1); MLX5_SET(rqc, rqc, mem_rq_type, MLX5_RQC_MEM_RQ_TYPE_MEMORY_RQ_INLINE); MLX5_SET(rqc, rqc, state, MLX5_RQC_STATE_RST); MLX5_SET(rqc, rqc, flush_in_error_en, 1); MLX5_SET(rqc, rqc, user_index, MLX5_GET(qpc, qpc, user_index)); MLX5_SET(rqc, rqc, cqn, MLX5_GET(qpc, qpc, cqn_rcv)); if (mqp->flags & MLX5_IB_QP_CAP_SCATTER_FCS) MLX5_SET(rqc, rqc, scatter_fcs, 1); wq = MLX5_ADDR_OF(rqc, rqc, wq); MLX5_SET(wq, wq, wq_type, MLX5_WQ_TYPE_CYCLIC); if (rq->flags & MLX5_IB_RQ_PCI_WRITE_END_PADDING) MLX5_SET(wq, wq, end_padding_mode, MLX5_WQ_END_PAD_MODE_ALIGN); MLX5_SET(wq, wq, page_offset, MLX5_GET(qpc, qpc, page_offset)); MLX5_SET(wq, wq, pd, MLX5_GET(qpc, qpc, pd)); MLX5_SET64(wq, wq, dbr_addr, MLX5_GET64(qpc, qpc, dbr_addr)); MLX5_SET(wq, wq, log_wq_stride, MLX5_GET(qpc, qpc, log_rq_stride) + 4); MLX5_SET(wq, wq, log_wq_pg_sz, MLX5_GET(qpc, qpc, log_page_size)); MLX5_SET(wq, wq, log_wq_sz, MLX5_GET(qpc, qpc, log_rq_size)); pas = (__be64 *)MLX5_ADDR_OF(wq, wq, pas); qp_pas = (__be64 *)MLX5_ADDR_OF(create_qp_in, qpin, pas); memcpy(pas, qp_pas, rq_pas_size); err = mlx5_core_create_rq_tracked(dev->mdev, in, inlen, &rq->base.mqp); kvfree(in); return err; } static void destroy_raw_packet_qp_rq(struct mlx5_ib_dev *dev, struct mlx5_ib_rq *rq) { mlx5_core_destroy_rq_tracked(dev->mdev, &rq->base.mqp); } static bool tunnel_offload_supported(struct mlx5_core_dev *dev) { return (MLX5_CAP_ETH(dev, tunnel_stateless_vxlan) || MLX5_CAP_ETH(dev, tunnel_stateless_gre) || MLX5_CAP_ETH(dev, tunnel_stateless_geneve_rx)); } static int create_raw_packet_qp_tir(struct mlx5_ib_dev *dev, struct mlx5_ib_rq *rq, u32 tdn, bool tunnel_offload_en) { u32 *in; void *tirc; int inlen; int err; inlen = MLX5_ST_SZ_BYTES(create_tir_in); in = kvzalloc(inlen, GFP_KERNEL); if (!in) return -ENOMEM; tirc = MLX5_ADDR_OF(create_tir_in, in, ctx); MLX5_SET(tirc, tirc, disp_type, MLX5_TIRC_DISP_TYPE_DIRECT); MLX5_SET(tirc, tirc, inline_rqn, rq->base.mqp.qpn); MLX5_SET(tirc, tirc, transport_domain, tdn); if (tunnel_offload_en) MLX5_SET(tirc, tirc, tunneled_offload_en, 1); if (dev->rep) MLX5_SET(tirc, tirc, self_lb_block, MLX5_TIRC_SELF_LB_BLOCK_BLOCK_UNICAST_); err = mlx5_core_create_tir(dev->mdev, in, inlen, &rq->tirn); kvfree(in); return err; } static void destroy_raw_packet_qp_tir(struct mlx5_ib_dev *dev, struct mlx5_ib_rq *rq) { mlx5_core_destroy_tir(dev->mdev, rq->tirn); } static int create_raw_packet_qp(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *qp, u32 *in, size_t inlen, struct ib_pd *pd) { struct mlx5_ib_raw_packet_qp *raw_packet_qp = &qp->raw_packet_qp; struct mlx5_ib_sq *sq = &raw_packet_qp->sq; struct mlx5_ib_rq *rq = &raw_packet_qp->rq; struct ib_uobject *uobj = pd->uobject; struct ib_ucontext *ucontext = uobj->context; struct mlx5_ib_ucontext *mucontext = to_mucontext(ucontext); int err; u32 tdn = mucontext->tdn; if (qp->sq.wqe_cnt) { err = create_raw_packet_qp_tis(dev, qp, sq, tdn); if (err) return err; err = create_raw_packet_qp_sq(dev, sq, in, pd); if (err) goto err_destroy_tis; sq->base.container_mibqp = qp; sq->base.mqp.event = mlx5_ib_qp_event; } if (qp->rq.wqe_cnt) { rq->base.container_mibqp = qp; if (qp->flags & MLX5_IB_QP_CVLAN_STRIPPING) rq->flags |= MLX5_IB_RQ_CVLAN_STRIPPING; if (qp->flags & MLX5_IB_QP_PCI_WRITE_END_PADDING) rq->flags |= MLX5_IB_RQ_PCI_WRITE_END_PADDING; err = create_raw_packet_qp_rq(dev, rq, in, inlen); if (err) goto err_destroy_sq; err = create_raw_packet_qp_tir(dev, rq, tdn, qp->tunnel_offload_en); if (err) goto err_destroy_rq; } qp->trans_qp.base.mqp.qpn = qp->sq.wqe_cnt ? sq->base.mqp.qpn : rq->base.mqp.qpn; return 0; err_destroy_rq: destroy_raw_packet_qp_rq(dev, rq); err_destroy_sq: if (!qp->sq.wqe_cnt) return err; destroy_raw_packet_qp_sq(dev, sq); err_destroy_tis: destroy_raw_packet_qp_tis(dev, sq); return err; } static void destroy_raw_packet_qp(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *qp) { struct mlx5_ib_raw_packet_qp *raw_packet_qp = &qp->raw_packet_qp; struct mlx5_ib_sq *sq = &raw_packet_qp->sq; struct mlx5_ib_rq *rq = &raw_packet_qp->rq; if (qp->rq.wqe_cnt) { destroy_raw_packet_qp_tir(dev, rq); destroy_raw_packet_qp_rq(dev, rq); } if (qp->sq.wqe_cnt) { destroy_raw_packet_qp_sq(dev, sq); destroy_raw_packet_qp_tis(dev, sq); } } static void raw_packet_qp_copy_info(struct mlx5_ib_qp *qp, struct mlx5_ib_raw_packet_qp *raw_packet_qp) { struct mlx5_ib_sq *sq = &raw_packet_qp->sq; struct mlx5_ib_rq *rq = &raw_packet_qp->rq; sq->sq = &qp->sq; rq->rq = &qp->rq; sq->doorbell = &qp->db; rq->doorbell = &qp->db; } static void destroy_rss_raw_qp_tir(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *qp) { mlx5_core_destroy_tir(dev->mdev, qp->rss_qp.tirn); } static int create_rss_raw_qp_tir(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *qp, struct ib_pd *pd, struct ib_qp_init_attr *init_attr, struct ib_udata *udata) { struct ib_uobject *uobj = pd->uobject; struct ib_ucontext *ucontext = uobj->context; struct mlx5_ib_ucontext *mucontext = to_mucontext(ucontext); struct mlx5_ib_create_qp_resp resp = {}; int inlen; int err; u32 *in; void *tirc; void *hfso; u32 selected_fields = 0; u32 outer_l4; size_t min_resp_len; u32 tdn = mucontext->tdn; struct mlx5_ib_create_qp_rss ucmd = {}; size_t required_cmd_sz; if (init_attr->qp_type != IB_QPT_RAW_PACKET) return -EOPNOTSUPP; if (init_attr->create_flags || init_attr->send_cq) return -EINVAL; min_resp_len = offsetof(typeof(resp), bfreg_index) + sizeof(resp.bfreg_index); if (udata->outlen < min_resp_len) return -EINVAL; required_cmd_sz = offsetof(typeof(ucmd), flags) + sizeof(ucmd.flags); if (udata->inlen < required_cmd_sz) { mlx5_ib_dbg(dev, "invalid inlen\n"); return -EINVAL; } if (udata->inlen > sizeof(ucmd) && !ib_is_udata_cleared(udata, sizeof(ucmd), udata->inlen - sizeof(ucmd))) { mlx5_ib_dbg(dev, "inlen is not supported\n"); return -EOPNOTSUPP; } if (ib_copy_from_udata(&ucmd, udata, min(sizeof(ucmd), udata->inlen))) { mlx5_ib_dbg(dev, "copy failed\n"); return -EFAULT; } if (ucmd.comp_mask) { mlx5_ib_dbg(dev, "invalid comp mask\n"); return -EOPNOTSUPP; } if (ucmd.flags & ~MLX5_QP_FLAG_TUNNEL_OFFLOADS) { mlx5_ib_dbg(dev, "invalid flags\n"); return -EOPNOTSUPP; } if (ucmd.flags & MLX5_QP_FLAG_TUNNEL_OFFLOADS && !tunnel_offload_supported(dev->mdev)) { mlx5_ib_dbg(dev, "tunnel offloads isn't supported\n"); return -EOPNOTSUPP; } if (ucmd.rx_hash_fields_mask & MLX5_RX_HASH_INNER && !(ucmd.flags & MLX5_QP_FLAG_TUNNEL_OFFLOADS)) { mlx5_ib_dbg(dev, "Tunnel offloads must be set for inner RSS\n"); return -EOPNOTSUPP; } err = ib_copy_to_udata(udata, &resp, min(udata->outlen, sizeof(resp))); if (err) { mlx5_ib_dbg(dev, "copy failed\n"); return -EINVAL; } inlen = MLX5_ST_SZ_BYTES(create_tir_in); in = kvzalloc(inlen, GFP_KERNEL); if (!in) return -ENOMEM; tirc = MLX5_ADDR_OF(create_tir_in, in, ctx); MLX5_SET(tirc, tirc, disp_type, MLX5_TIRC_DISP_TYPE_INDIRECT); MLX5_SET(tirc, tirc, indirect_table, init_attr->rwq_ind_tbl->ind_tbl_num); MLX5_SET(tirc, tirc, transport_domain, tdn); hfso = MLX5_ADDR_OF(tirc, tirc, rx_hash_field_selector_outer); if (ucmd.flags & MLX5_QP_FLAG_TUNNEL_OFFLOADS) MLX5_SET(tirc, tirc, tunneled_offload_en, 1); if (ucmd.rx_hash_fields_mask & MLX5_RX_HASH_INNER) hfso = MLX5_ADDR_OF(tirc, tirc, rx_hash_field_selector_inner); else hfso = MLX5_ADDR_OF(tirc, tirc, rx_hash_field_selector_outer); switch (ucmd.rx_hash_function) { case MLX5_RX_HASH_FUNC_TOEPLITZ: { void *rss_key = MLX5_ADDR_OF(tirc, tirc, rx_hash_toeplitz_key); size_t len = MLX5_FLD_SZ_BYTES(tirc, rx_hash_toeplitz_key); if (len != ucmd.rx_key_len) { err = -EINVAL; goto err; } MLX5_SET(tirc, tirc, rx_hash_fn, MLX5_RX_HASH_FN_TOEPLITZ); MLX5_SET(tirc, tirc, rx_hash_symmetric, 1); memcpy(rss_key, ucmd.rx_hash_key, len); break; } default: err = -EOPNOTSUPP; goto err; } if (!ucmd.rx_hash_fields_mask) { /* special case when this TIR serves as steering entry without hashing */ if (!init_attr->rwq_ind_tbl->log_ind_tbl_size) goto create_tir; err = -EINVAL; goto err; } if (((ucmd.rx_hash_fields_mask & MLX5_RX_HASH_SRC_IPV4) || (ucmd.rx_hash_fields_mask & MLX5_RX_HASH_DST_IPV4)) && ((ucmd.rx_hash_fields_mask & MLX5_RX_HASH_SRC_IPV6) || (ucmd.rx_hash_fields_mask & MLX5_RX_HASH_DST_IPV6))) { err = -EINVAL; goto err; } /* If none of IPV4 & IPV6 SRC/DST was set - this bit field is ignored */ if ((ucmd.rx_hash_fields_mask & MLX5_RX_HASH_SRC_IPV4) || (ucmd.rx_hash_fields_mask & MLX5_RX_HASH_DST_IPV4)) MLX5_SET(rx_hash_field_select, hfso, l3_prot_type, MLX5_L3_PROT_TYPE_IPV4); else if ((ucmd.rx_hash_fields_mask & MLX5_RX_HASH_SRC_IPV6) || (ucmd.rx_hash_fields_mask & MLX5_RX_HASH_DST_IPV6)) MLX5_SET(rx_hash_field_select, hfso, l3_prot_type, MLX5_L3_PROT_TYPE_IPV6); outer_l4 = ((ucmd.rx_hash_fields_mask & MLX5_RX_HASH_SRC_PORT_TCP) || (ucmd.rx_hash_fields_mask & MLX5_RX_HASH_DST_PORT_TCP)) << 0 | ((ucmd.rx_hash_fields_mask & MLX5_RX_HASH_SRC_PORT_UDP) || (ucmd.rx_hash_fields_mask & MLX5_RX_HASH_DST_PORT_UDP)) << 1 | (ucmd.rx_hash_fields_mask & MLX5_RX_HASH_IPSEC_SPI) << 2; /* Check that only one l4 protocol is set */ if (outer_l4 & (outer_l4 - 1)) { err = -EINVAL; goto err; } /* If none of TCP & UDP SRC/DST was set - this bit field is ignored */ if ((ucmd.rx_hash_fields_mask & MLX5_RX_HASH_SRC_PORT_TCP) || (ucmd.rx_hash_fields_mask & MLX5_RX_HASH_DST_PORT_TCP)) MLX5_SET(rx_hash_field_select, hfso, l4_prot_type, MLX5_L4_PROT_TYPE_TCP); else if ((ucmd.rx_hash_fields_mask & MLX5_RX_HASH_SRC_PORT_UDP) || (ucmd.rx_hash_fields_mask & MLX5_RX_HASH_DST_PORT_UDP)) MLX5_SET(rx_hash_field_select, hfso, l4_prot_type, MLX5_L4_PROT_TYPE_UDP); if ((ucmd.rx_hash_fields_mask & MLX5_RX_HASH_SRC_IPV4) || (ucmd.rx_hash_fields_mask & MLX5_RX_HASH_SRC_IPV6)) selected_fields |= MLX5_HASH_FIELD_SEL_SRC_IP; if ((ucmd.rx_hash_fields_mask & MLX5_RX_HASH_DST_IPV4) || (ucmd.rx_hash_fields_mask & MLX5_RX_HASH_DST_IPV6)) selected_fields |= MLX5_HASH_FIELD_SEL_DST_IP; if ((ucmd.rx_hash_fields_mask & MLX5_RX_HASH_SRC_PORT_TCP) || (ucmd.rx_hash_fields_mask & MLX5_RX_HASH_SRC_PORT_UDP)) selected_fields |= MLX5_HASH_FIELD_SEL_L4_SPORT; if ((ucmd.rx_hash_fields_mask & MLX5_RX_HASH_DST_PORT_TCP) || (ucmd.rx_hash_fields_mask & MLX5_RX_HASH_DST_PORT_UDP)) selected_fields |= MLX5_HASH_FIELD_SEL_L4_DPORT; if (ucmd.rx_hash_fields_mask & MLX5_RX_HASH_IPSEC_SPI) selected_fields |= MLX5_HASH_FIELD_SEL_IPSEC_SPI; MLX5_SET(rx_hash_field_select, hfso, selected_fields, selected_fields); create_tir: if (dev->rep) MLX5_SET(tirc, tirc, self_lb_block, MLX5_TIRC_SELF_LB_BLOCK_BLOCK_UNICAST_); err = mlx5_core_create_tir(dev->mdev, in, inlen, &qp->rss_qp.tirn); if (err) goto err; kvfree(in); /* qpn is reserved for that QP */ qp->trans_qp.base.mqp.qpn = 0; qp->flags |= MLX5_IB_QP_RSS; return 0; err: kvfree(in); return err; } static int create_qp_common(struct mlx5_ib_dev *dev, struct ib_pd *pd, struct ib_qp_init_attr *init_attr, struct ib_udata *udata, struct mlx5_ib_qp *qp) { struct mlx5_ib_resources *devr = &dev->devr; int inlen = MLX5_ST_SZ_BYTES(create_qp_in); struct mlx5_core_dev *mdev = dev->mdev; struct mlx5_ib_create_qp_resp resp; struct mlx5_ib_cq *send_cq; struct mlx5_ib_cq *recv_cq; unsigned long flags; u32 uidx = MLX5_IB_DEFAULT_UIDX; struct mlx5_ib_create_qp ucmd; struct mlx5_ib_qp_base *base; int mlx5_st; void *qpc; u32 *in; int err; mutex_init(&qp->mutex); spin_lock_init(&qp->sq.lock); spin_lock_init(&qp->rq.lock); mlx5_st = to_mlx5_st(init_attr->qp_type); if (mlx5_st < 0) return -EINVAL; if (init_attr->rwq_ind_tbl) { if (!udata) return -ENOSYS; err = create_rss_raw_qp_tir(dev, qp, pd, init_attr, udata); return err; } if (init_attr->create_flags & IB_QP_CREATE_BLOCK_MULTICAST_LOOPBACK) { if (!MLX5_CAP_GEN(mdev, block_lb_mc)) { mlx5_ib_dbg(dev, "block multicast loopback isn't supported\n"); return -EINVAL; } else { qp->flags |= MLX5_IB_QP_BLOCK_MULTICAST_LOOPBACK; } } if (init_attr->create_flags & (IB_QP_CREATE_CROSS_CHANNEL | IB_QP_CREATE_MANAGED_SEND | IB_QP_CREATE_MANAGED_RECV)) { if (!MLX5_CAP_GEN(mdev, cd)) { mlx5_ib_dbg(dev, "cross-channel isn't supported\n"); return -EINVAL; } if (init_attr->create_flags & IB_QP_CREATE_CROSS_CHANNEL) qp->flags |= MLX5_IB_QP_CROSS_CHANNEL; if (init_attr->create_flags & IB_QP_CREATE_MANAGED_SEND) qp->flags |= MLX5_IB_QP_MANAGED_SEND; if (init_attr->create_flags & IB_QP_CREATE_MANAGED_RECV) qp->flags |= MLX5_IB_QP_MANAGED_RECV; } if (init_attr->qp_type == IB_QPT_UD && (init_attr->create_flags & IB_QP_CREATE_IPOIB_UD_LSO)) if (!MLX5_CAP_GEN(mdev, ipoib_basic_offloads)) { mlx5_ib_dbg(dev, "ipoib UD lso qp isn't supported\n"); return -EOPNOTSUPP; } if (init_attr->create_flags & IB_QP_CREATE_SCATTER_FCS) { if (init_attr->qp_type != IB_QPT_RAW_PACKET) { mlx5_ib_dbg(dev, "Scatter FCS is supported only for Raw Packet QPs"); return -EOPNOTSUPP; } if (!MLX5_CAP_GEN(dev->mdev, eth_net_offloads) || !MLX5_CAP_ETH(dev->mdev, scatter_fcs)) { mlx5_ib_dbg(dev, "Scatter FCS isn't supported\n"); return -EOPNOTSUPP; } qp->flags |= MLX5_IB_QP_CAP_SCATTER_FCS; } if (init_attr->sq_sig_type == IB_SIGNAL_ALL_WR) qp->sq_signal_bits = MLX5_WQE_CTRL_CQ_UPDATE; if (init_attr->create_flags & IB_QP_CREATE_CVLAN_STRIPPING) { if (!(MLX5_CAP_GEN(dev->mdev, eth_net_offloads) && MLX5_CAP_ETH(dev->mdev, vlan_cap)) || (init_attr->qp_type != IB_QPT_RAW_PACKET)) return -EOPNOTSUPP; qp->flags |= MLX5_IB_QP_CVLAN_STRIPPING; } if (pd && pd->uobject) { if (ib_copy_from_udata(&ucmd, udata, sizeof(ucmd))) { mlx5_ib_dbg(dev, "copy failed\n"); return -EFAULT; } err = get_qp_user_index(to_mucontext(pd->uobject->context), &ucmd, udata->inlen, &uidx); if (err) return err; qp->wq_sig = !!(ucmd.flags & MLX5_QP_FLAG_SIGNATURE); qp->scat_cqe = !!(ucmd.flags & MLX5_QP_FLAG_SCATTER_CQE); if (ucmd.flags & MLX5_QP_FLAG_TUNNEL_OFFLOADS) { if (init_attr->qp_type != IB_QPT_RAW_PACKET || !tunnel_offload_supported(mdev)) { mlx5_ib_dbg(dev, "Tunnel offload isn't supported\n"); return -EOPNOTSUPP; } qp->tunnel_offload_en = true; } if (init_attr->create_flags & IB_QP_CREATE_SOURCE_QPN) { if (init_attr->qp_type != IB_QPT_UD || (MLX5_CAP_GEN(dev->mdev, port_type) != MLX5_CAP_PORT_TYPE_IB) || !mlx5_get_flow_namespace(dev->mdev, MLX5_FLOW_NAMESPACE_BYPASS)) { mlx5_ib_dbg(dev, "Source QP option isn't supported\n"); return -EOPNOTSUPP; } qp->flags |= MLX5_IB_QP_UNDERLAY; qp->underlay_qpn = init_attr->source_qpn; } } else { qp->wq_sig = !!wq_signature; } base = (init_attr->qp_type == IB_QPT_RAW_PACKET || qp->flags & MLX5_IB_QP_UNDERLAY) ? &qp->raw_packet_qp.rq.base : &qp->trans_qp.base; qp->has_rq = qp_has_rq(init_attr); err = set_rq_size(dev, &init_attr->cap, qp->has_rq, qp, (pd && pd->uobject) ? &ucmd : NULL); if (err) { mlx5_ib_dbg(dev, "err %d\n", err); return err; } if (pd) { if (pd->uobject) { __u32 max_wqes = 1 << MLX5_CAP_GEN(mdev, log_max_qp_sz); mlx5_ib_dbg(dev, "requested sq_wqe_count (%d)\n", ucmd.sq_wqe_count); if (ucmd.rq_wqe_shift != qp->rq.wqe_shift || ucmd.rq_wqe_count != qp->rq.wqe_cnt) { mlx5_ib_dbg(dev, "invalid rq params\n"); return -EINVAL; } if (ucmd.sq_wqe_count > max_wqes) { mlx5_ib_dbg(dev, "requested sq_wqe_count (%d) > max allowed (%d)\n", ucmd.sq_wqe_count, max_wqes); return -EINVAL; } if (init_attr->create_flags & mlx5_ib_create_qp_sqpn_qp1()) { mlx5_ib_dbg(dev, "user-space is not allowed to create UD QPs spoofing as QP1\n"); return -EINVAL; } err = create_user_qp(dev, pd, qp, udata, init_attr, &in, &resp, &inlen, base); if (err) mlx5_ib_dbg(dev, "err %d\n", err); } else { err = create_kernel_qp(dev, init_attr, qp, &in, &inlen, base); if (err) mlx5_ib_dbg(dev, "err %d\n", err); } if (err) return err; } else { in = kvzalloc(inlen, GFP_KERNEL); if (!in) return -ENOMEM; qp->create_type = MLX5_QP_EMPTY; } if (is_sqp(init_attr->qp_type)) qp->port = init_attr->port_num; qpc = MLX5_ADDR_OF(create_qp_in, in, qpc); MLX5_SET(qpc, qpc, st, mlx5_st); MLX5_SET(qpc, qpc, pm_state, MLX5_QP_PM_MIGRATED); if (init_attr->qp_type != MLX5_IB_QPT_REG_UMR) MLX5_SET(qpc, qpc, pd, to_mpd(pd ? pd : devr->p0)->pdn); else MLX5_SET(qpc, qpc, latency_sensitive, 1); if (qp->wq_sig) MLX5_SET(qpc, qpc, wq_signature, 1); if (qp->flags & MLX5_IB_QP_BLOCK_MULTICAST_LOOPBACK) MLX5_SET(qpc, qpc, block_lb_mc, 1); if (qp->flags & MLX5_IB_QP_CROSS_CHANNEL) MLX5_SET(qpc, qpc, cd_master, 1); if (qp->flags & MLX5_IB_QP_MANAGED_SEND) MLX5_SET(qpc, qpc, cd_slave_send, 1); if (qp->flags & MLX5_IB_QP_MANAGED_RECV) MLX5_SET(qpc, qpc, cd_slave_receive, 1); if (qp->scat_cqe && is_connected(init_attr->qp_type)) { int rcqe_sz; int scqe_sz; rcqe_sz = mlx5_ib_get_cqe_size(dev, init_attr->recv_cq); scqe_sz = mlx5_ib_get_cqe_size(dev, init_attr->send_cq); if (rcqe_sz == 128) MLX5_SET(qpc, qpc, cs_res, MLX5_RES_SCAT_DATA64_CQE); else MLX5_SET(qpc, qpc, cs_res, MLX5_RES_SCAT_DATA32_CQE); if (init_attr->sq_sig_type == IB_SIGNAL_ALL_WR) { if (scqe_sz == 128) MLX5_SET(qpc, qpc, cs_req, MLX5_REQ_SCAT_DATA64_CQE); else MLX5_SET(qpc, qpc, cs_req, MLX5_REQ_SCAT_DATA32_CQE); } } if (qp->rq.wqe_cnt) { MLX5_SET(qpc, qpc, log_rq_stride, qp->rq.wqe_shift - 4); MLX5_SET(qpc, qpc, log_rq_size, ilog2(qp->rq.wqe_cnt)); } MLX5_SET(qpc, qpc, rq_type, get_rx_type(qp, init_attr)); if (qp->sq.wqe_cnt) { MLX5_SET(qpc, qpc, log_sq_size, ilog2(qp->sq.wqe_cnt)); } else { MLX5_SET(qpc, qpc, no_sq, 1); if (init_attr->srq && init_attr->srq->srq_type == IB_SRQT_TM) MLX5_SET(qpc, qpc, offload_type, MLX5_QPC_OFFLOAD_TYPE_RNDV); } /* Set default resources */ switch (init_attr->qp_type) { case IB_QPT_XRC_TGT: MLX5_SET(qpc, qpc, cqn_rcv, to_mcq(devr->c0)->mcq.cqn); MLX5_SET(qpc, qpc, cqn_snd, to_mcq(devr->c0)->mcq.cqn); MLX5_SET(qpc, qpc, srqn_rmpn_xrqn, to_msrq(devr->s0)->msrq.srqn); MLX5_SET(qpc, qpc, xrcd, to_mxrcd(init_attr->xrcd)->xrcdn); break; case IB_QPT_XRC_INI: MLX5_SET(qpc, qpc, cqn_rcv, to_mcq(devr->c0)->mcq.cqn); MLX5_SET(qpc, qpc, xrcd, to_mxrcd(devr->x1)->xrcdn); MLX5_SET(qpc, qpc, srqn_rmpn_xrqn, to_msrq(devr->s0)->msrq.srqn); break; default: if (init_attr->srq) { MLX5_SET(qpc, qpc, xrcd, to_mxrcd(devr->x0)->xrcdn); MLX5_SET(qpc, qpc, srqn_rmpn_xrqn, to_msrq(init_attr->srq)->msrq.srqn); } else { MLX5_SET(qpc, qpc, xrcd, to_mxrcd(devr->x1)->xrcdn); MLX5_SET(qpc, qpc, srqn_rmpn_xrqn, to_msrq(devr->s1)->msrq.srqn); } } if (init_attr->send_cq) MLX5_SET(qpc, qpc, cqn_snd, to_mcq(init_attr->send_cq)->mcq.cqn); if (init_attr->recv_cq) MLX5_SET(qpc, qpc, cqn_rcv, to_mcq(init_attr->recv_cq)->mcq.cqn); MLX5_SET64(qpc, qpc, dbr_addr, qp->db.dma); /* 0xffffff means we ask to work with cqe version 0 */ if (MLX5_CAP_GEN(mdev, cqe_version) == MLX5_CQE_VERSION_V1) MLX5_SET(qpc, qpc, user_index, uidx); /* we use IB_QP_CREATE_IPOIB_UD_LSO to indicates ipoib qp */ if (init_attr->qp_type == IB_QPT_UD && (init_attr->create_flags & IB_QP_CREATE_IPOIB_UD_LSO)) { MLX5_SET(qpc, qpc, ulp_stateless_offload_mode, 1); qp->flags |= MLX5_IB_QP_LSO; } if (init_attr->create_flags & IB_QP_CREATE_PCI_WRITE_END_PADDING) { if (!MLX5_CAP_GEN(dev->mdev, end_pad)) { mlx5_ib_dbg(dev, "scatter end padding is not supported\n"); err = -EOPNOTSUPP; goto err; } else if (init_attr->qp_type != IB_QPT_RAW_PACKET) { MLX5_SET(qpc, qpc, end_padding_mode, MLX5_WQ_END_PAD_MODE_ALIGN); } else { qp->flags |= MLX5_IB_QP_PCI_WRITE_END_PADDING; } } if (inlen < 0) { err = -EINVAL; goto err; } if (init_attr->qp_type == IB_QPT_RAW_PACKET || qp->flags & MLX5_IB_QP_UNDERLAY) { qp->raw_packet_qp.sq.ubuffer.buf_addr = ucmd.sq_buf_addr; raw_packet_qp_copy_info(qp, &qp->raw_packet_qp); err = create_raw_packet_qp(dev, qp, in, inlen, pd); } else { err = mlx5_core_create_qp(dev->mdev, &base->mqp, in, inlen); } if (err) { mlx5_ib_dbg(dev, "create qp failed\n"); goto err_create; } kvfree(in); base->container_mibqp = qp; base->mqp.event = mlx5_ib_qp_event; get_cqs(init_attr->qp_type, init_attr->send_cq, init_attr->recv_cq, &send_cq, &recv_cq); spin_lock_irqsave(&dev->reset_flow_resource_lock, flags); mlx5_ib_lock_cqs(send_cq, recv_cq); /* Maintain device to QPs access, needed for further handling via reset * flow */ list_add_tail(&qp->qps_list, &dev->qp_list); /* Maintain CQ to QPs access, needed for further handling via reset flow */ if (send_cq) list_add_tail(&qp->cq_send_list, &send_cq->list_send_qp); if (recv_cq) list_add_tail(&qp->cq_recv_list, &recv_cq->list_recv_qp); mlx5_ib_unlock_cqs(send_cq, recv_cq); spin_unlock_irqrestore(&dev->reset_flow_resource_lock, flags); return 0; err_create: if (qp->create_type == MLX5_QP_USER) destroy_qp_user(dev, pd, qp, base); else if (qp->create_type == MLX5_QP_KERNEL) destroy_qp_kernel(dev, qp); err: kvfree(in); return err; } static void mlx5_ib_lock_cqs(struct mlx5_ib_cq *send_cq, struct mlx5_ib_cq *recv_cq) __acquires(&send_cq->lock) __acquires(&recv_cq->lock) { if (send_cq) { if (recv_cq) { if (send_cq->mcq.cqn < recv_cq->mcq.cqn) { spin_lock(&send_cq->lock); spin_lock_nested(&recv_cq->lock, SINGLE_DEPTH_NESTING); } else if (send_cq->mcq.cqn == recv_cq->mcq.cqn) { spin_lock(&send_cq->lock); __acquire(&recv_cq->lock); } else { spin_lock(&recv_cq->lock); spin_lock_nested(&send_cq->lock, SINGLE_DEPTH_NESTING); } } else { spin_lock(&send_cq->lock); __acquire(&recv_cq->lock); } } else if (recv_cq) { spin_lock(&recv_cq->lock); __acquire(&send_cq->lock); } else { __acquire(&send_cq->lock); __acquire(&recv_cq->lock); } } static void mlx5_ib_unlock_cqs(struct mlx5_ib_cq *send_cq, struct mlx5_ib_cq *recv_cq) __releases(&send_cq->lock) __releases(&recv_cq->lock) { if (send_cq) { if (recv_cq) { if (send_cq->mcq.cqn < recv_cq->mcq.cqn) { spin_unlock(&recv_cq->lock); spin_unlock(&send_cq->lock); } else if (send_cq->mcq.cqn == recv_cq->mcq.cqn) { __release(&recv_cq->lock); spin_unlock(&send_cq->lock); } else { spin_unlock(&send_cq->lock); spin_unlock(&recv_cq->lock); } } else { __release(&recv_cq->lock); spin_unlock(&send_cq->lock); } } else if (recv_cq) { __release(&send_cq->lock); spin_unlock(&recv_cq->lock); } else { __release(&recv_cq->lock); __release(&send_cq->lock); } } static struct mlx5_ib_pd *get_pd(struct mlx5_ib_qp *qp) { return to_mpd(qp->ibqp.pd); } static void get_cqs(enum ib_qp_type qp_type, struct ib_cq *ib_send_cq, struct ib_cq *ib_recv_cq, struct mlx5_ib_cq **send_cq, struct mlx5_ib_cq **recv_cq) { switch (qp_type) { case IB_QPT_XRC_TGT: *send_cq = NULL; *recv_cq = NULL; break; case MLX5_IB_QPT_REG_UMR: case IB_QPT_XRC_INI: *send_cq = ib_send_cq ? to_mcq(ib_send_cq) : NULL; *recv_cq = NULL; break; case IB_QPT_SMI: case MLX5_IB_QPT_HW_GSI: case IB_QPT_RC: case IB_QPT_UC: case IB_QPT_UD: case IB_QPT_RAW_IPV6: case IB_QPT_RAW_ETHERTYPE: case IB_QPT_RAW_PACKET: *send_cq = ib_send_cq ? to_mcq(ib_send_cq) : NULL; *recv_cq = ib_recv_cq ? to_mcq(ib_recv_cq) : NULL; break; case IB_QPT_MAX: default: *send_cq = NULL; *recv_cq = NULL; break; } } static int modify_raw_packet_qp(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *qp, const struct mlx5_modify_raw_qp_param *raw_qp_param, u8 lag_tx_affinity); static void destroy_qp_common(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *qp) { struct mlx5_ib_cq *send_cq, *recv_cq; struct mlx5_ib_qp_base *base; unsigned long flags; int err; if (qp->ibqp.rwq_ind_tbl) { destroy_rss_raw_qp_tir(dev, qp); return; } base = (qp->ibqp.qp_type == IB_QPT_RAW_PACKET || qp->flags & MLX5_IB_QP_UNDERLAY) ? &qp->raw_packet_qp.rq.base : &qp->trans_qp.base; if (qp->state != IB_QPS_RESET) { if (qp->ibqp.qp_type != IB_QPT_RAW_PACKET && !(qp->flags & MLX5_IB_QP_UNDERLAY)) { err = mlx5_core_qp_modify(dev->mdev, MLX5_CMD_OP_2RST_QP, 0, NULL, &base->mqp); } else { struct mlx5_modify_raw_qp_param raw_qp_param = { .operation = MLX5_CMD_OP_2RST_QP }; err = modify_raw_packet_qp(dev, qp, &raw_qp_param, 0); } if (err) mlx5_ib_warn(dev, "mlx5_ib: modify QP 0x%06x to RESET failed\n", base->mqp.qpn); } get_cqs(qp->ibqp.qp_type, qp->ibqp.send_cq, qp->ibqp.recv_cq, &send_cq, &recv_cq); spin_lock_irqsave(&dev->reset_flow_resource_lock, flags); mlx5_ib_lock_cqs(send_cq, recv_cq); /* del from lists under both locks above to protect reset flow paths */ list_del(&qp->qps_list); if (send_cq) list_del(&qp->cq_send_list); if (recv_cq) list_del(&qp->cq_recv_list); if (qp->create_type == MLX5_QP_KERNEL) { __mlx5_ib_cq_clean(recv_cq, base->mqp.qpn, qp->ibqp.srq ? to_msrq(qp->ibqp.srq) : NULL); if (send_cq != recv_cq) __mlx5_ib_cq_clean(send_cq, base->mqp.qpn, NULL); } mlx5_ib_unlock_cqs(send_cq, recv_cq); spin_unlock_irqrestore(&dev->reset_flow_resource_lock, flags); if (qp->ibqp.qp_type == IB_QPT_RAW_PACKET || qp->flags & MLX5_IB_QP_UNDERLAY) { destroy_raw_packet_qp(dev, qp); } else { err = mlx5_core_destroy_qp(dev->mdev, &base->mqp); if (err) mlx5_ib_warn(dev, "failed to destroy QP 0x%x\n", base->mqp.qpn); } if (qp->create_type == MLX5_QP_KERNEL) destroy_qp_kernel(dev, qp); else if (qp->create_type == MLX5_QP_USER) destroy_qp_user(dev, &get_pd(qp)->ibpd, qp, base); } static const char *ib_qp_type_str(enum ib_qp_type type) { switch (type) { case IB_QPT_SMI: return "IB_QPT_SMI"; case IB_QPT_GSI: return "IB_QPT_GSI"; case IB_QPT_RC: return "IB_QPT_RC"; case IB_QPT_UC: return "IB_QPT_UC"; case IB_QPT_UD: return "IB_QPT_UD"; case IB_QPT_RAW_IPV6: return "IB_QPT_RAW_IPV6"; case IB_QPT_RAW_ETHERTYPE: return "IB_QPT_RAW_ETHERTYPE"; case IB_QPT_XRC_INI: return "IB_QPT_XRC_INI"; case IB_QPT_XRC_TGT: return "IB_QPT_XRC_TGT"; case IB_QPT_RAW_PACKET: return "IB_QPT_RAW_PACKET"; case MLX5_IB_QPT_REG_UMR: return "MLX5_IB_QPT_REG_UMR"; case IB_QPT_DRIVER: return "IB_QPT_DRIVER"; case IB_QPT_MAX: default: return "Invalid QP type"; } } static struct ib_qp *mlx5_ib_create_dct(struct ib_pd *pd, struct ib_qp_init_attr *attr, struct mlx5_ib_create_qp *ucmd) { struct mlx5_ib_qp *qp; int err = 0; u32 uidx = MLX5_IB_DEFAULT_UIDX; void *dctc; if (!attr->srq || !attr->recv_cq) return ERR_PTR(-EINVAL); err = get_qp_user_index(to_mucontext(pd->uobject->context), ucmd, sizeof(*ucmd), &uidx); if (err) return ERR_PTR(err); qp = kzalloc(sizeof(*qp), GFP_KERNEL); if (!qp) return ERR_PTR(-ENOMEM); qp->dct.in = kzalloc(MLX5_ST_SZ_BYTES(create_dct_in), GFP_KERNEL); if (!qp->dct.in) { err = -ENOMEM; goto err_free; } dctc = MLX5_ADDR_OF(create_dct_in, qp->dct.in, dct_context_entry); qp->qp_sub_type = MLX5_IB_QPT_DCT; MLX5_SET(dctc, dctc, pd, to_mpd(pd)->pdn); MLX5_SET(dctc, dctc, srqn_xrqn, to_msrq(attr->srq)->msrq.srqn); MLX5_SET(dctc, dctc, cqn, to_mcq(attr->recv_cq)->mcq.cqn); MLX5_SET64(dctc, dctc, dc_access_key, ucmd->access_key); MLX5_SET(dctc, dctc, user_index, uidx); qp->state = IB_QPS_RESET; return &qp->ibqp; err_free: kfree(qp); return ERR_PTR(err); } static int set_mlx_qp_type(struct mlx5_ib_dev *dev, struct ib_qp_init_attr *init_attr, struct mlx5_ib_create_qp *ucmd, struct ib_udata *udata) { enum { MLX_QP_FLAGS = MLX5_QP_FLAG_TYPE_DCT | MLX5_QP_FLAG_TYPE_DCI }; int err; if (!udata) return -EINVAL; if (udata->inlen < sizeof(*ucmd)) { mlx5_ib_dbg(dev, "create_qp user command is smaller than expected\n"); return -EINVAL; } err = ib_copy_from_udata(ucmd, udata, sizeof(*ucmd)); if (err) return err; if ((ucmd->flags & MLX_QP_FLAGS) == MLX5_QP_FLAG_TYPE_DCI) { init_attr->qp_type = MLX5_IB_QPT_DCI; } else { if ((ucmd->flags & MLX_QP_FLAGS) == MLX5_QP_FLAG_TYPE_DCT) { init_attr->qp_type = MLX5_IB_QPT_DCT; } else { mlx5_ib_dbg(dev, "Invalid QP flags\n"); return -EINVAL; } } if (!MLX5_CAP_GEN(dev->mdev, dct)) { mlx5_ib_dbg(dev, "DC transport is not supported\n"); return -EOPNOTSUPP; } return 0; } struct ib_qp *mlx5_ib_create_qp(struct ib_pd *pd, struct ib_qp_init_attr *verbs_init_attr, struct ib_udata *udata) { struct mlx5_ib_dev *dev; struct mlx5_ib_qp *qp; u16 xrcdn = 0; int err; struct ib_qp_init_attr mlx_init_attr; struct ib_qp_init_attr *init_attr = verbs_init_attr; if (pd) { dev = to_mdev(pd->device); if (init_attr->qp_type == IB_QPT_RAW_PACKET) { if (!pd->uobject) { mlx5_ib_dbg(dev, "Raw Packet QP is not supported for kernel consumers\n"); return ERR_PTR(-EINVAL); } else if (!to_mucontext(pd->uobject->context)->cqe_version) { mlx5_ib_dbg(dev, "Raw Packet QP is only supported for CQE version > 0\n"); return ERR_PTR(-EINVAL); } } } else { /* being cautious here */ if (init_attr->qp_type != IB_QPT_XRC_TGT && init_attr->qp_type != MLX5_IB_QPT_REG_UMR) { pr_warn("%s: no PD for transport %s\n", __func__, ib_qp_type_str(init_attr->qp_type)); return ERR_PTR(-EINVAL); } dev = to_mdev(to_mxrcd(init_attr->xrcd)->ibxrcd.device); } if (init_attr->qp_type == IB_QPT_DRIVER) { struct mlx5_ib_create_qp ucmd; init_attr = &mlx_init_attr; memcpy(init_attr, verbs_init_attr, sizeof(*verbs_init_attr)); err = set_mlx_qp_type(dev, init_attr, &ucmd, udata); if (err) return ERR_PTR(err); if (init_attr->qp_type == MLX5_IB_QPT_DCI) { if (init_attr->cap.max_recv_wr || init_attr->cap.max_recv_sge) { mlx5_ib_dbg(dev, "DCI QP requires zero size receive queue\n"); return ERR_PTR(-EINVAL); } } else { return mlx5_ib_create_dct(pd, init_attr, &ucmd); } } switch (init_attr->qp_type) { case IB_QPT_XRC_TGT: case IB_QPT_XRC_INI: if (!MLX5_CAP_GEN(dev->mdev, xrc)) { mlx5_ib_dbg(dev, "XRC not supported\n"); return ERR_PTR(-ENOSYS); } init_attr->recv_cq = NULL; if (init_attr->qp_type == IB_QPT_XRC_TGT) { xrcdn = to_mxrcd(init_attr->xrcd)->xrcdn; init_attr->send_cq = NULL; } /* fall through */ case IB_QPT_RAW_PACKET: case IB_QPT_RC: case IB_QPT_UC: case IB_QPT_UD: case IB_QPT_SMI: case MLX5_IB_QPT_HW_GSI: case MLX5_IB_QPT_REG_UMR: case MLX5_IB_QPT_DCI: qp = kzalloc(sizeof(*qp), GFP_KERNEL); if (!qp) return ERR_PTR(-ENOMEM); err = create_qp_common(dev, pd, init_attr, udata, qp); if (err) { mlx5_ib_dbg(dev, "create_qp_common failed\n"); kfree(qp); return ERR_PTR(err); } if (is_qp0(init_attr->qp_type)) qp->ibqp.qp_num = 0; else if (is_qp1(init_attr->qp_type)) qp->ibqp.qp_num = 1; else qp->ibqp.qp_num = qp->trans_qp.base.mqp.qpn; mlx5_ib_dbg(dev, "ib qpnum 0x%x, mlx qpn 0x%x, rcqn 0x%x, scqn 0x%x\n", qp->ibqp.qp_num, qp->trans_qp.base.mqp.qpn, init_attr->recv_cq ? to_mcq(init_attr->recv_cq)->mcq.cqn : -1, init_attr->send_cq ? to_mcq(init_attr->send_cq)->mcq.cqn : -1); qp->trans_qp.xrcdn = xrcdn; break; case IB_QPT_GSI: return mlx5_ib_gsi_create_qp(pd, init_attr); case IB_QPT_RAW_IPV6: case IB_QPT_RAW_ETHERTYPE: case IB_QPT_MAX: default: mlx5_ib_dbg(dev, "unsupported qp type %d\n", init_attr->qp_type); /* Don't support raw QPs */ return ERR_PTR(-EINVAL); } if (verbs_init_attr->qp_type == IB_QPT_DRIVER) qp->qp_sub_type = init_attr->qp_type; return &qp->ibqp; } static int mlx5_ib_destroy_dct(struct mlx5_ib_qp *mqp) { struct mlx5_ib_dev *dev = to_mdev(mqp->ibqp.device); if (mqp->state == IB_QPS_RTR) { int err; err = mlx5_core_destroy_dct(dev->mdev, &mqp->dct.mdct); if (err) { mlx5_ib_warn(dev, "failed to destroy DCT %d\n", err); return err; } } kfree(mqp->dct.in); kfree(mqp); return 0; } int mlx5_ib_destroy_qp(struct ib_qp *qp) { struct mlx5_ib_dev *dev = to_mdev(qp->device); struct mlx5_ib_qp *mqp = to_mqp(qp); if (unlikely(qp->qp_type == IB_QPT_GSI)) return mlx5_ib_gsi_destroy_qp(qp); if (mqp->qp_sub_type == MLX5_IB_QPT_DCT) return mlx5_ib_destroy_dct(mqp); destroy_qp_common(dev, mqp); kfree(mqp); return 0; } static __be32 to_mlx5_access_flags(struct mlx5_ib_qp *qp, const struct ib_qp_attr *attr, int attr_mask) { u32 hw_access_flags = 0; u8 dest_rd_atomic; u32 access_flags; if (attr_mask & IB_QP_MAX_DEST_RD_ATOMIC) dest_rd_atomic = attr->max_dest_rd_atomic; else dest_rd_atomic = qp->trans_qp.resp_depth; if (attr_mask & IB_QP_ACCESS_FLAGS) access_flags = attr->qp_access_flags; else access_flags = qp->trans_qp.atomic_rd_en; if (!dest_rd_atomic) access_flags &= IB_ACCESS_REMOTE_WRITE; if (access_flags & IB_ACCESS_REMOTE_READ) hw_access_flags |= MLX5_QP_BIT_RRE; if (access_flags & IB_ACCESS_REMOTE_ATOMIC) hw_access_flags |= (MLX5_QP_BIT_RAE | MLX5_ATOMIC_MODE_CX); if (access_flags & IB_ACCESS_REMOTE_WRITE) hw_access_flags |= MLX5_QP_BIT_RWE; return cpu_to_be32(hw_access_flags); } enum { MLX5_PATH_FLAG_FL = 1 << 0, MLX5_PATH_FLAG_FREE_AR = 1 << 1, MLX5_PATH_FLAG_COUNTER = 1 << 2, }; static int ib_rate_to_mlx5(struct mlx5_ib_dev *dev, u8 rate) { if (rate == IB_RATE_PORT_CURRENT) return 0; if (rate < IB_RATE_2_5_GBPS || rate > IB_RATE_300_GBPS) return -EINVAL; while (rate != IB_RATE_PORT_CURRENT && !(1 << (rate + MLX5_STAT_RATE_OFFSET) & MLX5_CAP_GEN(dev->mdev, stat_rate_support))) --rate; return rate ? rate + MLX5_STAT_RATE_OFFSET : rate; } static int modify_raw_packet_eth_prio(struct mlx5_core_dev *dev, struct mlx5_ib_sq *sq, u8 sl) { void *in; void *tisc; int inlen; int err; inlen = MLX5_ST_SZ_BYTES(modify_tis_in); in = kvzalloc(inlen, GFP_KERNEL); if (!in) return -ENOMEM; MLX5_SET(modify_tis_in, in, bitmask.prio, 1); tisc = MLX5_ADDR_OF(modify_tis_in, in, ctx); MLX5_SET(tisc, tisc, prio, ((sl & 0x7) << 1)); err = mlx5_core_modify_tis(dev, sq->tisn, in, inlen); kvfree(in); return err; } static int modify_raw_packet_tx_affinity(struct mlx5_core_dev *dev, struct mlx5_ib_sq *sq, u8 tx_affinity) { void *in; void *tisc; int inlen; int err; inlen = MLX5_ST_SZ_BYTES(modify_tis_in); in = kvzalloc(inlen, GFP_KERNEL); if (!in) return -ENOMEM; MLX5_SET(modify_tis_in, in, bitmask.lag_tx_port_affinity, 1); tisc = MLX5_ADDR_OF(modify_tis_in, in, ctx); MLX5_SET(tisc, tisc, lag_tx_port_affinity, tx_affinity); err = mlx5_core_modify_tis(dev, sq->tisn, in, inlen); kvfree(in); return err; } static int mlx5_set_path(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *qp, const struct rdma_ah_attr *ah, struct mlx5_qp_path *path, u8 port, int attr_mask, u32 path_flags, const struct ib_qp_attr *attr, bool alt) { const struct ib_global_route *grh = rdma_ah_read_grh(ah); int err; enum ib_gid_type gid_type; u8 ah_flags = rdma_ah_get_ah_flags(ah); u8 sl = rdma_ah_get_sl(ah); if (attr_mask & IB_QP_PKEY_INDEX) path->pkey_index = cpu_to_be16(alt ? attr->alt_pkey_index : attr->pkey_index); if (ah_flags & IB_AH_GRH) { if (grh->sgid_index >= dev->mdev->port_caps[port - 1].gid_table_len) { pr_err("sgid_index (%u) too large. max is %d\n", grh->sgid_index, dev->mdev->port_caps[port - 1].gid_table_len); return -EINVAL; } } if (ah->type == RDMA_AH_ATTR_TYPE_ROCE) { if (!(ah_flags & IB_AH_GRH)) return -EINVAL; memcpy(path->rmac, ah->roce.dmac, sizeof(ah->roce.dmac)); if (qp->ibqp.qp_type == IB_QPT_RC || qp->ibqp.qp_type == IB_QPT_UC || qp->ibqp.qp_type == IB_QPT_XRC_INI || qp->ibqp.qp_type == IB_QPT_XRC_TGT) path->udp_sport = mlx5_get_roce_udp_sport(dev, ah->grh.sgid_attr); path->dci_cfi_prio_sl = (sl & 0x7) << 4; gid_type = ah->grh.sgid_attr->gid_type; if (gid_type == IB_GID_TYPE_ROCE_UDP_ENCAP) path->ecn_dscp = (grh->traffic_class >> 2) & 0x3f; } else { path->fl_free_ar = (path_flags & MLX5_PATH_FLAG_FL) ? 0x80 : 0; path->fl_free_ar |= (path_flags & MLX5_PATH_FLAG_FREE_AR) ? 0x40 : 0; path->rlid = cpu_to_be16(rdma_ah_get_dlid(ah)); path->grh_mlid = rdma_ah_get_path_bits(ah) & 0x7f; if (ah_flags & IB_AH_GRH) path->grh_mlid |= 1 << 7; path->dci_cfi_prio_sl = sl & 0xf; } if (ah_flags & IB_AH_GRH) { path->mgid_index = grh->sgid_index; path->hop_limit = grh->hop_limit; path->tclass_flowlabel = cpu_to_be32((grh->traffic_class << 20) | (grh->flow_label)); memcpy(path->rgid, grh->dgid.raw, 16); } err = ib_rate_to_mlx5(dev, rdma_ah_get_static_rate(ah)); if (err < 0) return err; path->static_rate = err; path->port = port; if (attr_mask & IB_QP_TIMEOUT) path->ackto_lt = (alt ? attr->alt_timeout : attr->timeout) << 3; if ((qp->ibqp.qp_type == IB_QPT_RAW_PACKET) && qp->sq.wqe_cnt) return modify_raw_packet_eth_prio(dev->mdev, &qp->raw_packet_qp.sq, sl & 0xf); return 0; } static enum mlx5_qp_optpar opt_mask[MLX5_QP_NUM_STATE][MLX5_QP_NUM_STATE][MLX5_QP_ST_MAX] = { [MLX5_QP_STATE_INIT] = { [MLX5_QP_STATE_INIT] = { [MLX5_QP_ST_RC] = MLX5_QP_OPTPAR_RRE | MLX5_QP_OPTPAR_RAE | MLX5_QP_OPTPAR_RWE | MLX5_QP_OPTPAR_PKEY_INDEX | MLX5_QP_OPTPAR_PRI_PORT, [MLX5_QP_ST_UC] = MLX5_QP_OPTPAR_RWE | MLX5_QP_OPTPAR_PKEY_INDEX | MLX5_QP_OPTPAR_PRI_PORT, [MLX5_QP_ST_UD] = MLX5_QP_OPTPAR_PKEY_INDEX | MLX5_QP_OPTPAR_Q_KEY | MLX5_QP_OPTPAR_PRI_PORT, }, [MLX5_QP_STATE_RTR] = { [MLX5_QP_ST_RC] = MLX5_QP_OPTPAR_ALT_ADDR_PATH | MLX5_QP_OPTPAR_RRE | MLX5_QP_OPTPAR_RAE | MLX5_QP_OPTPAR_RWE | MLX5_QP_OPTPAR_PKEY_INDEX, [MLX5_QP_ST_UC] = MLX5_QP_OPTPAR_ALT_ADDR_PATH | MLX5_QP_OPTPAR_RWE | MLX5_QP_OPTPAR_PKEY_INDEX, [MLX5_QP_ST_UD] = MLX5_QP_OPTPAR_PKEY_INDEX | MLX5_QP_OPTPAR_Q_KEY, [MLX5_QP_ST_MLX] = MLX5_QP_OPTPAR_PKEY_INDEX | MLX5_QP_OPTPAR_Q_KEY, [MLX5_QP_ST_XRC] = MLX5_QP_OPTPAR_ALT_ADDR_PATH | MLX5_QP_OPTPAR_RRE | MLX5_QP_OPTPAR_RAE | MLX5_QP_OPTPAR_RWE | MLX5_QP_OPTPAR_PKEY_INDEX, }, }, [MLX5_QP_STATE_RTR] = { [MLX5_QP_STATE_RTS] = { [MLX5_QP_ST_RC] = MLX5_QP_OPTPAR_ALT_ADDR_PATH | MLX5_QP_OPTPAR_RRE | MLX5_QP_OPTPAR_RAE | MLX5_QP_OPTPAR_RWE | MLX5_QP_OPTPAR_PM_STATE | MLX5_QP_OPTPAR_RNR_TIMEOUT, [MLX5_QP_ST_UC] = MLX5_QP_OPTPAR_ALT_ADDR_PATH | MLX5_QP_OPTPAR_RWE | MLX5_QP_OPTPAR_PM_STATE, [MLX5_QP_ST_UD] = MLX5_QP_OPTPAR_Q_KEY, }, }, [MLX5_QP_STATE_RTS] = { [MLX5_QP_STATE_RTS] = { [MLX5_QP_ST_RC] = MLX5_QP_OPTPAR_RRE | MLX5_QP_OPTPAR_RAE | MLX5_QP_OPTPAR_RWE | MLX5_QP_OPTPAR_RNR_TIMEOUT | MLX5_QP_OPTPAR_PM_STATE | MLX5_QP_OPTPAR_ALT_ADDR_PATH, [MLX5_QP_ST_UC] = MLX5_QP_OPTPAR_RWE | MLX5_QP_OPTPAR_PM_STATE | MLX5_QP_OPTPAR_ALT_ADDR_PATH, [MLX5_QP_ST_UD] = MLX5_QP_OPTPAR_Q_KEY | MLX5_QP_OPTPAR_SRQN | MLX5_QP_OPTPAR_CQN_RCV, }, }, [MLX5_QP_STATE_SQER] = { [MLX5_QP_STATE_RTS] = { [MLX5_QP_ST_UD] = MLX5_QP_OPTPAR_Q_KEY, [MLX5_QP_ST_MLX] = MLX5_QP_OPTPAR_Q_KEY, [MLX5_QP_ST_UC] = MLX5_QP_OPTPAR_RWE, [MLX5_QP_ST_RC] = MLX5_QP_OPTPAR_RNR_TIMEOUT | MLX5_QP_OPTPAR_RWE | MLX5_QP_OPTPAR_RAE | MLX5_QP_OPTPAR_RRE, }, }, }; static int ib_nr_to_mlx5_nr(int ib_mask) { switch (ib_mask) { case IB_QP_STATE: return 0; case IB_QP_CUR_STATE: return 0; case IB_QP_EN_SQD_ASYNC_NOTIFY: return 0; case IB_QP_ACCESS_FLAGS: return MLX5_QP_OPTPAR_RWE | MLX5_QP_OPTPAR_RRE | MLX5_QP_OPTPAR_RAE; case IB_QP_PKEY_INDEX: return MLX5_QP_OPTPAR_PKEY_INDEX; case IB_QP_PORT: return MLX5_QP_OPTPAR_PRI_PORT; case IB_QP_QKEY: return MLX5_QP_OPTPAR_Q_KEY; case IB_QP_AV: return MLX5_QP_OPTPAR_PRIMARY_ADDR_PATH | MLX5_QP_OPTPAR_PRI_PORT; case IB_QP_PATH_MTU: return 0; case IB_QP_TIMEOUT: return MLX5_QP_OPTPAR_ACK_TIMEOUT; case IB_QP_RETRY_CNT: return MLX5_QP_OPTPAR_RETRY_COUNT; case IB_QP_RNR_RETRY: return MLX5_QP_OPTPAR_RNR_RETRY; case IB_QP_RQ_PSN: return 0; case IB_QP_MAX_QP_RD_ATOMIC: return MLX5_QP_OPTPAR_SRA_MAX; case IB_QP_ALT_PATH: return MLX5_QP_OPTPAR_ALT_ADDR_PATH; case IB_QP_MIN_RNR_TIMER: return MLX5_QP_OPTPAR_RNR_TIMEOUT; case IB_QP_SQ_PSN: return 0; case IB_QP_MAX_DEST_RD_ATOMIC: return MLX5_QP_OPTPAR_RRA_MAX | MLX5_QP_OPTPAR_RWE | MLX5_QP_OPTPAR_RRE | MLX5_QP_OPTPAR_RAE; case IB_QP_PATH_MIG_STATE: return MLX5_QP_OPTPAR_PM_STATE; case IB_QP_CAP: return 0; case IB_QP_DEST_QPN: return 0; } return 0; } static int ib_mask_to_mlx5_opt(int ib_mask) { int result = 0; int i; for (i = 0; i < 8 * sizeof(int); i++) { if ((1 << i) & ib_mask) result |= ib_nr_to_mlx5_nr(1 << i); } return result; } static int modify_raw_packet_qp_rq(struct mlx5_ib_dev *dev, struct mlx5_ib_rq *rq, int new_state, const struct mlx5_modify_raw_qp_param *raw_qp_param) { void *in; void *rqc; int inlen; int err; inlen = MLX5_ST_SZ_BYTES(modify_rq_in); in = kvzalloc(inlen, GFP_KERNEL); if (!in) return -ENOMEM; MLX5_SET(modify_rq_in, in, rq_state, rq->state); rqc = MLX5_ADDR_OF(modify_rq_in, in, ctx); MLX5_SET(rqc, rqc, state, new_state); if (raw_qp_param->set_mask & MLX5_RAW_QP_MOD_SET_RQ_Q_CTR_ID) { if (MLX5_CAP_GEN(dev->mdev, modify_rq_counter_set_id)) { MLX5_SET64(modify_rq_in, in, modify_bitmask, MLX5_MODIFY_RQ_IN_MODIFY_BITMASK_RQ_COUNTER_SET_ID); MLX5_SET(rqc, rqc, counter_set_id, raw_qp_param->rq_q_ctr_id); } else pr_info_once("%s: RAW PACKET QP counters are not supported on current FW\n", dev->ib_dev.name); } err = mlx5_core_modify_rq(dev->mdev, rq->base.mqp.qpn, in, inlen); if (err) goto out; rq->state = new_state; out: kvfree(in); return err; } static int modify_raw_packet_qp_sq(struct mlx5_core_dev *dev, struct mlx5_ib_sq *sq, int new_state, const struct mlx5_modify_raw_qp_param *raw_qp_param) { struct mlx5_ib_qp *ibqp = sq->base.container_mibqp; struct mlx5_rate_limit old_rl = ibqp->rl; struct mlx5_rate_limit new_rl = old_rl; bool new_rate_added = false; u16 rl_index = 0; void *in; void *sqc; int inlen; int err; inlen = MLX5_ST_SZ_BYTES(modify_sq_in); in = kvzalloc(inlen, GFP_KERNEL); if (!in) return -ENOMEM; MLX5_SET(modify_sq_in, in, sq_state, sq->state); sqc = MLX5_ADDR_OF(modify_sq_in, in, ctx); MLX5_SET(sqc, sqc, state, new_state); if (raw_qp_param->set_mask & MLX5_RAW_QP_RATE_LIMIT) { if (new_state != MLX5_SQC_STATE_RDY) pr_warn("%s: Rate limit can only be changed when SQ is moving to RDY\n", __func__); else new_rl = raw_qp_param->rl; } if (!mlx5_rl_are_equal(&old_rl, &new_rl)) { if (new_rl.rate) { err = mlx5_rl_add_rate(dev, &rl_index, &new_rl); if (err) { pr_err("Failed configuring rate limit(err %d): \ rate %u, max_burst_sz %u, typical_pkt_sz %u\n", err, new_rl.rate, new_rl.max_burst_sz, new_rl.typical_pkt_sz); goto out; } new_rate_added = true; } MLX5_SET64(modify_sq_in, in, modify_bitmask, 1); /* index 0 means no limit */ MLX5_SET(sqc, sqc, packet_pacing_rate_limit_index, rl_index); } err = mlx5_core_modify_sq(dev, sq->base.mqp.qpn, in, inlen); if (err) { /* Remove new rate from table if failed */ if (new_rate_added) mlx5_rl_remove_rate(dev, &new_rl); goto out; } /* Only remove the old rate after new rate was set */ if ((old_rl.rate && !mlx5_rl_are_equal(&old_rl, &new_rl)) || (new_state != MLX5_SQC_STATE_RDY)) mlx5_rl_remove_rate(dev, &old_rl); ibqp->rl = new_rl; sq->state = new_state; out: kvfree(in); return err; } static int modify_raw_packet_qp(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *qp, const struct mlx5_modify_raw_qp_param *raw_qp_param, u8 tx_affinity) { struct mlx5_ib_raw_packet_qp *raw_packet_qp = &qp->raw_packet_qp; struct mlx5_ib_rq *rq = &raw_packet_qp->rq; struct mlx5_ib_sq *sq = &raw_packet_qp->sq; int modify_rq = !!qp->rq.wqe_cnt; int modify_sq = !!qp->sq.wqe_cnt; int rq_state; int sq_state; int err; switch (raw_qp_param->operation) { case MLX5_CMD_OP_RST2INIT_QP: rq_state = MLX5_RQC_STATE_RDY; sq_state = MLX5_SQC_STATE_RDY; break; case MLX5_CMD_OP_2ERR_QP: rq_state = MLX5_RQC_STATE_ERR; sq_state = MLX5_SQC_STATE_ERR; break; case MLX5_CMD_OP_2RST_QP: rq_state = MLX5_RQC_STATE_RST; sq_state = MLX5_SQC_STATE_RST; break; case MLX5_CMD_OP_RTR2RTS_QP: case MLX5_CMD_OP_RTS2RTS_QP: if (raw_qp_param->set_mask == MLX5_RAW_QP_RATE_LIMIT) { modify_rq = 0; sq_state = sq->state; } else { return raw_qp_param->set_mask ? -EINVAL : 0; } break; case MLX5_CMD_OP_INIT2INIT_QP: case MLX5_CMD_OP_INIT2RTR_QP: if (raw_qp_param->set_mask) return -EINVAL; else return 0; default: WARN_ON(1); return -EINVAL; } if (modify_rq) { err = modify_raw_packet_qp_rq(dev, rq, rq_state, raw_qp_param); if (err) return err; } if (modify_sq) { if (tx_affinity) { err = modify_raw_packet_tx_affinity(dev->mdev, sq, tx_affinity); if (err) return err; } return modify_raw_packet_qp_sq(dev->mdev, sq, sq_state, raw_qp_param); } return 0; } static int __mlx5_ib_modify_qp(struct ib_qp *ibqp, const struct ib_qp_attr *attr, int attr_mask, enum ib_qp_state cur_state, enum ib_qp_state new_state, const struct mlx5_ib_modify_qp *ucmd) { static const u16 optab[MLX5_QP_NUM_STATE][MLX5_QP_NUM_STATE] = { [MLX5_QP_STATE_RST] = { [MLX5_QP_STATE_RST] = MLX5_CMD_OP_2RST_QP, [MLX5_QP_STATE_ERR] = MLX5_CMD_OP_2ERR_QP, [MLX5_QP_STATE_INIT] = MLX5_CMD_OP_RST2INIT_QP, }, [MLX5_QP_STATE_INIT] = { [MLX5_QP_STATE_RST] = MLX5_CMD_OP_2RST_QP, [MLX5_QP_STATE_ERR] = MLX5_CMD_OP_2ERR_QP, [MLX5_QP_STATE_INIT] = MLX5_CMD_OP_INIT2INIT_QP, [MLX5_QP_STATE_RTR] = MLX5_CMD_OP_INIT2RTR_QP, }, [MLX5_QP_STATE_RTR] = { [MLX5_QP_STATE_RST] = MLX5_CMD_OP_2RST_QP, [MLX5_QP_STATE_ERR] = MLX5_CMD_OP_2ERR_QP, [MLX5_QP_STATE_RTS] = MLX5_CMD_OP_RTR2RTS_QP, }, [MLX5_QP_STATE_RTS] = { [MLX5_QP_STATE_RST] = MLX5_CMD_OP_2RST_QP, [MLX5_QP_STATE_ERR] = MLX5_CMD_OP_2ERR_QP, [MLX5_QP_STATE_RTS] = MLX5_CMD_OP_RTS2RTS_QP, }, [MLX5_QP_STATE_SQD] = { [MLX5_QP_STATE_RST] = MLX5_CMD_OP_2RST_QP, [MLX5_QP_STATE_ERR] = MLX5_CMD_OP_2ERR_QP, }, [MLX5_QP_STATE_SQER] = { [MLX5_QP_STATE_RST] = MLX5_CMD_OP_2RST_QP, [MLX5_QP_STATE_ERR] = MLX5_CMD_OP_2ERR_QP, [MLX5_QP_STATE_RTS] = MLX5_CMD_OP_SQERR2RTS_QP, }, [MLX5_QP_STATE_ERR] = { [MLX5_QP_STATE_RST] = MLX5_CMD_OP_2RST_QP, [MLX5_QP_STATE_ERR] = MLX5_CMD_OP_2ERR_QP, } }; struct mlx5_ib_dev *dev = to_mdev(ibqp->device); struct mlx5_ib_qp *qp = to_mqp(ibqp); struct mlx5_ib_qp_base *base = &qp->trans_qp.base; struct mlx5_ib_cq *send_cq, *recv_cq; struct mlx5_qp_context *context; struct mlx5_ib_pd *pd; struct mlx5_ib_port *mibport = NULL; enum mlx5_qp_state mlx5_cur, mlx5_new; enum mlx5_qp_optpar optpar; int mlx5_st; int err; u16 op; u8 tx_affinity = 0; mlx5_st = to_mlx5_st(ibqp->qp_type == IB_QPT_DRIVER ? qp->qp_sub_type : ibqp->qp_type); if (mlx5_st < 0) return -EINVAL; context = kzalloc(sizeof(*context), GFP_KERNEL); if (!context) return -ENOMEM; context->flags = cpu_to_be32(mlx5_st << 16); if (!(attr_mask & IB_QP_PATH_MIG_STATE)) { context->flags |= cpu_to_be32(MLX5_QP_PM_MIGRATED << 11); } else { switch (attr->path_mig_state) { case IB_MIG_MIGRATED: context->flags |= cpu_to_be32(MLX5_QP_PM_MIGRATED << 11); break; case IB_MIG_REARM: context->flags |= cpu_to_be32(MLX5_QP_PM_REARM << 11); break; case IB_MIG_ARMED: context->flags |= cpu_to_be32(MLX5_QP_PM_ARMED << 11); break; } } if ((cur_state == IB_QPS_RESET) && (new_state == IB_QPS_INIT)) { if ((ibqp->qp_type == IB_QPT_RC) || (ibqp->qp_type == IB_QPT_UD && !(qp->flags & MLX5_IB_QP_SQPN_QP1)) || (ibqp->qp_type == IB_QPT_UC) || (ibqp->qp_type == IB_QPT_RAW_PACKET) || (ibqp->qp_type == IB_QPT_XRC_INI) || (ibqp->qp_type == IB_QPT_XRC_TGT)) { if (mlx5_lag_is_active(dev->mdev)) { u8 p = mlx5_core_native_port_num(dev->mdev); tx_affinity = (unsigned int)atomic_add_return(1, &dev->roce[p].next_port) % MLX5_MAX_PORTS + 1; context->flags |= cpu_to_be32(tx_affinity << 24); } } } if (is_sqp(ibqp->qp_type)) { context->mtu_msgmax = (IB_MTU_256 << 5) | 8; } else if ((ibqp->qp_type == IB_QPT_UD && !(qp->flags & MLX5_IB_QP_UNDERLAY)) || ibqp->qp_type == MLX5_IB_QPT_REG_UMR) { context->mtu_msgmax = (IB_MTU_4096 << 5) | 12; } else if (attr_mask & IB_QP_PATH_MTU) { if (attr->path_mtu < IB_MTU_256 || attr->path_mtu > IB_MTU_4096) { mlx5_ib_warn(dev, "invalid mtu %d\n", attr->path_mtu); err = -EINVAL; goto out; } context->mtu_msgmax = (attr->path_mtu << 5) | (u8)MLX5_CAP_GEN(dev->mdev, log_max_msg); } if (attr_mask & IB_QP_DEST_QPN) context->log_pg_sz_remote_qpn = cpu_to_be32(attr->dest_qp_num); if (attr_mask & IB_QP_PKEY_INDEX) context->pri_path.pkey_index = cpu_to_be16(attr->pkey_index); /* todo implement counter_index functionality */ if (is_sqp(ibqp->qp_type)) context->pri_path.port = qp->port; if (attr_mask & IB_QP_PORT) context->pri_path.port = attr->port_num; if (attr_mask & IB_QP_AV) { err = mlx5_set_path(dev, qp, &attr->ah_attr, &context->pri_path, attr_mask & IB_QP_PORT ? attr->port_num : qp->port, attr_mask, 0, attr, false); if (err) goto out; } if (attr_mask & IB_QP_TIMEOUT) context->pri_path.ackto_lt |= attr->timeout << 3; if (attr_mask & IB_QP_ALT_PATH) { err = mlx5_set_path(dev, qp, &attr->alt_ah_attr, &context->alt_path, attr->alt_port_num, attr_mask | IB_QP_PKEY_INDEX | IB_QP_TIMEOUT, 0, attr, true); if (err) goto out; } pd = get_pd(qp); get_cqs(qp->ibqp.qp_type, qp->ibqp.send_cq, qp->ibqp.recv_cq, &send_cq, &recv_cq); context->flags_pd = cpu_to_be32(pd ? pd->pdn : to_mpd(dev->devr.p0)->pdn); context->cqn_send = send_cq ? cpu_to_be32(send_cq->mcq.cqn) : 0; context->cqn_recv = recv_cq ? cpu_to_be32(recv_cq->mcq.cqn) : 0; context->params1 = cpu_to_be32(MLX5_IB_ACK_REQ_FREQ << 28); if (attr_mask & IB_QP_RNR_RETRY) context->params1 |= cpu_to_be32(attr->rnr_retry << 13); if (attr_mask & IB_QP_RETRY_CNT) context->params1 |= cpu_to_be32(attr->retry_cnt << 16); if (attr_mask & IB_QP_MAX_QP_RD_ATOMIC) { if (attr->max_rd_atomic) context->params1 |= cpu_to_be32(fls(attr->max_rd_atomic - 1) << 21); } if (attr_mask & IB_QP_SQ_PSN) context->next_send_psn = cpu_to_be32(attr->sq_psn); if (attr_mask & IB_QP_MAX_DEST_RD_ATOMIC) { if (attr->max_dest_rd_atomic) context->params2 |= cpu_to_be32(fls(attr->max_dest_rd_atomic - 1) << 21); } if (attr_mask & (IB_QP_ACCESS_FLAGS | IB_QP_MAX_DEST_RD_ATOMIC)) context->params2 |= to_mlx5_access_flags(qp, attr, attr_mask); if (attr_mask & IB_QP_MIN_RNR_TIMER) context->rnr_nextrecvpsn |= cpu_to_be32(attr->min_rnr_timer << 24); if (attr_mask & IB_QP_RQ_PSN) context->rnr_nextrecvpsn |= cpu_to_be32(attr->rq_psn); if (attr_mask & IB_QP_QKEY) context->qkey = cpu_to_be32(attr->qkey); if (qp->rq.wqe_cnt && cur_state == IB_QPS_RESET && new_state == IB_QPS_INIT) context->db_rec_addr = cpu_to_be64(qp->db.dma); if (cur_state == IB_QPS_RESET && new_state == IB_QPS_INIT) { u8 port_num = (attr_mask & IB_QP_PORT ? attr->port_num : qp->port) - 1; /* Underlay port should be used - index 0 function per port */ if (qp->flags & MLX5_IB_QP_UNDERLAY) port_num = 0; mibport = &dev->port[port_num]; context->qp_counter_set_usr_page |= cpu_to_be32((u32)(mibport->cnts.set_id) << 24); } if (!ibqp->uobject && cur_state == IB_QPS_RESET && new_state == IB_QPS_INIT) context->sq_crq_size |= cpu_to_be16(1 << 4); if (qp->flags & MLX5_IB_QP_SQPN_QP1) context->deth_sqpn = cpu_to_be32(1); mlx5_cur = to_mlx5_state(cur_state); mlx5_new = to_mlx5_state(new_state); if (mlx5_cur >= MLX5_QP_NUM_STATE || mlx5_new >= MLX5_QP_NUM_STATE || !optab[mlx5_cur][mlx5_new]) { err = -EINVAL; goto out; } op = optab[mlx5_cur][mlx5_new]; optpar = ib_mask_to_mlx5_opt(attr_mask); optpar &= opt_mask[mlx5_cur][mlx5_new][mlx5_st]; if (qp->ibqp.qp_type == IB_QPT_RAW_PACKET || qp->flags & MLX5_IB_QP_UNDERLAY) { struct mlx5_modify_raw_qp_param raw_qp_param = {}; raw_qp_param.operation = op; if (cur_state == IB_QPS_RESET && new_state == IB_QPS_INIT) { raw_qp_param.rq_q_ctr_id = mibport->cnts.set_id; raw_qp_param.set_mask |= MLX5_RAW_QP_MOD_SET_RQ_Q_CTR_ID; } if (attr_mask & IB_QP_RATE_LIMIT) { raw_qp_param.rl.rate = attr->rate_limit; if (ucmd->burst_info.max_burst_sz) { if (attr->rate_limit && MLX5_CAP_QOS(dev->mdev, packet_pacing_burst_bound)) { raw_qp_param.rl.max_burst_sz = ucmd->burst_info.max_burst_sz; } else { err = -EINVAL; goto out; } } if (ucmd->burst_info.typical_pkt_sz) { if (attr->rate_limit && MLX5_CAP_QOS(dev->mdev, packet_pacing_typical_size)) { raw_qp_param.rl.typical_pkt_sz = ucmd->burst_info.typical_pkt_sz; } else { err = -EINVAL; goto out; } } raw_qp_param.set_mask |= MLX5_RAW_QP_RATE_LIMIT; } err = modify_raw_packet_qp(dev, qp, &raw_qp_param, tx_affinity); } else { err = mlx5_core_qp_modify(dev->mdev, op, optpar, context, &base->mqp); } if (err) goto out; qp->state = new_state; if (attr_mask & IB_QP_ACCESS_FLAGS) qp->trans_qp.atomic_rd_en = attr->qp_access_flags; if (attr_mask & IB_QP_MAX_DEST_RD_ATOMIC) qp->trans_qp.resp_depth = attr->max_dest_rd_atomic; if (attr_mask & IB_QP_PORT) qp->port = attr->port_num; if (attr_mask & IB_QP_ALT_PATH) qp->trans_qp.alt_port = attr->alt_port_num; /* * If we moved a kernel QP to RESET, clean up all old CQ * entries and reinitialize the QP. */ if (new_state == IB_QPS_RESET && !ibqp->uobject && ibqp->qp_type != IB_QPT_XRC_TGT) { mlx5_ib_cq_clean(recv_cq, base->mqp.qpn, ibqp->srq ? to_msrq(ibqp->srq) : NULL); if (send_cq != recv_cq) mlx5_ib_cq_clean(send_cq, base->mqp.qpn, NULL); qp->rq.head = 0; qp->rq.tail = 0; qp->sq.head = 0; qp->sq.tail = 0; qp->sq.cur_post = 0; qp->sq.last_poll = 0; qp->db.db[MLX5_RCV_DBR] = 0; qp->db.db[MLX5_SND_DBR] = 0; } out: kfree(context); return err; } static inline bool is_valid_mask(int mask, int req, int opt) { if ((mask & req) != req) return false; if (mask & ~(req | opt)) return false; return true; } /* check valid transition for driver QP types * for now the only QP type that this function supports is DCI */ static bool modify_dci_qp_is_ok(enum ib_qp_state cur_state, enum ib_qp_state new_state, enum ib_qp_attr_mask attr_mask) { int req = IB_QP_STATE; int opt = 0; if (cur_state == IB_QPS_RESET && new_state == IB_QPS_INIT) { req |= IB_QP_PKEY_INDEX | IB_QP_PORT; return is_valid_mask(attr_mask, req, opt); } else if (cur_state == IB_QPS_INIT && new_state == IB_QPS_INIT) { opt = IB_QP_PKEY_INDEX | IB_QP_PORT; return is_valid_mask(attr_mask, req, opt); } else if (cur_state == IB_QPS_INIT && new_state == IB_QPS_RTR) { req |= IB_QP_PATH_MTU; opt = IB_QP_PKEY_INDEX; return is_valid_mask(attr_mask, req, opt); } else if (cur_state == IB_QPS_RTR && new_state == IB_QPS_RTS) { req |= IB_QP_TIMEOUT | IB_QP_RETRY_CNT | IB_QP_RNR_RETRY | IB_QP_MAX_QP_RD_ATOMIC | IB_QP_SQ_PSN; opt = IB_QP_MIN_RNR_TIMER; return is_valid_mask(attr_mask, req, opt); } else if (cur_state == IB_QPS_RTS && new_state == IB_QPS_RTS) { opt = IB_QP_MIN_RNR_TIMER; return is_valid_mask(attr_mask, req, opt); } else if (cur_state != IB_QPS_RESET && new_state == IB_QPS_ERR) { return is_valid_mask(attr_mask, req, opt); } return false; } /* mlx5_ib_modify_dct: modify a DCT QP * valid transitions are: * RESET to INIT: must set access_flags, pkey_index and port * INIT to RTR : must set min_rnr_timer, tclass, flow_label, * mtu, gid_index and hop_limit * Other transitions and attributes are illegal */ static int mlx5_ib_modify_dct(struct ib_qp *ibqp, struct ib_qp_attr *attr, int attr_mask, struct ib_udata *udata) { struct mlx5_ib_qp *qp = to_mqp(ibqp); struct mlx5_ib_dev *dev = to_mdev(ibqp->device); enum ib_qp_state cur_state, new_state; int err = 0; int required = IB_QP_STATE; void *dctc; if (!(attr_mask & IB_QP_STATE)) return -EINVAL; cur_state = qp->state; new_state = attr->qp_state; dctc = MLX5_ADDR_OF(create_dct_in, qp->dct.in, dct_context_entry); if (cur_state == IB_QPS_RESET && new_state == IB_QPS_INIT) { required |= IB_QP_ACCESS_FLAGS | IB_QP_PKEY_INDEX | IB_QP_PORT; if (!is_valid_mask(attr_mask, required, 0)) return -EINVAL; if (attr->port_num == 0 || attr->port_num > MLX5_CAP_GEN(dev->mdev, num_ports)) { mlx5_ib_dbg(dev, "invalid port number %d. number of ports is %d\n", attr->port_num, dev->num_ports); return -EINVAL; } if (attr->qp_access_flags & IB_ACCESS_REMOTE_READ) MLX5_SET(dctc, dctc, rre, 1); if (attr->qp_access_flags & IB_ACCESS_REMOTE_WRITE) MLX5_SET(dctc, dctc, rwe, 1); if (attr->qp_access_flags & IB_ACCESS_REMOTE_ATOMIC) { if (!mlx5_ib_dc_atomic_is_supported(dev)) return -EOPNOTSUPP; MLX5_SET(dctc, dctc, rae, 1); MLX5_SET(dctc, dctc, atomic_mode, MLX5_ATOMIC_MODE_DCT_CX); } MLX5_SET(dctc, dctc, pkey_index, attr->pkey_index); MLX5_SET(dctc, dctc, port, attr->port_num); MLX5_SET(dctc, dctc, counter_set_id, dev->port[attr->port_num - 1].cnts.set_id); } else if (cur_state == IB_QPS_INIT && new_state == IB_QPS_RTR) { struct mlx5_ib_modify_qp_resp resp = {}; u32 min_resp_len = offsetof(typeof(resp), dctn) + sizeof(resp.dctn); if (udata->outlen < min_resp_len) return -EINVAL; resp.response_length = min_resp_len; required |= IB_QP_MIN_RNR_TIMER | IB_QP_AV | IB_QP_PATH_MTU; if (!is_valid_mask(attr_mask, required, 0)) return -EINVAL; MLX5_SET(dctc, dctc, min_rnr_nak, attr->min_rnr_timer); MLX5_SET(dctc, dctc, tclass, attr->ah_attr.grh.traffic_class); MLX5_SET(dctc, dctc, flow_label, attr->ah_attr.grh.flow_label); MLX5_SET(dctc, dctc, mtu, attr->path_mtu); MLX5_SET(dctc, dctc, my_addr_index, attr->ah_attr.grh.sgid_index); MLX5_SET(dctc, dctc, hop_limit, attr->ah_attr.grh.hop_limit); err = mlx5_core_create_dct(dev->mdev, &qp->dct.mdct, qp->dct.in, MLX5_ST_SZ_BYTES(create_dct_in)); if (err) return err; resp.dctn = qp->dct.mdct.mqp.qpn; err = ib_copy_to_udata(udata, &resp, resp.response_length); if (err) { mlx5_core_destroy_dct(dev->mdev, &qp->dct.mdct); return err; } } else { mlx5_ib_warn(dev, "Modify DCT: Invalid transition from %d to %d\n", cur_state, new_state); return -EINVAL; } if (err) qp->state = IB_QPS_ERR; else qp->state = new_state; return err; } int mlx5_ib_modify_qp(struct ib_qp *ibqp, struct ib_qp_attr *attr, int attr_mask, struct ib_udata *udata) { struct mlx5_ib_dev *dev = to_mdev(ibqp->device); struct mlx5_ib_qp *qp = to_mqp(ibqp); struct mlx5_ib_modify_qp ucmd = {}; enum ib_qp_type qp_type; enum ib_qp_state cur_state, new_state; size_t required_cmd_sz; int err = -EINVAL; int port; enum rdma_link_layer ll = IB_LINK_LAYER_UNSPECIFIED; if (ibqp->rwq_ind_tbl) return -ENOSYS; if (udata && udata->inlen) { required_cmd_sz = offsetof(typeof(ucmd), reserved) + sizeof(ucmd.reserved); if (udata->inlen < required_cmd_sz) return -EINVAL; if (udata->inlen > sizeof(ucmd) && !ib_is_udata_cleared(udata, sizeof(ucmd), udata->inlen - sizeof(ucmd))) return -EOPNOTSUPP; if (ib_copy_from_udata(&ucmd, udata, min(udata->inlen, sizeof(ucmd)))) return -EFAULT; if (ucmd.comp_mask || memchr_inv(&ucmd.reserved, 0, sizeof(ucmd.reserved)) || memchr_inv(&ucmd.burst_info.reserved, 0, sizeof(ucmd.burst_info.reserved))) return -EOPNOTSUPP; } if (unlikely(ibqp->qp_type == IB_QPT_GSI)) return mlx5_ib_gsi_modify_qp(ibqp, attr, attr_mask); if (ibqp->qp_type == IB_QPT_DRIVER) qp_type = qp->qp_sub_type; else qp_type = (unlikely(ibqp->qp_type == MLX5_IB_QPT_HW_GSI)) ? IB_QPT_GSI : ibqp->qp_type; if (qp_type == MLX5_IB_QPT_DCT) return mlx5_ib_modify_dct(ibqp, attr, attr_mask, udata); mutex_lock(&qp->mutex); cur_state = attr_mask & IB_QP_CUR_STATE ? attr->cur_qp_state : qp->state; new_state = attr_mask & IB_QP_STATE ? attr->qp_state : cur_state; if (!(cur_state == new_state && cur_state == IB_QPS_RESET)) { port = attr_mask & IB_QP_PORT ? attr->port_num : qp->port; ll = dev->ib_dev.get_link_layer(&dev->ib_dev, port); } if (qp->flags & MLX5_IB_QP_UNDERLAY) { if (attr_mask & ~(IB_QP_STATE | IB_QP_CUR_STATE)) { mlx5_ib_dbg(dev, "invalid attr_mask 0x%x when underlay QP is used\n", attr_mask); goto out; } } else if (qp_type != MLX5_IB_QPT_REG_UMR && qp_type != MLX5_IB_QPT_DCI && !ib_modify_qp_is_ok(cur_state, new_state, qp_type, attr_mask, ll)) { mlx5_ib_dbg(dev, "invalid QP state transition from %d to %d, qp_type %d, attr_mask 0x%x\n", cur_state, new_state, ibqp->qp_type, attr_mask); goto out; } else if (qp_type == MLX5_IB_QPT_DCI && !modify_dci_qp_is_ok(cur_state, new_state, attr_mask)) { mlx5_ib_dbg(dev, "invalid QP state transition from %d to %d, qp_type %d, attr_mask 0x%x\n", cur_state, new_state, qp_type, attr_mask); goto out; } if ((attr_mask & IB_QP_PORT) && (attr->port_num == 0 || attr->port_num > dev->num_ports)) { mlx5_ib_dbg(dev, "invalid port number %d. number of ports is %d\n", attr->port_num, dev->num_ports); goto out; } if (attr_mask & IB_QP_PKEY_INDEX) { port = attr_mask & IB_QP_PORT ? attr->port_num : qp->port; if (attr->pkey_index >= dev->mdev->port_caps[port - 1].pkey_table_len) { mlx5_ib_dbg(dev, "invalid pkey index %d\n", attr->pkey_index); goto out; } } if (attr_mask & IB_QP_MAX_QP_RD_ATOMIC && attr->max_rd_atomic > (1 << MLX5_CAP_GEN(dev->mdev, log_max_ra_res_qp))) { mlx5_ib_dbg(dev, "invalid max_rd_atomic value %d\n", attr->max_rd_atomic); goto out; } if (attr_mask & IB_QP_MAX_DEST_RD_ATOMIC && attr->max_dest_rd_atomic > (1 << MLX5_CAP_GEN(dev->mdev, log_max_ra_req_qp))) { mlx5_ib_dbg(dev, "invalid max_dest_rd_atomic value %d\n", attr->max_dest_rd_atomic); goto out; } if (cur_state == new_state && cur_state == IB_QPS_RESET) { err = 0; goto out; } err = __mlx5_ib_modify_qp(ibqp, attr, attr_mask, cur_state, new_state, &ucmd); out: mutex_unlock(&qp->mutex); return err; } static int mlx5_wq_overflow(struct mlx5_ib_wq *wq, int nreq, struct ib_cq *ib_cq) { struct mlx5_ib_cq *cq; unsigned cur; cur = wq->head - wq->tail; if (likely(cur + nreq < wq->max_post)) return 0; cq = to_mcq(ib_cq); spin_lock(&cq->lock); cur = wq->head - wq->tail; spin_unlock(&cq->lock); return cur + nreq >= wq->max_post; } static __always_inline void set_raddr_seg(struct mlx5_wqe_raddr_seg *rseg, u64 remote_addr, u32 rkey) { rseg->raddr = cpu_to_be64(remote_addr); rseg->rkey = cpu_to_be32(rkey); rseg->reserved = 0; } static void *set_eth_seg(struct mlx5_wqe_eth_seg *eseg, const struct ib_send_wr *wr, void *qend, struct mlx5_ib_qp *qp, int *size) { void *seg = eseg; memset(eseg, 0, sizeof(struct mlx5_wqe_eth_seg)); if (wr->send_flags & IB_SEND_IP_CSUM) eseg->cs_flags = MLX5_ETH_WQE_L3_CSUM | MLX5_ETH_WQE_L4_CSUM; seg += sizeof(struct mlx5_wqe_eth_seg); *size += sizeof(struct mlx5_wqe_eth_seg) / 16; if (wr->opcode == IB_WR_LSO) { struct ib_ud_wr *ud_wr = container_of(wr, struct ib_ud_wr, wr); int size_of_inl_hdr_start = sizeof(eseg->inline_hdr.start); u64 left, leftlen, copysz; void *pdata = ud_wr->header; left = ud_wr->hlen; eseg->mss = cpu_to_be16(ud_wr->mss); eseg->inline_hdr.sz = cpu_to_be16(left); /* * check if there is space till the end of queue, if yes, * copy all in one shot, otherwise copy till the end of queue, * rollback and than the copy the left */ leftlen = qend - (void *)eseg->inline_hdr.start; copysz = min_t(u64, leftlen, left); memcpy(seg - size_of_inl_hdr_start, pdata, copysz); if (likely(copysz > size_of_inl_hdr_start)) { seg += ALIGN(copysz - size_of_inl_hdr_start, 16); *size += ALIGN(copysz - size_of_inl_hdr_start, 16) / 16; } if (unlikely(copysz < left)) { /* the last wqe in the queue */ seg = mlx5_get_send_wqe(qp, 0); left -= copysz; pdata += copysz; memcpy(seg, pdata, left); seg += ALIGN(left, 16); *size += ALIGN(left, 16) / 16; } } return seg; } static void set_datagram_seg(struct mlx5_wqe_datagram_seg *dseg, const struct ib_send_wr *wr) { memcpy(&dseg->av, &to_mah(ud_wr(wr)->ah)->av, sizeof(struct mlx5_av)); dseg->av.dqp_dct = cpu_to_be32(ud_wr(wr)->remote_qpn | MLX5_EXTENDED_UD_AV); dseg->av.key.qkey.qkey = cpu_to_be32(ud_wr(wr)->remote_qkey); } static void set_data_ptr_seg(struct mlx5_wqe_data_seg *dseg, struct ib_sge *sg) { dseg->byte_count = cpu_to_be32(sg->length); dseg->lkey = cpu_to_be32(sg->lkey); dseg->addr = cpu_to_be64(sg->addr); } static u64 get_xlt_octo(u64 bytes) { return ALIGN(bytes, MLX5_IB_UMR_XLT_ALIGNMENT) / MLX5_IB_UMR_OCTOWORD; } static __be64 frwr_mkey_mask(void) { u64 result; result = MLX5_MKEY_MASK_LEN | MLX5_MKEY_MASK_PAGE_SIZE | MLX5_MKEY_MASK_START_ADDR | MLX5_MKEY_MASK_EN_RINVAL | MLX5_MKEY_MASK_KEY | MLX5_MKEY_MASK_LR | MLX5_MKEY_MASK_LW | MLX5_MKEY_MASK_RR | MLX5_MKEY_MASK_RW | MLX5_MKEY_MASK_A | MLX5_MKEY_MASK_SMALL_FENCE | MLX5_MKEY_MASK_FREE; return cpu_to_be64(result); } static __be64 sig_mkey_mask(void) { u64 result; result = MLX5_MKEY_MASK_LEN | MLX5_MKEY_MASK_PAGE_SIZE | MLX5_MKEY_MASK_START_ADDR | MLX5_MKEY_MASK_EN_SIGERR | MLX5_MKEY_MASK_EN_RINVAL | MLX5_MKEY_MASK_KEY | MLX5_MKEY_MASK_LR | MLX5_MKEY_MASK_LW | MLX5_MKEY_MASK_RR | MLX5_MKEY_MASK_RW | MLX5_MKEY_MASK_SMALL_FENCE | MLX5_MKEY_MASK_FREE | MLX5_MKEY_MASK_BSF_EN; return cpu_to_be64(result); } static void set_reg_umr_seg(struct mlx5_wqe_umr_ctrl_seg *umr, struct mlx5_ib_mr *mr, bool umr_inline) { int size = mr->ndescs * mr->desc_size; memset(umr, 0, sizeof(*umr)); umr->flags = MLX5_UMR_CHECK_NOT_FREE; if (umr_inline) umr->flags |= MLX5_UMR_INLINE; umr->xlt_octowords = cpu_to_be16(get_xlt_octo(size)); umr->mkey_mask = frwr_mkey_mask(); } static void set_linv_umr_seg(struct mlx5_wqe_umr_ctrl_seg *umr) { memset(umr, 0, sizeof(*umr)); umr->mkey_mask = cpu_to_be64(MLX5_MKEY_MASK_FREE); umr->flags = MLX5_UMR_INLINE; } static __be64 get_umr_enable_mr_mask(void) { u64 result; result = MLX5_MKEY_MASK_KEY | MLX5_MKEY_MASK_FREE; return cpu_to_be64(result); } static __be64 get_umr_disable_mr_mask(void) { u64 result; result = MLX5_MKEY_MASK_FREE; return cpu_to_be64(result); } static __be64 get_umr_update_translation_mask(void) { u64 result; result = MLX5_MKEY_MASK_LEN | MLX5_MKEY_MASK_PAGE_SIZE | MLX5_MKEY_MASK_START_ADDR; return cpu_to_be64(result); } static __be64 get_umr_update_access_mask(int atomic) { u64 result; result = MLX5_MKEY_MASK_LR | MLX5_MKEY_MASK_LW | MLX5_MKEY_MASK_RR | MLX5_MKEY_MASK_RW; if (atomic) result |= MLX5_MKEY_MASK_A; return cpu_to_be64(result); } static __be64 get_umr_update_pd_mask(void) { u64 result; result = MLX5_MKEY_MASK_PD; return cpu_to_be64(result); } static int umr_check_mkey_mask(struct mlx5_ib_dev *dev, u64 mask) { if ((mask & MLX5_MKEY_MASK_PAGE_SIZE && MLX5_CAP_GEN(dev->mdev, umr_modify_entity_size_disabled)) || (mask & MLX5_MKEY_MASK_A && MLX5_CAP_GEN(dev->mdev, umr_modify_atomic_disabled))) return -EPERM; return 0; } static int set_reg_umr_segment(struct mlx5_ib_dev *dev, struct mlx5_wqe_umr_ctrl_seg *umr, const struct ib_send_wr *wr, int atomic) { const struct mlx5_umr_wr *umrwr = umr_wr(wr); memset(umr, 0, sizeof(*umr)); if (wr->send_flags & MLX5_IB_SEND_UMR_FAIL_IF_FREE) umr->flags = MLX5_UMR_CHECK_FREE; /* fail if free */ else umr->flags = MLX5_UMR_CHECK_NOT_FREE; /* fail if not free */ umr->xlt_octowords = cpu_to_be16(get_xlt_octo(umrwr->xlt_size)); if (wr->send_flags & MLX5_IB_SEND_UMR_UPDATE_XLT) { u64 offset = get_xlt_octo(umrwr->offset); umr->xlt_offset = cpu_to_be16(offset & 0xffff); umr->xlt_offset_47_16 = cpu_to_be32(offset >> 16); umr->flags |= MLX5_UMR_TRANSLATION_OFFSET_EN; } if (wr->send_flags & MLX5_IB_SEND_UMR_UPDATE_TRANSLATION) umr->mkey_mask |= get_umr_update_translation_mask(); if (wr->send_flags & MLX5_IB_SEND_UMR_UPDATE_PD_ACCESS) { umr->mkey_mask |= get_umr_update_access_mask(atomic); umr->mkey_mask |= get_umr_update_pd_mask(); } if (wr->send_flags & MLX5_IB_SEND_UMR_ENABLE_MR) umr->mkey_mask |= get_umr_enable_mr_mask(); if (wr->send_flags & MLX5_IB_SEND_UMR_DISABLE_MR) umr->mkey_mask |= get_umr_disable_mr_mask(); if (!wr->num_sge) umr->flags |= MLX5_UMR_INLINE; return umr_check_mkey_mask(dev, be64_to_cpu(umr->mkey_mask)); } static u8 get_umr_flags(int acc) { return (acc & IB_ACCESS_REMOTE_ATOMIC ? MLX5_PERM_ATOMIC : 0) | (acc & IB_ACCESS_REMOTE_WRITE ? MLX5_PERM_REMOTE_WRITE : 0) | (acc & IB_ACCESS_REMOTE_READ ? MLX5_PERM_REMOTE_READ : 0) | (acc & IB_ACCESS_LOCAL_WRITE ? MLX5_PERM_LOCAL_WRITE : 0) | MLX5_PERM_LOCAL_READ | MLX5_PERM_UMR_EN; } static void set_reg_mkey_seg(struct mlx5_mkey_seg *seg, struct mlx5_ib_mr *mr, u32 key, int access) { int ndescs = ALIGN(mr->ndescs, 8) >> 1; memset(seg, 0, sizeof(*seg)); if (mr->access_mode == MLX5_MKC_ACCESS_MODE_MTT) seg->log2_page_size = ilog2(mr->ibmr.page_size); else if (mr->access_mode == MLX5_MKC_ACCESS_MODE_KLMS) /* KLMs take twice the size of MTTs */ ndescs *= 2; seg->flags = get_umr_flags(access) | mr->access_mode; seg->qpn_mkey7_0 = cpu_to_be32((key & 0xff) | 0xffffff00); seg->flags_pd = cpu_to_be32(MLX5_MKEY_REMOTE_INVAL); seg->start_addr = cpu_to_be64(mr->ibmr.iova); seg->len = cpu_to_be64(mr->ibmr.length); seg->xlt_oct_size = cpu_to_be32(ndescs); } static void set_linv_mkey_seg(struct mlx5_mkey_seg *seg) { memset(seg, 0, sizeof(*seg)); seg->status = MLX5_MKEY_STATUS_FREE; } static void set_reg_mkey_segment(struct mlx5_mkey_seg *seg, const struct ib_send_wr *wr) { const struct mlx5_umr_wr *umrwr = umr_wr(wr); memset(seg, 0, sizeof(*seg)); if (wr->send_flags & MLX5_IB_SEND_UMR_DISABLE_MR) seg->status = MLX5_MKEY_STATUS_FREE; seg->flags = convert_access(umrwr->access_flags); if (umrwr->pd) seg->flags_pd = cpu_to_be32(to_mpd(umrwr->pd)->pdn); if (wr->send_flags & MLX5_IB_SEND_UMR_UPDATE_TRANSLATION && !umrwr->length) seg->flags_pd |= cpu_to_be32(MLX5_MKEY_LEN64); seg->start_addr = cpu_to_be64(umrwr->virt_addr); seg->len = cpu_to_be64(umrwr->length); seg->log2_page_size = umrwr->page_shift; seg->qpn_mkey7_0 = cpu_to_be32(0xffffff00 | mlx5_mkey_variant(umrwr->mkey)); } static void set_reg_data_seg(struct mlx5_wqe_data_seg *dseg, struct mlx5_ib_mr *mr, struct mlx5_ib_pd *pd) { int bcount = mr->desc_size * mr->ndescs; dseg->addr = cpu_to_be64(mr->desc_map); dseg->byte_count = cpu_to_be32(ALIGN(bcount, 64)); dseg->lkey = cpu_to_be32(pd->ibpd.local_dma_lkey); } static void set_reg_umr_inline_seg(void *seg, struct mlx5_ib_qp *qp, struct mlx5_ib_mr *mr, int mr_list_size) { void *qend = qp->sq.qend; void *addr = mr->descs; int copy; if (unlikely(seg + mr_list_size > qend)) { copy = qend - seg; memcpy(seg, addr, copy); addr += copy; mr_list_size -= copy; seg = mlx5_get_send_wqe(qp, 0); } memcpy(seg, addr, mr_list_size); seg += mr_list_size; } static __be32 send_ieth(const struct ib_send_wr *wr) { switch (wr->opcode) { case IB_WR_SEND_WITH_IMM: case IB_WR_RDMA_WRITE_WITH_IMM: return wr->ex.imm_data; case IB_WR_SEND_WITH_INV: return cpu_to_be32(wr->ex.invalidate_rkey); default: return 0; } } static u8 calc_sig(void *wqe, int size) { u8 *p = wqe; u8 res = 0; int i; for (i = 0; i < size; i++) res ^= p[i]; return ~res; } static u8 wq_sig(void *wqe) { return calc_sig(wqe, (*((u8 *)wqe + 8) & 0x3f) << 4); } static int set_data_inl_seg(struct mlx5_ib_qp *qp, const struct ib_send_wr *wr, void *wqe, int *sz) { struct mlx5_wqe_inline_seg *seg; void *qend = qp->sq.qend; void *addr; int inl = 0; int copy; int len; int i; seg = wqe; wqe += sizeof(*seg); for (i = 0; i < wr->num_sge; i++) { addr = (void *)(unsigned long)(wr->sg_list[i].addr); len = wr->sg_list[i].length; inl += len; if (unlikely(inl > qp->max_inline_data)) return -ENOMEM; if (unlikely(wqe + len > qend)) { copy = qend - wqe; memcpy(wqe, addr, copy); addr += copy; len -= copy; wqe = mlx5_get_send_wqe(qp, 0); } memcpy(wqe, addr, len); wqe += len; } seg->byte_count = cpu_to_be32(inl | MLX5_INLINE_SEG); *sz = ALIGN(inl + sizeof(seg->byte_count), 16) / 16; return 0; } static u16 prot_field_size(enum ib_signature_type type) { switch (type) { case IB_SIG_TYPE_T10_DIF: return MLX5_DIF_SIZE; default: return 0; } } static u8 bs_selector(int block_size) { switch (block_size) { case 512: return 0x1; case 520: return 0x2; case 4096: return 0x3; case 4160: return 0x4; case 1073741824: return 0x5; default: return 0; } } static void mlx5_fill_inl_bsf(struct ib_sig_domain *domain, struct mlx5_bsf_inl *inl) { /* Valid inline section and allow BSF refresh */ inl->vld_refresh = cpu_to_be16(MLX5_BSF_INL_VALID | MLX5_BSF_REFRESH_DIF); inl->dif_apptag = cpu_to_be16(domain->sig.dif.app_tag); inl->dif_reftag = cpu_to_be32(domain->sig.dif.ref_tag); /* repeating block */ inl->rp_inv_seed = MLX5_BSF_REPEAT_BLOCK; inl->sig_type = domain->sig.dif.bg_type == IB_T10DIF_CRC ? MLX5_DIF_CRC : MLX5_DIF_IPCS; if (domain->sig.dif.ref_remap) inl->dif_inc_ref_guard_check |= MLX5_BSF_INC_REFTAG; if (domain->sig.dif.app_escape) { if (domain->sig.dif.ref_escape) inl->dif_inc_ref_guard_check |= MLX5_BSF_APPREF_ESCAPE; else inl->dif_inc_ref_guard_check |= MLX5_BSF_APPTAG_ESCAPE; } inl->dif_app_bitmask_check = cpu_to_be16(domain->sig.dif.apptag_check_mask); } static int mlx5_set_bsf(struct ib_mr *sig_mr, struct ib_sig_attrs *sig_attrs, struct mlx5_bsf *bsf, u32 data_size) { struct mlx5_core_sig_ctx *msig = to_mmr(sig_mr)->sig; struct mlx5_bsf_basic *basic = &bsf->basic; struct ib_sig_domain *mem = &sig_attrs->mem; struct ib_sig_domain *wire = &sig_attrs->wire; memset(bsf, 0, sizeof(*bsf)); /* Basic + Extended + Inline */ basic->bsf_size_sbs = 1 << 7; /* Input domain check byte mask */ basic->check_byte_mask = sig_attrs->check_mask; basic->raw_data_size = cpu_to_be32(data_size); /* Memory domain */ switch (sig_attrs->mem.sig_type) { case IB_SIG_TYPE_NONE: break; case IB_SIG_TYPE_T10_DIF: basic->mem.bs_selector = bs_selector(mem->sig.dif.pi_interval); basic->m_bfs_psv = cpu_to_be32(msig->psv_memory.psv_idx); mlx5_fill_inl_bsf(mem, &bsf->m_inl); break; default: return -EINVAL; } /* Wire domain */ switch (sig_attrs->wire.sig_type) { case IB_SIG_TYPE_NONE: break; case IB_SIG_TYPE_T10_DIF: if (mem->sig.dif.pi_interval == wire->sig.dif.pi_interval && mem->sig_type == wire->sig_type) { /* Same block structure */ basic->bsf_size_sbs |= 1 << 4; if (mem->sig.dif.bg_type == wire->sig.dif.bg_type) basic->wire.copy_byte_mask |= MLX5_CPY_GRD_MASK; if (mem->sig.dif.app_tag == wire->sig.dif.app_tag) basic->wire.copy_byte_mask |= MLX5_CPY_APP_MASK; if (mem->sig.dif.ref_tag == wire->sig.dif.ref_tag) basic->wire.copy_byte_mask |= MLX5_CPY_REF_MASK; } else basic->wire.bs_selector = bs_selector(wire->sig.dif.pi_interval); basic->w_bfs_psv = cpu_to_be32(msig->psv_wire.psv_idx); mlx5_fill_inl_bsf(wire, &bsf->w_inl); break; default: return -EINVAL; } return 0; } static int set_sig_data_segment(const struct ib_sig_handover_wr *wr, struct mlx5_ib_qp *qp, void **seg, int *size) { struct ib_sig_attrs *sig_attrs = wr->sig_attrs; struct ib_mr *sig_mr = wr->sig_mr; struct mlx5_bsf *bsf; u32 data_len = wr->wr.sg_list->length; u32 data_key = wr->wr.sg_list->lkey; u64 data_va = wr->wr.sg_list->addr; int ret; int wqe_size; if (!wr->prot || (data_key == wr->prot->lkey && data_va == wr->prot->addr && data_len == wr->prot->length)) { /** * Source domain doesn't contain signature information * or data and protection are interleaved in memory. * So need construct: * ------------------ * | data_klm | * ------------------ * | BSF | * ------------------ **/ struct mlx5_klm *data_klm = *seg; data_klm->bcount = cpu_to_be32(data_len); data_klm->key = cpu_to_be32(data_key); data_klm->va = cpu_to_be64(data_va); wqe_size = ALIGN(sizeof(*data_klm), 64); } else { /** * Source domain contains signature information * So need construct a strided block format: * --------------------------- * | stride_block_ctrl | * --------------------------- * | data_klm | * --------------------------- * | prot_klm | * --------------------------- * | BSF | * --------------------------- **/ struct mlx5_stride_block_ctrl_seg *sblock_ctrl; struct mlx5_stride_block_entry *data_sentry; struct mlx5_stride_block_entry *prot_sentry; u32 prot_key = wr->prot->lkey; u64 prot_va = wr->prot->addr; u16 block_size = sig_attrs->mem.sig.dif.pi_interval; int prot_size; sblock_ctrl = *seg; data_sentry = (void *)sblock_ctrl + sizeof(*sblock_ctrl); prot_sentry = (void *)data_sentry + sizeof(*data_sentry); prot_size = prot_field_size(sig_attrs->mem.sig_type); if (!prot_size) { pr_err("Bad block size given: %u\n", block_size); return -EINVAL; } sblock_ctrl->bcount_per_cycle = cpu_to_be32(block_size + prot_size); sblock_ctrl->op = cpu_to_be32(MLX5_STRIDE_BLOCK_OP); sblock_ctrl->repeat_count = cpu_to_be32(data_len / block_size); sblock_ctrl->num_entries = cpu_to_be16(2); data_sentry->bcount = cpu_to_be16(block_size); data_sentry->key = cpu_to_be32(data_key); data_sentry->va = cpu_to_be64(data_va); data_sentry->stride = cpu_to_be16(block_size); prot_sentry->bcount = cpu_to_be16(prot_size); prot_sentry->key = cpu_to_be32(prot_key); prot_sentry->va = cpu_to_be64(prot_va); prot_sentry->stride = cpu_to_be16(prot_size); wqe_size = ALIGN(sizeof(*sblock_ctrl) + sizeof(*data_sentry) + sizeof(*prot_sentry), 64); } *seg += wqe_size; *size += wqe_size / 16; if (unlikely((*seg == qp->sq.qend))) *seg = mlx5_get_send_wqe(qp, 0); bsf = *seg; ret = mlx5_set_bsf(sig_mr, sig_attrs, bsf, data_len); if (ret) return -EINVAL; *seg += sizeof(*bsf); *size += sizeof(*bsf) / 16; if (unlikely((*seg == qp->sq.qend))) *seg = mlx5_get_send_wqe(qp, 0); return 0; } static void set_sig_mkey_segment(struct mlx5_mkey_seg *seg, const struct ib_sig_handover_wr *wr, u32 size, u32 length, u32 pdn) { struct ib_mr *sig_mr = wr->sig_mr; u32 sig_key = sig_mr->rkey; u8 sigerr = to_mmr(sig_mr)->sig->sigerr_count & 1; memset(seg, 0, sizeof(*seg)); seg->flags = get_umr_flags(wr->access_flags) | MLX5_MKC_ACCESS_MODE_KLMS; seg->qpn_mkey7_0 = cpu_to_be32((sig_key & 0xff) | 0xffffff00); seg->flags_pd = cpu_to_be32(MLX5_MKEY_REMOTE_INVAL | sigerr << 26 | MLX5_MKEY_BSF_EN | pdn); seg->len = cpu_to_be64(length); seg->xlt_oct_size = cpu_to_be32(get_xlt_octo(size)); seg->bsfs_octo_size = cpu_to_be32(MLX5_MKEY_BSF_OCTO_SIZE); } static void set_sig_umr_segment(struct mlx5_wqe_umr_ctrl_seg *umr, u32 size) { memset(umr, 0, sizeof(*umr)); umr->flags = MLX5_FLAGS_INLINE | MLX5_FLAGS_CHECK_FREE; umr->xlt_octowords = cpu_to_be16(get_xlt_octo(size)); umr->bsf_octowords = cpu_to_be16(MLX5_MKEY_BSF_OCTO_SIZE); umr->mkey_mask = sig_mkey_mask(); } static int set_sig_umr_wr(const struct ib_send_wr *send_wr, struct mlx5_ib_qp *qp, void **seg, int *size) { const struct ib_sig_handover_wr *wr = sig_handover_wr(send_wr); struct mlx5_ib_mr *sig_mr = to_mmr(wr->sig_mr); u32 pdn = get_pd(qp)->pdn; u32 xlt_size; int region_len, ret; if (unlikely(wr->wr.num_sge != 1) || unlikely(wr->access_flags & IB_ACCESS_REMOTE_ATOMIC) || unlikely(!sig_mr->sig) || unlikely(!qp->signature_en) || unlikely(!sig_mr->sig->sig_status_checked)) return -EINVAL; /* length of the protected region, data + protection */ region_len = wr->wr.sg_list->length; if (wr->prot && (wr->prot->lkey != wr->wr.sg_list->lkey || wr->prot->addr != wr->wr.sg_list->addr || wr->prot->length != wr->wr.sg_list->length)) region_len += wr->prot->length; /** * KLM octoword size - if protection was provided * then we use strided block format (3 octowords), * else we use single KLM (1 octoword) **/ xlt_size = wr->prot ? 0x30 : sizeof(struct mlx5_klm); set_sig_umr_segment(*seg, xlt_size); *seg += sizeof(struct mlx5_wqe_umr_ctrl_seg); *size += sizeof(struct mlx5_wqe_umr_ctrl_seg) / 16; if (unlikely((*seg == qp->sq.qend))) *seg = mlx5_get_send_wqe(qp, 0); set_sig_mkey_segment(*seg, wr, xlt_size, region_len, pdn); *seg += sizeof(struct mlx5_mkey_seg); *size += sizeof(struct mlx5_mkey_seg) / 16; if (unlikely((*seg == qp->sq.qend))) *seg = mlx5_get_send_wqe(qp, 0); ret = set_sig_data_segment(wr, qp, seg, size); if (ret) return ret; sig_mr->sig->sig_status_checked = false; return 0; } static int set_psv_wr(struct ib_sig_domain *domain, u32 psv_idx, void **seg, int *size) { struct mlx5_seg_set_psv *psv_seg = *seg; memset(psv_seg, 0, sizeof(*psv_seg)); psv_seg->psv_num = cpu_to_be32(psv_idx); switch (domain->sig_type) { case IB_SIG_TYPE_NONE: break; case IB_SIG_TYPE_T10_DIF: psv_seg->transient_sig = cpu_to_be32(domain->sig.dif.bg << 16 | domain->sig.dif.app_tag); psv_seg->ref_tag = cpu_to_be32(domain->sig.dif.ref_tag); break; default: pr_err("Bad signature type (%d) is given.\n", domain->sig_type); return -EINVAL; } *seg += sizeof(*psv_seg); *size += sizeof(*psv_seg) / 16; return 0; } static int set_reg_wr(struct mlx5_ib_qp *qp, const struct ib_reg_wr *wr, void **seg, int *size) { struct mlx5_ib_mr *mr = to_mmr(wr->mr); struct mlx5_ib_pd *pd = to_mpd(qp->ibqp.pd); int mr_list_size = mr->ndescs * mr->desc_size; bool umr_inline = mr_list_size <= MLX5_IB_SQ_UMR_INLINE_THRESHOLD; if (unlikely(wr->wr.send_flags & IB_SEND_INLINE)) { mlx5_ib_warn(to_mdev(qp->ibqp.device), "Invalid IB_SEND_INLINE send flag\n"); return -EINVAL; } set_reg_umr_seg(*seg, mr, umr_inline); *seg += sizeof(struct mlx5_wqe_umr_ctrl_seg); *size += sizeof(struct mlx5_wqe_umr_ctrl_seg) / 16; if (unlikely((*seg == qp->sq.qend))) *seg = mlx5_get_send_wqe(qp, 0); set_reg_mkey_seg(*seg, mr, wr->key, wr->access); *seg += sizeof(struct mlx5_mkey_seg); *size += sizeof(struct mlx5_mkey_seg) / 16; if (unlikely((*seg == qp->sq.qend))) *seg = mlx5_get_send_wqe(qp, 0); if (umr_inline) { set_reg_umr_inline_seg(*seg, qp, mr, mr_list_size); *size += get_xlt_octo(mr_list_size); } else { set_reg_data_seg(*seg, mr, pd); *seg += sizeof(struct mlx5_wqe_data_seg); *size += (sizeof(struct mlx5_wqe_data_seg) / 16); } return 0; } static void set_linv_wr(struct mlx5_ib_qp *qp, void **seg, int *size) { set_linv_umr_seg(*seg); *seg += sizeof(struct mlx5_wqe_umr_ctrl_seg); *size += sizeof(struct mlx5_wqe_umr_ctrl_seg) / 16; if (unlikely((*seg == qp->sq.qend))) *seg = mlx5_get_send_wqe(qp, 0); set_linv_mkey_seg(*seg); *seg += sizeof(struct mlx5_mkey_seg); *size += sizeof(struct mlx5_mkey_seg) / 16; if (unlikely((*seg == qp->sq.qend))) *seg = mlx5_get_send_wqe(qp, 0); } static void dump_wqe(struct mlx5_ib_qp *qp, int idx, int size_16) { __be32 *p = NULL; int tidx = idx; int i, j; pr_debug("dump wqe at %p\n", mlx5_get_send_wqe(qp, tidx)); for (i = 0, j = 0; i < size_16 * 4; i += 4, j += 4) { if ((i & 0xf) == 0) { void *buf = mlx5_get_send_wqe(qp, tidx); tidx = (tidx + 1) & (qp->sq.wqe_cnt - 1); p = buf; j = 0; } pr_debug("%08x %08x %08x %08x\n", be32_to_cpu(p[j]), be32_to_cpu(p[j + 1]), be32_to_cpu(p[j + 2]), be32_to_cpu(p[j + 3])); } } static int __begin_wqe(struct mlx5_ib_qp *qp, void **seg, struct mlx5_wqe_ctrl_seg **ctrl, const struct ib_send_wr *wr, unsigned *idx, int *size, int nreq, bool send_signaled, bool solicited) { if (unlikely(mlx5_wq_overflow(&qp->sq, nreq, qp->ibqp.send_cq))) return -ENOMEM; *idx = qp->sq.cur_post & (qp->sq.wqe_cnt - 1); *seg = mlx5_get_send_wqe(qp, *idx); *ctrl = *seg; *(uint32_t *)(*seg + 8) = 0; (*ctrl)->imm = send_ieth(wr); (*ctrl)->fm_ce_se = qp->sq_signal_bits | (send_signaled ? MLX5_WQE_CTRL_CQ_UPDATE : 0) | (solicited ? MLX5_WQE_CTRL_SOLICITED : 0); *seg += sizeof(**ctrl); *size = sizeof(**ctrl) / 16; return 0; } static int begin_wqe(struct mlx5_ib_qp *qp, void **seg, struct mlx5_wqe_ctrl_seg **ctrl, const struct ib_send_wr *wr, unsigned *idx, int *size, int nreq) { return __begin_wqe(qp, seg, ctrl, wr, idx, size, nreq, wr->send_flags & IB_SEND_SIGNALED, wr->send_flags & IB_SEND_SOLICITED); } static void finish_wqe(struct mlx5_ib_qp *qp, struct mlx5_wqe_ctrl_seg *ctrl, u8 size, unsigned idx, u64 wr_id, int nreq, u8 fence, u32 mlx5_opcode) { u8 opmod = 0; ctrl->opmod_idx_opcode = cpu_to_be32(((u32)(qp->sq.cur_post) << 8) | mlx5_opcode | ((u32)opmod << 24)); ctrl->qpn_ds = cpu_to_be32(size | (qp->trans_qp.base.mqp.qpn << 8)); ctrl->fm_ce_se |= fence; if (unlikely(qp->wq_sig)) ctrl->signature = wq_sig(ctrl); qp->sq.wrid[idx] = wr_id; qp->sq.w_list[idx].opcode = mlx5_opcode; qp->sq.wqe_head[idx] = qp->sq.head + nreq; qp->sq.cur_post += DIV_ROUND_UP(size * 16, MLX5_SEND_WQE_BB); qp->sq.w_list[idx].next = qp->sq.cur_post; } static int _mlx5_ib_post_send(struct ib_qp *ibqp, const struct ib_send_wr *wr, const struct ib_send_wr **bad_wr, bool drain) { struct mlx5_wqe_ctrl_seg *ctrl = NULL; /* compiler warning */ struct mlx5_ib_dev *dev = to_mdev(ibqp->device); struct mlx5_core_dev *mdev = dev->mdev; struct mlx5_ib_qp *qp; struct mlx5_ib_mr *mr; struct mlx5_wqe_data_seg *dpseg; struct mlx5_wqe_xrc_seg *xrc; struct mlx5_bf *bf; int uninitialized_var(size); void *qend; unsigned long flags; unsigned idx; int err = 0; int num_sge; void *seg; int nreq; int i; u8 next_fence = 0; u8 fence; if (unlikely(ibqp->qp_type == IB_QPT_GSI)) return mlx5_ib_gsi_post_send(ibqp, wr, bad_wr); qp = to_mqp(ibqp); bf = &qp->bf; qend = qp->sq.qend; spin_lock_irqsave(&qp->sq.lock, flags); if (mdev->state == MLX5_DEVICE_STATE_INTERNAL_ERROR && !drain) { err = -EIO; *bad_wr = wr; nreq = 0; goto out; } for (nreq = 0; wr; nreq++, wr = wr->next) { if (unlikely(wr->opcode >= ARRAY_SIZE(mlx5_ib_opcode))) { mlx5_ib_warn(dev, "\n"); err = -EINVAL; *bad_wr = wr; goto out; } num_sge = wr->num_sge; if (unlikely(num_sge > qp->sq.max_gs)) { mlx5_ib_warn(dev, "\n"); err = -EINVAL; *bad_wr = wr; goto out; } err = begin_wqe(qp, &seg, &ctrl, wr, &idx, &size, nreq); if (err) { mlx5_ib_warn(dev, "\n"); err = -ENOMEM; *bad_wr = wr; goto out; } if (wr->opcode == IB_WR_LOCAL_INV || wr->opcode == IB_WR_REG_MR) { fence = dev->umr_fence; next_fence = MLX5_FENCE_MODE_INITIATOR_SMALL; } else if (wr->send_flags & IB_SEND_FENCE) { if (qp->next_fence) fence = MLX5_FENCE_MODE_SMALL_AND_FENCE; else fence = MLX5_FENCE_MODE_FENCE; } else { fence = qp->next_fence; } switch (ibqp->qp_type) { case IB_QPT_XRC_INI: xrc = seg; seg += sizeof(*xrc); size += sizeof(*xrc) / 16; /* fall through */ case IB_QPT_RC: switch (wr->opcode) { case IB_WR_RDMA_READ: case IB_WR_RDMA_WRITE: case IB_WR_RDMA_WRITE_WITH_IMM: set_raddr_seg(seg, rdma_wr(wr)->remote_addr, rdma_wr(wr)->rkey); seg += sizeof(struct mlx5_wqe_raddr_seg); size += sizeof(struct mlx5_wqe_raddr_seg) / 16; break; case IB_WR_ATOMIC_CMP_AND_SWP: case IB_WR_ATOMIC_FETCH_AND_ADD: case IB_WR_MASKED_ATOMIC_CMP_AND_SWP: mlx5_ib_warn(dev, "Atomic operations are not supported yet\n"); err = -ENOSYS; *bad_wr = wr; goto out; case IB_WR_LOCAL_INV: qp->sq.wr_data[idx] = IB_WR_LOCAL_INV; ctrl->imm = cpu_to_be32(wr->ex.invalidate_rkey); set_linv_wr(qp, &seg, &size); num_sge = 0; break; case IB_WR_REG_MR: qp->sq.wr_data[idx] = IB_WR_REG_MR; ctrl->imm = cpu_to_be32(reg_wr(wr)->key); err = set_reg_wr(qp, reg_wr(wr), &seg, &size); if (err) { *bad_wr = wr; goto out; } num_sge = 0; break; case IB_WR_REG_SIG_MR: qp->sq.wr_data[idx] = IB_WR_REG_SIG_MR; mr = to_mmr(sig_handover_wr(wr)->sig_mr); ctrl->imm = cpu_to_be32(mr->ibmr.rkey); err = set_sig_umr_wr(wr, qp, &seg, &size); if (err) { mlx5_ib_warn(dev, "\n"); *bad_wr = wr; goto out; } finish_wqe(qp, ctrl, size, idx, wr->wr_id, nreq, fence, MLX5_OPCODE_UMR); /* * SET_PSV WQEs are not signaled and solicited * on error */ err = __begin_wqe(qp, &seg, &ctrl, wr, &idx, &size, nreq, false, true); if (err) { mlx5_ib_warn(dev, "\n"); err = -ENOMEM; *bad_wr = wr; goto out; } err = set_psv_wr(&sig_handover_wr(wr)->sig_attrs->mem, mr->sig->psv_memory.psv_idx, &seg, &size); if (err) { mlx5_ib_warn(dev, "\n"); *bad_wr = wr; goto out; } finish_wqe(qp, ctrl, size, idx, wr->wr_id, nreq, fence, MLX5_OPCODE_SET_PSV); err = __begin_wqe(qp, &seg, &ctrl, wr, &idx, &size, nreq, false, true); if (err) { mlx5_ib_warn(dev, "\n"); err = -ENOMEM; *bad_wr = wr; goto out; } err = set_psv_wr(&sig_handover_wr(wr)->sig_attrs->wire, mr->sig->psv_wire.psv_idx, &seg, &size); if (err) { mlx5_ib_warn(dev, "\n"); *bad_wr = wr; goto out; } finish_wqe(qp, ctrl, size, idx, wr->wr_id, nreq, fence, MLX5_OPCODE_SET_PSV); qp->next_fence = MLX5_FENCE_MODE_INITIATOR_SMALL; num_sge = 0; goto skip_psv; default: break; } break; case IB_QPT_UC: switch (wr->opcode) { case IB_WR_RDMA_WRITE: case IB_WR_RDMA_WRITE_WITH_IMM: set_raddr_seg(seg, rdma_wr(wr)->remote_addr, rdma_wr(wr)->rkey); seg += sizeof(struct mlx5_wqe_raddr_seg); size += sizeof(struct mlx5_wqe_raddr_seg) / 16; break; default: break; } break; case IB_QPT_SMI: if (unlikely(!mdev->port_caps[qp->port - 1].has_smi)) { mlx5_ib_warn(dev, "Send SMP MADs is not allowed\n"); err = -EPERM; *bad_wr = wr; goto out; } /* fall through */ case MLX5_IB_QPT_HW_GSI: set_datagram_seg(seg, wr); seg += sizeof(struct mlx5_wqe_datagram_seg); size += sizeof(struct mlx5_wqe_datagram_seg) / 16; if (unlikely((seg == qend))) seg = mlx5_get_send_wqe(qp, 0); break; case IB_QPT_UD: set_datagram_seg(seg, wr); seg += sizeof(struct mlx5_wqe_datagram_seg); size += sizeof(struct mlx5_wqe_datagram_seg) / 16; if (unlikely((seg == qend))) seg = mlx5_get_send_wqe(qp, 0); /* handle qp that supports ud offload */ if (qp->flags & IB_QP_CREATE_IPOIB_UD_LSO) { struct mlx5_wqe_eth_pad *pad; pad = seg; memset(pad, 0, sizeof(struct mlx5_wqe_eth_pad)); seg += sizeof(struct mlx5_wqe_eth_pad); size += sizeof(struct mlx5_wqe_eth_pad) / 16; seg = set_eth_seg(seg, wr, qend, qp, &size); if (unlikely((seg == qend))) seg = mlx5_get_send_wqe(qp, 0); } break; case MLX5_IB_QPT_REG_UMR: if (wr->opcode != MLX5_IB_WR_UMR) { err = -EINVAL; mlx5_ib_warn(dev, "bad opcode\n"); goto out; } qp->sq.wr_data[idx] = MLX5_IB_WR_UMR; ctrl->imm = cpu_to_be32(umr_wr(wr)->mkey); err = set_reg_umr_segment(dev, seg, wr, !!(MLX5_CAP_GEN(mdev, atomic))); if (unlikely(err)) goto out; seg += sizeof(struct mlx5_wqe_umr_ctrl_seg); size += sizeof(struct mlx5_wqe_umr_ctrl_seg) / 16; if (unlikely((seg == qend))) seg = mlx5_get_send_wqe(qp, 0); set_reg_mkey_segment(seg, wr); seg += sizeof(struct mlx5_mkey_seg); size += sizeof(struct mlx5_mkey_seg) / 16; if (unlikely((seg == qend))) seg = mlx5_get_send_wqe(qp, 0); break; default: break; } if (wr->send_flags & IB_SEND_INLINE && num_sge) { int uninitialized_var(sz); err = set_data_inl_seg(qp, wr, seg, &sz); if (unlikely(err)) { mlx5_ib_warn(dev, "\n"); *bad_wr = wr; goto out; } size += sz; } else { dpseg = seg; for (i = 0; i < num_sge; i++) { if (unlikely(dpseg == qend)) { seg = mlx5_get_send_wqe(qp, 0); dpseg = seg; } if (likely(wr->sg_list[i].length)) { set_data_ptr_seg(dpseg, wr->sg_list + i); size += sizeof(struct mlx5_wqe_data_seg) / 16; dpseg++; } } } qp->next_fence = next_fence; finish_wqe(qp, ctrl, size, idx, wr->wr_id, nreq, fence, mlx5_ib_opcode[wr->opcode]); skip_psv: if (0) dump_wqe(qp, idx, size); } out: if (likely(nreq)) { qp->sq.head += nreq; /* Make sure that descriptors are written before * updating doorbell record and ringing the doorbell */ wmb(); qp->db.db[MLX5_SND_DBR] = cpu_to_be32(qp->sq.cur_post); /* Make sure doorbell record is visible to the HCA before * we hit doorbell */ wmb(); /* currently we support only regular doorbells */ mlx5_write64((__be32 *)ctrl, bf->bfreg->map + bf->offset, NULL); /* Make sure doorbells don't leak out of SQ spinlock * and reach the HCA out of order. */ mmiowb(); bf->offset ^= bf->buf_size; } spin_unlock_irqrestore(&qp->sq.lock, flags); return err; } int mlx5_ib_post_send(struct ib_qp *ibqp, const struct ib_send_wr *wr, const struct ib_send_wr **bad_wr) { return _mlx5_ib_post_send(ibqp, wr, bad_wr, false); } static void set_sig_seg(struct mlx5_rwqe_sig *sig, int size) { sig->signature = calc_sig(sig, size); } static int _mlx5_ib_post_recv(struct ib_qp *ibqp, const struct ib_recv_wr *wr, const struct ib_recv_wr **bad_wr, bool drain) { struct mlx5_ib_qp *qp = to_mqp(ibqp); struct mlx5_wqe_data_seg *scat; struct mlx5_rwqe_sig *sig; struct mlx5_ib_dev *dev = to_mdev(ibqp->device); struct mlx5_core_dev *mdev = dev->mdev; unsigned long flags; int err = 0; int nreq; int ind; int i; if (unlikely(ibqp->qp_type == IB_QPT_GSI)) return mlx5_ib_gsi_post_recv(ibqp, wr, bad_wr); spin_lock_irqsave(&qp->rq.lock, flags); if (mdev->state == MLX5_DEVICE_STATE_INTERNAL_ERROR && !drain) { err = -EIO; *bad_wr = wr; nreq = 0; goto out; } ind = qp->rq.head & (qp->rq.wqe_cnt - 1); for (nreq = 0; wr; nreq++, wr = wr->next) { if (mlx5_wq_overflow(&qp->rq, nreq, qp->ibqp.recv_cq)) { err = -ENOMEM; *bad_wr = wr; goto out; } if (unlikely(wr->num_sge > qp->rq.max_gs)) { err = -EINVAL; *bad_wr = wr; goto out; } scat = get_recv_wqe(qp, ind); if (qp->wq_sig) scat++; for (i = 0; i < wr->num_sge; i++) set_data_ptr_seg(scat + i, wr->sg_list + i); if (i < qp->rq.max_gs) { scat[i].byte_count = 0; scat[i].lkey = cpu_to_be32(MLX5_INVALID_LKEY); scat[i].addr = 0; } if (qp->wq_sig) { sig = (struct mlx5_rwqe_sig *)scat; set_sig_seg(sig, (qp->rq.max_gs + 1) << 2); } qp->rq.wrid[ind] = wr->wr_id; ind = (ind + 1) & (qp->rq.wqe_cnt - 1); } out: if (likely(nreq)) { qp->rq.head += nreq; /* Make sure that descriptors are written before * doorbell record. */ wmb(); *qp->db.db = cpu_to_be32(qp->rq.head & 0xffff); } spin_unlock_irqrestore(&qp->rq.lock, flags); return err; } int mlx5_ib_post_recv(struct ib_qp *ibqp, const struct ib_recv_wr *wr, const struct ib_recv_wr **bad_wr) { return _mlx5_ib_post_recv(ibqp, wr, bad_wr, false); } static inline enum ib_qp_state to_ib_qp_state(enum mlx5_qp_state mlx5_state) { switch (mlx5_state) { case MLX5_QP_STATE_RST: return IB_QPS_RESET; case MLX5_QP_STATE_INIT: return IB_QPS_INIT; case MLX5_QP_STATE_RTR: return IB_QPS_RTR; case MLX5_QP_STATE_RTS: return IB_QPS_RTS; case MLX5_QP_STATE_SQ_DRAINING: case MLX5_QP_STATE_SQD: return IB_QPS_SQD; case MLX5_QP_STATE_SQER: return IB_QPS_SQE; case MLX5_QP_STATE_ERR: return IB_QPS_ERR; default: return -1; } } static inline enum ib_mig_state to_ib_mig_state(int mlx5_mig_state) { switch (mlx5_mig_state) { case MLX5_QP_PM_ARMED: return IB_MIG_ARMED; case MLX5_QP_PM_REARM: return IB_MIG_REARM; case MLX5_QP_PM_MIGRATED: return IB_MIG_MIGRATED; default: return -1; } } static int to_ib_qp_access_flags(int mlx5_flags) { int ib_flags = 0; if (mlx5_flags & MLX5_QP_BIT_RRE) ib_flags |= IB_ACCESS_REMOTE_READ; if (mlx5_flags & MLX5_QP_BIT_RWE) ib_flags |= IB_ACCESS_REMOTE_WRITE; if (mlx5_flags & MLX5_QP_BIT_RAE) ib_flags |= IB_ACCESS_REMOTE_ATOMIC; return ib_flags; } static void to_rdma_ah_attr(struct mlx5_ib_dev *ibdev, struct rdma_ah_attr *ah_attr, struct mlx5_qp_path *path) { memset(ah_attr, 0, sizeof(*ah_attr)); if (!path->port || path->port > ibdev->num_ports) return; ah_attr->type = rdma_ah_find_type(&ibdev->ib_dev, path->port); rdma_ah_set_port_num(ah_attr, path->port); rdma_ah_set_sl(ah_attr, path->dci_cfi_prio_sl & 0xf); rdma_ah_set_dlid(ah_attr, be16_to_cpu(path->rlid)); rdma_ah_set_path_bits(ah_attr, path->grh_mlid & 0x7f); rdma_ah_set_static_rate(ah_attr, path->static_rate ? path->static_rate - 5 : 0); if (path->grh_mlid & (1 << 7)) { u32 tc_fl = be32_to_cpu(path->tclass_flowlabel); rdma_ah_set_grh(ah_attr, NULL, tc_fl & 0xfffff, path->mgid_index, path->hop_limit, (tc_fl >> 20) & 0xff); rdma_ah_set_dgid_raw(ah_attr, path->rgid); } } static int query_raw_packet_qp_sq_state(struct mlx5_ib_dev *dev, struct mlx5_ib_sq *sq, u8 *sq_state) { int err; err = mlx5_core_query_sq_state(dev->mdev, sq->base.mqp.qpn, sq_state); if (err) goto out; sq->state = *sq_state; out: return err; } static int query_raw_packet_qp_rq_state(struct mlx5_ib_dev *dev, struct mlx5_ib_rq *rq, u8 *rq_state) { void *out; void *rqc; int inlen; int err; inlen = MLX5_ST_SZ_BYTES(query_rq_out); out = kvzalloc(inlen, GFP_KERNEL); if (!out) return -ENOMEM; err = mlx5_core_query_rq(dev->mdev, rq->base.mqp.qpn, out); if (err) goto out; rqc = MLX5_ADDR_OF(query_rq_out, out, rq_context); *rq_state = MLX5_GET(rqc, rqc, state); rq->state = *rq_state; out: kvfree(out); return err; } static int sqrq_state_to_qp_state(u8 sq_state, u8 rq_state, struct mlx5_ib_qp *qp, u8 *qp_state) { static const u8 sqrq_trans[MLX5_RQ_NUM_STATE][MLX5_SQ_NUM_STATE] = { [MLX5_RQC_STATE_RST] = { [MLX5_SQC_STATE_RST] = IB_QPS_RESET, [MLX5_SQC_STATE_RDY] = MLX5_QP_STATE_BAD, [MLX5_SQC_STATE_ERR] = MLX5_QP_STATE_BAD, [MLX5_SQ_STATE_NA] = IB_QPS_RESET, }, [MLX5_RQC_STATE_RDY] = { [MLX5_SQC_STATE_RST] = MLX5_QP_STATE_BAD, [MLX5_SQC_STATE_RDY] = MLX5_QP_STATE, [MLX5_SQC_STATE_ERR] = IB_QPS_SQE, [MLX5_SQ_STATE_NA] = MLX5_QP_STATE, }, [MLX5_RQC_STATE_ERR] = { [MLX5_SQC_STATE_RST] = MLX5_QP_STATE_BAD, [MLX5_SQC_STATE_RDY] = MLX5_QP_STATE_BAD, [MLX5_SQC_STATE_ERR] = IB_QPS_ERR, [MLX5_SQ_STATE_NA] = IB_QPS_ERR, }, [MLX5_RQ_STATE_NA] = { [MLX5_SQC_STATE_RST] = IB_QPS_RESET, [MLX5_SQC_STATE_RDY] = MLX5_QP_STATE, [MLX5_SQC_STATE_ERR] = MLX5_QP_STATE, [MLX5_SQ_STATE_NA] = MLX5_QP_STATE_BAD, }, }; *qp_state = sqrq_trans[rq_state][sq_state]; if (*qp_state == MLX5_QP_STATE_BAD) { WARN(1, "Buggy Raw Packet QP state, SQ 0x%x state: 0x%x, RQ 0x%x state: 0x%x", qp->raw_packet_qp.sq.base.mqp.qpn, sq_state, qp->raw_packet_qp.rq.base.mqp.qpn, rq_state); return -EINVAL; } if (*qp_state == MLX5_QP_STATE) *qp_state = qp->state; return 0; } static int query_raw_packet_qp_state(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *qp, u8 *raw_packet_qp_state) { struct mlx5_ib_raw_packet_qp *raw_packet_qp = &qp->raw_packet_qp; struct mlx5_ib_sq *sq = &raw_packet_qp->sq; struct mlx5_ib_rq *rq = &raw_packet_qp->rq; int err; u8 sq_state = MLX5_SQ_STATE_NA; u8 rq_state = MLX5_RQ_STATE_NA; if (qp->sq.wqe_cnt) { err = query_raw_packet_qp_sq_state(dev, sq, &sq_state); if (err) return err; } if (qp->rq.wqe_cnt) { err = query_raw_packet_qp_rq_state(dev, rq, &rq_state); if (err) return err; } return sqrq_state_to_qp_state(sq_state, rq_state, qp, raw_packet_qp_state); } static int query_qp_attr(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *qp, struct ib_qp_attr *qp_attr) { int outlen = MLX5_ST_SZ_BYTES(query_qp_out); struct mlx5_qp_context *context; int mlx5_state; u32 *outb; int err = 0; outb = kzalloc(outlen, GFP_KERNEL); if (!outb) return -ENOMEM; err = mlx5_core_qp_query(dev->mdev, &qp->trans_qp.base.mqp, outb, outlen); if (err) goto out; /* FIXME: use MLX5_GET rather than mlx5_qp_context manual struct */ context = (struct mlx5_qp_context *)MLX5_ADDR_OF(query_qp_out, outb, qpc); mlx5_state = be32_to_cpu(context->flags) >> 28; qp->state = to_ib_qp_state(mlx5_state); qp_attr->path_mtu = context->mtu_msgmax >> 5; qp_attr->path_mig_state = to_ib_mig_state((be32_to_cpu(context->flags) >> 11) & 0x3); qp_attr->qkey = be32_to_cpu(context->qkey); qp_attr->rq_psn = be32_to_cpu(context->rnr_nextrecvpsn) & 0xffffff; qp_attr->sq_psn = be32_to_cpu(context->next_send_psn) & 0xffffff; qp_attr->dest_qp_num = be32_to_cpu(context->log_pg_sz_remote_qpn) & 0xffffff; qp_attr->qp_access_flags = to_ib_qp_access_flags(be32_to_cpu(context->params2)); if (qp->ibqp.qp_type == IB_QPT_RC || qp->ibqp.qp_type == IB_QPT_UC) { to_rdma_ah_attr(dev, &qp_attr->ah_attr, &context->pri_path); to_rdma_ah_attr(dev, &qp_attr->alt_ah_attr, &context->alt_path); qp_attr->alt_pkey_index = be16_to_cpu(context->alt_path.pkey_index); qp_attr->alt_port_num = rdma_ah_get_port_num(&qp_attr->alt_ah_attr); } qp_attr->pkey_index = be16_to_cpu(context->pri_path.pkey_index); qp_attr->port_num = context->pri_path.port; /* qp_attr->en_sqd_async_notify is only applicable in modify qp */ qp_attr->sq_draining = mlx5_state == MLX5_QP_STATE_SQ_DRAINING; qp_attr->max_rd_atomic = 1 << ((be32_to_cpu(context->params1) >> 21) & 0x7); qp_attr->max_dest_rd_atomic = 1 << ((be32_to_cpu(context->params2) >> 21) & 0x7); qp_attr->min_rnr_timer = (be32_to_cpu(context->rnr_nextrecvpsn) >> 24) & 0x1f; qp_attr->timeout = context->pri_path.ackto_lt >> 3; qp_attr->retry_cnt = (be32_to_cpu(context->params1) >> 16) & 0x7; qp_attr->rnr_retry = (be32_to_cpu(context->params1) >> 13) & 0x7; qp_attr->alt_timeout = context->alt_path.ackto_lt >> 3; out: kfree(outb); return err; } static int mlx5_ib_dct_query_qp(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *mqp, struct ib_qp_attr *qp_attr, int qp_attr_mask, struct ib_qp_init_attr *qp_init_attr) { struct mlx5_core_dct *dct = &mqp->dct.mdct; u32 *out; u32 access_flags = 0; int outlen = MLX5_ST_SZ_BYTES(query_dct_out); void *dctc; int err; int supported_mask = IB_QP_STATE | IB_QP_ACCESS_FLAGS | IB_QP_PORT | IB_QP_MIN_RNR_TIMER | IB_QP_AV | IB_QP_PATH_MTU | IB_QP_PKEY_INDEX; if (qp_attr_mask & ~supported_mask) return -EINVAL; if (mqp->state != IB_QPS_RTR) return -EINVAL; out = kzalloc(outlen, GFP_KERNEL); if (!out) return -ENOMEM; err = mlx5_core_dct_query(dev->mdev, dct, out, outlen); if (err) goto out; dctc = MLX5_ADDR_OF(query_dct_out, out, dct_context_entry); if (qp_attr_mask & IB_QP_STATE) qp_attr->qp_state = IB_QPS_RTR; if (qp_attr_mask & IB_QP_ACCESS_FLAGS) { if (MLX5_GET(dctc, dctc, rre)) access_flags |= IB_ACCESS_REMOTE_READ; if (MLX5_GET(dctc, dctc, rwe)) access_flags |= IB_ACCESS_REMOTE_WRITE; if (MLX5_GET(dctc, dctc, rae)) access_flags |= IB_ACCESS_REMOTE_ATOMIC; qp_attr->qp_access_flags = access_flags; } if (qp_attr_mask & IB_QP_PORT) qp_attr->port_num = MLX5_GET(dctc, dctc, port); if (qp_attr_mask & IB_QP_MIN_RNR_TIMER) qp_attr->min_rnr_timer = MLX5_GET(dctc, dctc, min_rnr_nak); if (qp_attr_mask & IB_QP_AV) { qp_attr->ah_attr.grh.traffic_class = MLX5_GET(dctc, dctc, tclass); qp_attr->ah_attr.grh.flow_label = MLX5_GET(dctc, dctc, flow_label); qp_attr->ah_attr.grh.sgid_index = MLX5_GET(dctc, dctc, my_addr_index); qp_attr->ah_attr.grh.hop_limit = MLX5_GET(dctc, dctc, hop_limit); } if (qp_attr_mask & IB_QP_PATH_MTU) qp_attr->path_mtu = MLX5_GET(dctc, dctc, mtu); if (qp_attr_mask & IB_QP_PKEY_INDEX) qp_attr->pkey_index = MLX5_GET(dctc, dctc, pkey_index); out: kfree(out); return err; } int mlx5_ib_query_qp(struct ib_qp *ibqp, struct ib_qp_attr *qp_attr, int qp_attr_mask, struct ib_qp_init_attr *qp_init_attr) { struct mlx5_ib_dev *dev = to_mdev(ibqp->device); struct mlx5_ib_qp *qp = to_mqp(ibqp); int err = 0; u8 raw_packet_qp_state; if (ibqp->rwq_ind_tbl) return -ENOSYS; if (unlikely(ibqp->qp_type == IB_QPT_GSI)) return mlx5_ib_gsi_query_qp(ibqp, qp_attr, qp_attr_mask, qp_init_attr); /* Not all of output fields are applicable, make sure to zero them */ memset(qp_init_attr, 0, sizeof(*qp_init_attr)); memset(qp_attr, 0, sizeof(*qp_attr)); if (unlikely(qp->qp_sub_type == MLX5_IB_QPT_DCT)) return mlx5_ib_dct_query_qp(dev, qp, qp_attr, qp_attr_mask, qp_init_attr); mutex_lock(&qp->mutex); if (qp->ibqp.qp_type == IB_QPT_RAW_PACKET || qp->flags & MLX5_IB_QP_UNDERLAY) { err = query_raw_packet_qp_state(dev, qp, &raw_packet_qp_state); if (err) goto out; qp->state = raw_packet_qp_state; qp_attr->port_num = 1; } else { err = query_qp_attr(dev, qp, qp_attr); if (err) goto out; } qp_attr->qp_state = qp->state; qp_attr->cur_qp_state = qp_attr->qp_state; qp_attr->cap.max_recv_wr = qp->rq.wqe_cnt; qp_attr->cap.max_recv_sge = qp->rq.max_gs; if (!ibqp->uobject) { qp_attr->cap.max_send_wr = qp->sq.max_post; qp_attr->cap.max_send_sge = qp->sq.max_gs; qp_init_attr->qp_context = ibqp->qp_context; } else { qp_attr->cap.max_send_wr = 0; qp_attr->cap.max_send_sge = 0; } qp_init_attr->qp_type = ibqp->qp_type; qp_init_attr->recv_cq = ibqp->recv_cq; qp_init_attr->send_cq = ibqp->send_cq; qp_init_attr->srq = ibqp->srq; qp_attr->cap.max_inline_data = qp->max_inline_data; qp_init_attr->cap = qp_attr->cap; qp_init_attr->create_flags = 0; if (qp->flags & MLX5_IB_QP_BLOCK_MULTICAST_LOOPBACK) qp_init_attr->create_flags |= IB_QP_CREATE_BLOCK_MULTICAST_LOOPBACK; if (qp->flags & MLX5_IB_QP_CROSS_CHANNEL) qp_init_attr->create_flags |= IB_QP_CREATE_CROSS_CHANNEL; if (qp->flags & MLX5_IB_QP_MANAGED_SEND) qp_init_attr->create_flags |= IB_QP_CREATE_MANAGED_SEND; if (qp->flags & MLX5_IB_QP_MANAGED_RECV) qp_init_attr->create_flags |= IB_QP_CREATE_MANAGED_RECV; if (qp->flags & MLX5_IB_QP_SQPN_QP1) qp_init_attr->create_flags |= mlx5_ib_create_qp_sqpn_qp1(); qp_init_attr->sq_sig_type = qp->sq_signal_bits & MLX5_WQE_CTRL_CQ_UPDATE ? IB_SIGNAL_ALL_WR : IB_SIGNAL_REQ_WR; out: mutex_unlock(&qp->mutex); return err; } struct ib_xrcd *mlx5_ib_alloc_xrcd(struct ib_device *ibdev, struct ib_ucontext *context, struct ib_udata *udata) { struct mlx5_ib_dev *dev = to_mdev(ibdev); struct mlx5_ib_xrcd *xrcd; int err; if (!MLX5_CAP_GEN(dev->mdev, xrc)) return ERR_PTR(-ENOSYS); xrcd = kmalloc(sizeof(*xrcd), GFP_KERNEL); if (!xrcd) return ERR_PTR(-ENOMEM); err = mlx5_core_xrcd_alloc(dev->mdev, &xrcd->xrcdn); if (err) { kfree(xrcd); return ERR_PTR(-ENOMEM); } return &xrcd->ibxrcd; } int mlx5_ib_dealloc_xrcd(struct ib_xrcd *xrcd) { struct mlx5_ib_dev *dev = to_mdev(xrcd->device); u32 xrcdn = to_mxrcd(xrcd)->xrcdn; int err; err = mlx5_core_xrcd_dealloc(dev->mdev, xrcdn); if (err) mlx5_ib_warn(dev, "failed to dealloc xrcdn 0x%x\n", xrcdn); kfree(xrcd); return 0; } static void mlx5_ib_wq_event(struct mlx5_core_qp *core_qp, int type) { struct mlx5_ib_rwq *rwq = to_mibrwq(core_qp); struct mlx5_ib_dev *dev = to_mdev(rwq->ibwq.device); struct ib_event event; if (rwq->ibwq.event_handler) { event.device = rwq->ibwq.device; event.element.wq = &rwq->ibwq; switch (type) { case MLX5_EVENT_TYPE_WQ_CATAS_ERROR: event.event = IB_EVENT_WQ_FATAL; break; default: mlx5_ib_warn(dev, "Unexpected event type %d on WQ %06x\n", type, core_qp->qpn); return; } rwq->ibwq.event_handler(&event, rwq->ibwq.wq_context); } } static int set_delay_drop(struct mlx5_ib_dev *dev) { int err = 0; mutex_lock(&dev->delay_drop.lock); if (dev->delay_drop.activate) goto out; err = mlx5_core_set_delay_drop(dev->mdev, dev->delay_drop.timeout); if (err) goto out; dev->delay_drop.activate = true; out: mutex_unlock(&dev->delay_drop.lock); if (!err) atomic_inc(&dev->delay_drop.rqs_cnt); return err; } static int create_rq(struct mlx5_ib_rwq *rwq, struct ib_pd *pd, struct ib_wq_init_attr *init_attr) { struct mlx5_ib_dev *dev; int has_net_offloads; __be64 *rq_pas0; void *in; void *rqc; void *wq; int inlen; int err; dev = to_mdev(pd->device); inlen = MLX5_ST_SZ_BYTES(create_rq_in) + sizeof(u64) * rwq->rq_num_pas; in = kvzalloc(inlen, GFP_KERNEL); if (!in) return -ENOMEM; rqc = MLX5_ADDR_OF(create_rq_in, in, ctx); MLX5_SET(rqc, rqc, mem_rq_type, MLX5_RQC_MEM_RQ_TYPE_MEMORY_RQ_INLINE); MLX5_SET(rqc, rqc, user_index, rwq->user_index); MLX5_SET(rqc, rqc, cqn, to_mcq(init_attr->cq)->mcq.cqn); MLX5_SET(rqc, rqc, state, MLX5_RQC_STATE_RST); MLX5_SET(rqc, rqc, flush_in_error_en, 1); wq = MLX5_ADDR_OF(rqc, rqc, wq); MLX5_SET(wq, wq, wq_type, rwq->create_flags & MLX5_IB_WQ_FLAGS_STRIDING_RQ ? MLX5_WQ_TYPE_CYCLIC_STRIDING_RQ : MLX5_WQ_TYPE_CYCLIC); if (init_attr->create_flags & IB_WQ_FLAGS_PCI_WRITE_END_PADDING) { if (!MLX5_CAP_GEN(dev->mdev, end_pad)) { mlx5_ib_dbg(dev, "Scatter end padding is not supported\n"); err = -EOPNOTSUPP; goto out; } else { MLX5_SET(wq, wq, end_padding_mode, MLX5_WQ_END_PAD_MODE_ALIGN); } } MLX5_SET(wq, wq, log_wq_stride, rwq->log_rq_stride); if (rwq->create_flags & MLX5_IB_WQ_FLAGS_STRIDING_RQ) { MLX5_SET(wq, wq, two_byte_shift_en, rwq->two_byte_shift_en); MLX5_SET(wq, wq, log_wqe_stride_size, rwq->single_stride_log_num_of_bytes - MLX5_MIN_SINGLE_STRIDE_LOG_NUM_BYTES); MLX5_SET(wq, wq, log_wqe_num_of_strides, rwq->log_num_strides - MLX5_MIN_SINGLE_WQE_LOG_NUM_STRIDES); } MLX5_SET(wq, wq, log_wq_sz, rwq->log_rq_size); MLX5_SET(wq, wq, pd, to_mpd(pd)->pdn); MLX5_SET(wq, wq, page_offset, rwq->rq_page_offset); MLX5_SET(wq, wq, log_wq_pg_sz, rwq->log_page_size); MLX5_SET(wq, wq, wq_signature, rwq->wq_sig); MLX5_SET64(wq, wq, dbr_addr, rwq->db.dma); has_net_offloads = MLX5_CAP_GEN(dev->mdev, eth_net_offloads); if (init_attr->create_flags & IB_WQ_FLAGS_CVLAN_STRIPPING) { if (!(has_net_offloads && MLX5_CAP_ETH(dev->mdev, vlan_cap))) { mlx5_ib_dbg(dev, "VLAN offloads are not supported\n"); err = -EOPNOTSUPP; goto out; } } else { MLX5_SET(rqc, rqc, vsd, 1); } if (init_attr->create_flags & IB_WQ_FLAGS_SCATTER_FCS) { if (!(has_net_offloads && MLX5_CAP_ETH(dev->mdev, scatter_fcs))) { mlx5_ib_dbg(dev, "Scatter FCS is not supported\n"); err = -EOPNOTSUPP; goto out; } MLX5_SET(rqc, rqc, scatter_fcs, 1); } if (init_attr->create_flags & IB_WQ_FLAGS_DELAY_DROP) { if (!(dev->ib_dev.attrs.raw_packet_caps & IB_RAW_PACKET_CAP_DELAY_DROP)) { mlx5_ib_dbg(dev, "Delay drop is not supported\n"); err = -EOPNOTSUPP; goto out; } MLX5_SET(rqc, rqc, delay_drop_en, 1); } rq_pas0 = (__be64 *)MLX5_ADDR_OF(wq, wq, pas); mlx5_ib_populate_pas(dev, rwq->umem, rwq->page_shift, rq_pas0, 0); err = mlx5_core_create_rq_tracked(dev->mdev, in, inlen, &rwq->core_qp); if (!err && init_attr->create_flags & IB_WQ_FLAGS_DELAY_DROP) { err = set_delay_drop(dev); if (err) { mlx5_ib_warn(dev, "Failed to enable delay drop err=%d\n", err); mlx5_core_destroy_rq_tracked(dev->mdev, &rwq->core_qp); } else { rwq->create_flags |= MLX5_IB_WQ_FLAGS_DELAY_DROP; } } out: kvfree(in); return err; } static int set_user_rq_size(struct mlx5_ib_dev *dev, struct ib_wq_init_attr *wq_init_attr, struct mlx5_ib_create_wq *ucmd, struct mlx5_ib_rwq *rwq) { /* Sanity check RQ size before proceeding */ if (wq_init_attr->max_wr > (1 << MLX5_CAP_GEN(dev->mdev, log_max_wq_sz))) return -EINVAL; if (!ucmd->rq_wqe_count) return -EINVAL; rwq->wqe_count = ucmd->rq_wqe_count; rwq->wqe_shift = ucmd->rq_wqe_shift; if (check_shl_overflow(rwq->wqe_count, rwq->wqe_shift, &rwq->buf_size)) return -EINVAL; rwq->log_rq_stride = rwq->wqe_shift; rwq->log_rq_size = ilog2(rwq->wqe_count); return 0; } static int prepare_user_rq(struct ib_pd *pd, struct ib_wq_init_attr *init_attr, struct ib_udata *udata, struct mlx5_ib_rwq *rwq) { struct mlx5_ib_dev *dev = to_mdev(pd->device); struct mlx5_ib_create_wq ucmd = {}; int err; size_t required_cmd_sz; required_cmd_sz = offsetof(typeof(ucmd), single_stride_log_num_of_bytes) + sizeof(ucmd.single_stride_log_num_of_bytes); if (udata->inlen < required_cmd_sz) { mlx5_ib_dbg(dev, "invalid inlen\n"); return -EINVAL; } if (udata->inlen > sizeof(ucmd) && !ib_is_udata_cleared(udata, sizeof(ucmd), udata->inlen - sizeof(ucmd))) { mlx5_ib_dbg(dev, "inlen is not supported\n"); return -EOPNOTSUPP; } if (ib_copy_from_udata(&ucmd, udata, min(sizeof(ucmd), udata->inlen))) { mlx5_ib_dbg(dev, "copy failed\n"); return -EFAULT; } if (ucmd.comp_mask & (~MLX5_IB_CREATE_WQ_STRIDING_RQ)) { mlx5_ib_dbg(dev, "invalid comp mask\n"); return -EOPNOTSUPP; } else if (ucmd.comp_mask & MLX5_IB_CREATE_WQ_STRIDING_RQ) { if (!MLX5_CAP_GEN(dev->mdev, striding_rq)) { mlx5_ib_dbg(dev, "Striding RQ is not supported\n"); return -EOPNOTSUPP; } if ((ucmd.single_stride_log_num_of_bytes < MLX5_MIN_SINGLE_STRIDE_LOG_NUM_BYTES) || (ucmd.single_stride_log_num_of_bytes > MLX5_MAX_SINGLE_STRIDE_LOG_NUM_BYTES)) { mlx5_ib_dbg(dev, "Invalid log stride size (%u. Range is %u - %u)\n", ucmd.single_stride_log_num_of_bytes, MLX5_MIN_SINGLE_STRIDE_LOG_NUM_BYTES, MLX5_MAX_SINGLE_STRIDE_LOG_NUM_BYTES); return -EINVAL; } if ((ucmd.single_wqe_log_num_of_strides > MLX5_MAX_SINGLE_WQE_LOG_NUM_STRIDES) || (ucmd.single_wqe_log_num_of_strides < MLX5_MIN_SINGLE_WQE_LOG_NUM_STRIDES)) { mlx5_ib_dbg(dev, "Invalid log num strides (%u. Range is %u - %u)\n", ucmd.single_wqe_log_num_of_strides, MLX5_MIN_SINGLE_WQE_LOG_NUM_STRIDES, MLX5_MAX_SINGLE_WQE_LOG_NUM_STRIDES); return -EINVAL; } rwq->single_stride_log_num_of_bytes = ucmd.single_stride_log_num_of_bytes; rwq->log_num_strides = ucmd.single_wqe_log_num_of_strides; rwq->two_byte_shift_en = !!ucmd.two_byte_shift_en; rwq->create_flags |= MLX5_IB_WQ_FLAGS_STRIDING_RQ; } err = set_user_rq_size(dev, init_attr, &ucmd, rwq); if (err) { mlx5_ib_dbg(dev, "err %d\n", err); return err; } err = create_user_rq(dev, pd, rwq, &ucmd); if (err) { mlx5_ib_dbg(dev, "err %d\n", err); if (err) return err; } rwq->user_index = ucmd.user_index; return 0; } struct ib_wq *mlx5_ib_create_wq(struct ib_pd *pd, struct ib_wq_init_attr *init_attr, struct ib_udata *udata) { struct mlx5_ib_dev *dev; struct mlx5_ib_rwq *rwq; struct mlx5_ib_create_wq_resp resp = {}; size_t min_resp_len; int err; if (!udata) return ERR_PTR(-ENOSYS); min_resp_len = offsetof(typeof(resp), reserved) + sizeof(resp.reserved); if (udata->outlen && udata->outlen < min_resp_len) return ERR_PTR(-EINVAL); dev = to_mdev(pd->device); switch (init_attr->wq_type) { case IB_WQT_RQ: rwq = kzalloc(sizeof(*rwq), GFP_KERNEL); if (!rwq) return ERR_PTR(-ENOMEM); err = prepare_user_rq(pd, init_attr, udata, rwq); if (err) goto err; err = create_rq(rwq, pd, init_attr); if (err) goto err_user_rq; break; default: mlx5_ib_dbg(dev, "unsupported wq type %d\n", init_attr->wq_type); return ERR_PTR(-EINVAL); } rwq->ibwq.wq_num = rwq->core_qp.qpn; rwq->ibwq.state = IB_WQS_RESET; if (udata->outlen) { resp.response_length = offsetof(typeof(resp), response_length) + sizeof(resp.response_length); err = ib_copy_to_udata(udata, &resp, resp.response_length); if (err) goto err_copy; } rwq->core_qp.event = mlx5_ib_wq_event; rwq->ibwq.event_handler = init_attr->event_handler; return &rwq->ibwq; err_copy: mlx5_core_destroy_rq_tracked(dev->mdev, &rwq->core_qp); err_user_rq: destroy_user_rq(dev, pd, rwq); err: kfree(rwq); return ERR_PTR(err); } int mlx5_ib_destroy_wq(struct ib_wq *wq) { struct mlx5_ib_dev *dev = to_mdev(wq->device); struct mlx5_ib_rwq *rwq = to_mrwq(wq); mlx5_core_destroy_rq_tracked(dev->mdev, &rwq->core_qp); destroy_user_rq(dev, wq->pd, rwq); kfree(rwq); return 0; } struct ib_rwq_ind_table *mlx5_ib_create_rwq_ind_table(struct ib_device *device, struct ib_rwq_ind_table_init_attr *init_attr, struct ib_udata *udata) { struct mlx5_ib_dev *dev = to_mdev(device); struct mlx5_ib_rwq_ind_table *rwq_ind_tbl; int sz = 1 << init_attr->log_ind_tbl_size; struct mlx5_ib_create_rwq_ind_tbl_resp resp = {}; size_t min_resp_len; int inlen; int err; int i; u32 *in; void *rqtc; if (udata->inlen > 0 && !ib_is_udata_cleared(udata, 0, udata->inlen)) return ERR_PTR(-EOPNOTSUPP); if (init_attr->log_ind_tbl_size > MLX5_CAP_GEN(dev->mdev, log_max_rqt_size)) { mlx5_ib_dbg(dev, "log_ind_tbl_size = %d is bigger than supported = %d\n", init_attr->log_ind_tbl_size, MLX5_CAP_GEN(dev->mdev, log_max_rqt_size)); return ERR_PTR(-EINVAL); } min_resp_len = offsetof(typeof(resp), reserved) + sizeof(resp.reserved); if (udata->outlen && udata->outlen < min_resp_len) return ERR_PTR(-EINVAL); rwq_ind_tbl = kzalloc(sizeof(*rwq_ind_tbl), GFP_KERNEL); if (!rwq_ind_tbl) return ERR_PTR(-ENOMEM); inlen = MLX5_ST_SZ_BYTES(create_rqt_in) + sizeof(u32) * sz; in = kvzalloc(inlen, GFP_KERNEL); if (!in) { err = -ENOMEM; goto err; } rqtc = MLX5_ADDR_OF(create_rqt_in, in, rqt_context); MLX5_SET(rqtc, rqtc, rqt_actual_size, sz); MLX5_SET(rqtc, rqtc, rqt_max_size, sz); for (i = 0; i < sz; i++) MLX5_SET(rqtc, rqtc, rq_num[i], init_attr->ind_tbl[i]->wq_num); err = mlx5_core_create_rqt(dev->mdev, in, inlen, &rwq_ind_tbl->rqtn); kvfree(in); if (err) goto err; rwq_ind_tbl->ib_rwq_ind_tbl.ind_tbl_num = rwq_ind_tbl->rqtn; if (udata->outlen) { resp.response_length = offsetof(typeof(resp), response_length) + sizeof(resp.response_length); err = ib_copy_to_udata(udata, &resp, resp.response_length); if (err) goto err_copy; } return &rwq_ind_tbl->ib_rwq_ind_tbl; err_copy: mlx5_core_destroy_rqt(dev->mdev, rwq_ind_tbl->rqtn); err: kfree(rwq_ind_tbl); return ERR_PTR(err); } int mlx5_ib_destroy_rwq_ind_table(struct ib_rwq_ind_table *ib_rwq_ind_tbl) { struct mlx5_ib_rwq_ind_table *rwq_ind_tbl = to_mrwq_ind_table(ib_rwq_ind_tbl); struct mlx5_ib_dev *dev = to_mdev(ib_rwq_ind_tbl->device); mlx5_core_destroy_rqt(dev->mdev, rwq_ind_tbl->rqtn); kfree(rwq_ind_tbl); return 0; } int mlx5_ib_modify_wq(struct ib_wq *wq, struct ib_wq_attr *wq_attr, u32 wq_attr_mask, struct ib_udata *udata) { struct mlx5_ib_dev *dev = to_mdev(wq->device); struct mlx5_ib_rwq *rwq = to_mrwq(wq); struct mlx5_ib_modify_wq ucmd = {}; size_t required_cmd_sz; int curr_wq_state; int wq_state; int inlen; int err; void *rqc; void *in; required_cmd_sz = offsetof(typeof(ucmd), reserved) + sizeof(ucmd.reserved); if (udata->inlen < required_cmd_sz) return -EINVAL; if (udata->inlen > sizeof(ucmd) && !ib_is_udata_cleared(udata, sizeof(ucmd), udata->inlen - sizeof(ucmd))) return -EOPNOTSUPP; if (ib_copy_from_udata(&ucmd, udata, min(sizeof(ucmd), udata->inlen))) return -EFAULT; if (ucmd.comp_mask || ucmd.reserved) return -EOPNOTSUPP; inlen = MLX5_ST_SZ_BYTES(modify_rq_in); in = kvzalloc(inlen, GFP_KERNEL); if (!in) return -ENOMEM; rqc = MLX5_ADDR_OF(modify_rq_in, in, ctx); curr_wq_state = (wq_attr_mask & IB_WQ_CUR_STATE) ? wq_attr->curr_wq_state : wq->state; wq_state = (wq_attr_mask & IB_WQ_STATE) ? wq_attr->wq_state : curr_wq_state; if (curr_wq_state == IB_WQS_ERR) curr_wq_state = MLX5_RQC_STATE_ERR; if (wq_state == IB_WQS_ERR) wq_state = MLX5_RQC_STATE_ERR; MLX5_SET(modify_rq_in, in, rq_state, curr_wq_state); MLX5_SET(rqc, rqc, state, wq_state); if (wq_attr_mask & IB_WQ_FLAGS) { if (wq_attr->flags_mask & IB_WQ_FLAGS_CVLAN_STRIPPING) { if (!(MLX5_CAP_GEN(dev->mdev, eth_net_offloads) && MLX5_CAP_ETH(dev->mdev, vlan_cap))) { mlx5_ib_dbg(dev, "VLAN offloads are not " "supported\n"); err = -EOPNOTSUPP; goto out; } MLX5_SET64(modify_rq_in, in, modify_bitmask, MLX5_MODIFY_RQ_IN_MODIFY_BITMASK_VSD); MLX5_SET(rqc, rqc, vsd, (wq_attr->flags & IB_WQ_FLAGS_CVLAN_STRIPPING) ? 0 : 1); } if (wq_attr->flags_mask & IB_WQ_FLAGS_PCI_WRITE_END_PADDING) { mlx5_ib_dbg(dev, "Modifying scatter end padding is not supported\n"); err = -EOPNOTSUPP; goto out; } } if (curr_wq_state == IB_WQS_RESET && wq_state == IB_WQS_RDY) { if (MLX5_CAP_GEN(dev->mdev, modify_rq_counter_set_id)) { MLX5_SET64(modify_rq_in, in, modify_bitmask, MLX5_MODIFY_RQ_IN_MODIFY_BITMASK_RQ_COUNTER_SET_ID); MLX5_SET(rqc, rqc, counter_set_id, dev->port->cnts.set_id); } else pr_info_once("%s: Receive WQ counters are not supported on current FW\n", dev->ib_dev.name); } err = mlx5_core_modify_rq(dev->mdev, rwq->core_qp.qpn, in, inlen); if (!err) rwq->ibwq.state = (wq_state == MLX5_RQC_STATE_ERR) ? IB_WQS_ERR : wq_state; out: kvfree(in); return err; } struct mlx5_ib_drain_cqe { struct ib_cqe cqe; struct completion done; }; static void mlx5_ib_drain_qp_done(struct ib_cq *cq, struct ib_wc *wc) { struct mlx5_ib_drain_cqe *cqe = container_of(wc->wr_cqe, struct mlx5_ib_drain_cqe, cqe); complete(&cqe->done); } /* This function returns only once the drained WR was completed */ static void handle_drain_completion(struct ib_cq *cq, struct mlx5_ib_drain_cqe *sdrain, struct mlx5_ib_dev *dev) { struct mlx5_core_dev *mdev = dev->mdev; if (cq->poll_ctx == IB_POLL_DIRECT) { while (wait_for_completion_timeout(&sdrain->done, HZ / 10) <= 0) ib_process_cq_direct(cq, -1); return; } if (mdev->state == MLX5_DEVICE_STATE_INTERNAL_ERROR) { struct mlx5_ib_cq *mcq = to_mcq(cq); bool triggered = false; unsigned long flags; spin_lock_irqsave(&dev->reset_flow_resource_lock, flags); /* Make sure that the CQ handler won't run if wasn't run yet */ if (!mcq->mcq.reset_notify_added) mcq->mcq.reset_notify_added = 1; else triggered = true; spin_unlock_irqrestore(&dev->reset_flow_resource_lock, flags); if (triggered) { /* Wait for any scheduled/running task to be ended */ switch (cq->poll_ctx) { case IB_POLL_SOFTIRQ: irq_poll_disable(&cq->iop); irq_poll_enable(&cq->iop); break; case IB_POLL_WORKQUEUE: cancel_work_sync(&cq->work); break; default: WARN_ON_ONCE(1); } } /* Run the CQ handler - this makes sure that the drain WR will * be processed if wasn't processed yet. */ mcq->mcq.comp(&mcq->mcq); } wait_for_completion(&sdrain->done); } void mlx5_ib_drain_sq(struct ib_qp *qp) { struct ib_cq *cq = qp->send_cq; struct ib_qp_attr attr = { .qp_state = IB_QPS_ERR }; struct mlx5_ib_drain_cqe sdrain; const struct ib_send_wr *bad_swr; struct ib_rdma_wr swr = { .wr = { .next = NULL, { .wr_cqe = &sdrain.cqe, }, .opcode = IB_WR_RDMA_WRITE, }, }; int ret; struct mlx5_ib_dev *dev = to_mdev(qp->device); struct mlx5_core_dev *mdev = dev->mdev; ret = ib_modify_qp(qp, &attr, IB_QP_STATE); if (ret && mdev->state != MLX5_DEVICE_STATE_INTERNAL_ERROR) { WARN_ONCE(ret, "failed to drain send queue: %d\n", ret); return; } sdrain.cqe.done = mlx5_ib_drain_qp_done; init_completion(&sdrain.done); ret = _mlx5_ib_post_send(qp, &swr.wr, &bad_swr, true); if (ret) { WARN_ONCE(ret, "failed to drain send queue: %d\n", ret); return; } handle_drain_completion(cq, &sdrain, dev); } void mlx5_ib_drain_rq(struct ib_qp *qp) { struct ib_cq *cq = qp->recv_cq; struct ib_qp_attr attr = { .qp_state = IB_QPS_ERR }; struct mlx5_ib_drain_cqe rdrain; struct ib_recv_wr rwr = {}; const struct ib_recv_wr *bad_rwr; int ret; struct mlx5_ib_dev *dev = to_mdev(qp->device); struct mlx5_core_dev *mdev = dev->mdev; ret = ib_modify_qp(qp, &attr, IB_QP_STATE); if (ret && mdev->state != MLX5_DEVICE_STATE_INTERNAL_ERROR) { WARN_ONCE(ret, "failed to drain recv queue: %d\n", ret); return; } rwr.wr_cqe = &rdrain.cqe; rdrain.cqe.done = mlx5_ib_drain_qp_done; init_completion(&rdrain.done); ret = _mlx5_ib_post_recv(qp, &rwr, &bad_rwr, true); if (ret) { WARN_ONCE(ret, "failed to drain recv queue: %d\n", ret); return; } handle_drain_completion(cq, &rdrain, dev); }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_544_0
crossvul-cpp_data_good_1848_2
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % TTTTT H H RRRR EEEEE SSSSS H H OOO L DDDD % % T H H R R E SS H H O O L D D % % T HHHHH RRRR EEE SSS HHHHH O O L D D % % T H H R R E SS H H O O L D D % % T H H R R EEEEE SSSSS H H OOO LLLLL DDDD % % % % % % MagickCore Image Threshold Methods % % % % Software Design % % Cristy % % October 1996 % % % % % % Copyright 1999-2015 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/property.h" #include "MagickCore/blob.h" #include "MagickCore/cache-view.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colormap.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/configure.h" #include "MagickCore/constitute.h" #include "MagickCore/decorate.h" #include "MagickCore/draw.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/effect.h" #include "MagickCore/fx.h" #include "MagickCore/gem.h" #include "MagickCore/geometry.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/montage.h" #include "MagickCore/option.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/quantize.h" #include "MagickCore/quantum.h" #include "MagickCore/random_.h" #include "MagickCore/random-private.h" #include "MagickCore/resize.h" #include "MagickCore/resource_.h" #include "MagickCore/segment.h" #include "MagickCore/shear.h" #include "MagickCore/signature-private.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #include "MagickCore/threshold.h" #include "MagickCore/token.h" #include "MagickCore/transform.h" #include "MagickCore/xml-tree.h" #include "MagickCore/xml-tree-private.h" /* Define declarations. */ #define ThresholdsFilename "thresholds.xml" /* Typedef declarations. */ struct _ThresholdMap { char *map_id, *description; size_t width, height; ssize_t divisor, *levels; }; /* Static declarations. */ static const char *MinimalThresholdMap = "<?xml version=\"1.0\"?>" "<thresholds>" " <threshold map=\"threshold\" alias=\"1x1\">" " <description>Threshold 1x1 (non-dither)</description>" " <levels width=\"1\" height=\"1\" divisor=\"2\">" " 1" " </levels>" " </threshold>" " <threshold map=\"checks\" alias=\"2x1\">" " <description>Checkerboard 2x1 (dither)</description>" " <levels width=\"2\" height=\"2\" divisor=\"3\">" " 1 2" " 2 1" " </levels>" " </threshold>" "</thresholds>"; /* Forward declarations. */ static ThresholdMap *GetThresholdMapFile(const char *,const char *,const char *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A d a p t i v e T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AdaptiveThresholdImage() selects an individual threshold for each pixel % based on the range of intensity values in its local neighborhood. This % allows for thresholding of an image whose global intensity histogram % doesn't contain distinctive peaks. % % The format of the AdaptiveThresholdImage method is: % % Image *AdaptiveThresholdImage(const Image *image,const size_t width, % const size_t height,const double bias,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o width: the width of the local neighborhood. % % o height: the height of the local neighborhood. % % o bias: the mean bias. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *AdaptiveThresholdImage(const Image *image, const size_t width,const size_t height,const double bias, ExceptionInfo *exception) { #define AdaptiveThresholdImageTag "AdaptiveThreshold/Image" CacheView *image_view, *threshold_view; Image *threshold_image; MagickBooleanType status; MagickOffsetType progress; MagickSizeType number_pixels; ssize_t y; /* Initialize threshold image attributes. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); threshold_image=CloneImage(image,image->columns,image->rows,MagickTrue, exception); if (threshold_image == (Image *) NULL) return((Image *) NULL); status=SetImageStorageClass(threshold_image,DirectClass,exception); if (status == MagickFalse) { threshold_image=DestroyImage(threshold_image); return((Image *) NULL); } /* Threshold image. */ status=MagickTrue; progress=0; number_pixels=(MagickSizeType) width*height; image_view=AcquireVirtualCacheView(image,exception); threshold_view=AcquireAuthenticCacheView(threshold_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,threshold_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { double channel_bias[MaxPixelChannels], channel_sum[MaxPixelChannels]; register const Quantum *restrict p, *restrict pixels; register Quantum *restrict q; register ssize_t i, x; ssize_t center, u, v; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t) (height/2L),image->columns+width,height,exception); q=QueueCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns, 1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } center=(ssize_t) GetPixelChannels(image)*(image->columns+width)*(height/2L)+ GetPixelChannels(image)*(width/2); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image, channel); if ((traits == UndefinedPixelTrait) || (threshold_traits == UndefinedPixelTrait)) continue; if (((threshold_traits & CopyPixelTrait) != 0) || (GetPixelReadMask(image,p) == 0)) { SetPixelChannel(threshold_image,channel,p[center+i],q); continue; } pixels=p; channel_bias[channel]=0.0; channel_sum[channel]=0.0; for (v=0; v < (ssize_t) height; v++) { for (u=0; u < (ssize_t) width; u++) { if (u == (ssize_t) (width-1)) channel_bias[channel]+=pixels[i]; channel_sum[channel]+=pixels[i]; pixels+=GetPixelChannels(image); } pixels+=GetPixelChannels(image)*image->columns; } } for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double mean; PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image, channel); if ((traits == UndefinedPixelTrait) || (threshold_traits == UndefinedPixelTrait)) continue; if (((threshold_traits & CopyPixelTrait) != 0) || (GetPixelReadMask(image,p) == 0)) { SetPixelChannel(threshold_image,channel,p[center+i],q); continue; } channel_sum[channel]-=channel_bias[channel]; channel_bias[channel]=0.0; pixels=p; for (v=0; v < (ssize_t) height; v++) { channel_bias[channel]+=pixels[i]; pixels+=(width-1)*GetPixelChannels(image); channel_sum[channel]+=pixels[i]; pixels+=GetPixelChannels(image)*(image->columns+1); } mean=(double) (channel_sum[channel]/number_pixels+bias); SetPixelChannel(threshold_image,channel,(Quantum) ((double) p[center+i] <= mean ? 0 : QuantumRange),q); } p+=GetPixelChannels(image); q+=GetPixelChannels(threshold_image); } if (SyncCacheViewAuthenticPixels(threshold_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_AdaptiveThresholdImage) #endif proceed=SetImageProgress(image,AdaptiveThresholdImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } threshold_image->type=image->type; threshold_view=DestroyCacheView(threshold_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) threshold_image=DestroyImage(threshold_image); return(threshold_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % B i l e v e l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % BilevelImage() changes the value of individual pixels based on the % intensity of each pixel channel. The result is a high-contrast image. % % More precisely each channel value of the image is 'thresholded' so that if % it is equal to or less than the given value it is set to zero, while any % value greater than that give is set to it maximum or QuantumRange. % % This function is what is used to implement the "-threshold" operator for % the command line API. % % If the default channel setting is given the image is thresholded using just % the gray 'intensity' of the image, rather than the individual channels. % % The format of the BilevelImage method is: % % MagickBooleanType BilevelImage(Image *image,const double threshold, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o threshold: define the threshold values. % % o exception: return any errors or warnings in this structure. % % Aside: You can get the same results as operator using LevelImages() % with the 'threshold' value for both the black_point and the white_point. % */ MagickExport MagickBooleanType BilevelImage(Image *image,const double threshold, ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if (IsGrayColorspace(image->colorspace) != MagickFalse) (void) SetImageColorspace(image,sRGBColorspace,exception); /* Bilevel threshold image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double pixel; register ssize_t i; if (GetPixelReadMask(image,q) == 0) { q+=GetPixelChannels(image); continue; } pixel=GetPixelIntensity(image,q); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; if (image->channel_mask != DefaultChannels) pixel=(double) q[i]; q[i]=(Quantum) (pixel <= threshold ? 0 : QuantumRange); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_BilevelImage) #endif proceed=SetImageProgress(image,ThresholdImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % B l a c k T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % BlackThresholdImage() is like ThresholdImage() but forces all pixels below % the threshold into black while leaving all pixels at or above the threshold % unchanged. % % The format of the BlackThresholdImage method is: % % MagickBooleanType BlackThresholdImage(Image *image, % const char *threshold,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o threshold: define the threshold value. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType BlackThresholdImage(Image *image, const char *thresholds,ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view; GeometryInfo geometry_info; MagickBooleanType status; MagickOffsetType progress; PixelInfo threshold; MagickStatusType flags; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (thresholds == (const char *) NULL) return(MagickTrue); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if (IsGrayColorspace(image->colorspace) != MagickFalse) (void) SetImageColorspace(image,sRGBColorspace,exception); GetPixelInfo(image,&threshold); flags=ParseGeometry(thresholds,&geometry_info); threshold.red=geometry_info.rho; threshold.green=geometry_info.rho; threshold.blue=geometry_info.rho; threshold.black=geometry_info.rho; threshold.alpha=100.0; if ((flags & SigmaValue) != 0) threshold.green=geometry_info.sigma; if ((flags & XiValue) != 0) threshold.blue=geometry_info.xi; if ((flags & PsiValue) != 0) threshold.alpha=geometry_info.psi; if (threshold.colorspace == CMYKColorspace) { if ((flags & PsiValue) != 0) threshold.black=geometry_info.psi; if ((flags & ChiValue) != 0) threshold.alpha=geometry_info.chi; } if ((flags & PercentValue) != 0) { threshold.red*=(MagickRealType) (QuantumRange/100.0); threshold.green*=(MagickRealType) (QuantumRange/100.0); threshold.blue*=(MagickRealType) (QuantumRange/100.0); threshold.black*=(MagickRealType) (QuantumRange/100.0); threshold.alpha*=(MagickRealType) (QuantumRange/100.0); } /* White threshold image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double pixel; register ssize_t i; if (GetPixelReadMask(image,q) == 0) { q+=GetPixelChannels(image); continue; } pixel=GetPixelIntensity(image,q); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; if (image->channel_mask != DefaultChannels) pixel=(double) q[i]; if (pixel <= GetPixelInfoChannel(&threshold,channel)) q[i]=(Quantum) 0; } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_BlackThresholdImage) #endif proceed=SetImageProgress(image,ThresholdImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l a m p I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClampImage() set each pixel whose value is below zero to zero and any the % pixel whose value is above the quantum range to the quantum range (e.g. % 65535) otherwise the pixel value remains unchanged. % % The format of the ClampImage method is: % % MagickBooleanType ClampImage(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ClampImage(Image *image,ExceptionInfo *exception) { #define ClampImageTag "Clamp/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) { register ssize_t i; register PixelInfo *restrict q; q=image->colormap; for (i=0; i < (ssize_t) image->colors; i++) { q->red=(double) ClampPixel(q->red); q->green=(double) ClampPixel(q->green); q->blue=(double) ClampPixel(q->blue); q->alpha=(double) ClampPixel(q->alpha); q++; } return(SyncImage(image,exception)); } /* Clamp image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; if (GetPixelReadMask(image,q) == 0) { q+=GetPixelChannels(image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[i]=ClampPixel(q[i]); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ClampImage) #endif proceed=SetImageProgress(image,ClampImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y T h r e s h o l d M a p % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyThresholdMap() de-allocate the given ThresholdMap % % The format of the ListThresholdMaps method is: % % ThresholdMap *DestroyThresholdMap(Threshold *map) % % A description of each parameter follows. % % o map: Pointer to the Threshold map to destroy % */ MagickExport ThresholdMap *DestroyThresholdMap(ThresholdMap *map) { assert(map != (ThresholdMap *) NULL); if (map->map_id != (char *) NULL) map->map_id=DestroyString(map->map_id); if (map->description != (char *) NULL) map->description=DestroyString(map->description); if (map->levels != (ssize_t *) NULL) map->levels=(ssize_t *) RelinquishMagickMemory(map->levels); map=(ThresholdMap *) RelinquishMagickMemory(map); return(map); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t T h r e s h o l d M a p % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetThresholdMap() loads and searches one or more threshold map files for the % map matching the given name or alias. % % The format of the GetThresholdMap method is: % % ThresholdMap *GetThresholdMap(const char *map_id, % ExceptionInfo *exception) % % A description of each parameter follows. % % o map_id: ID of the map to look for. % % o exception: return any errors or warnings in this structure. % */ MagickExport ThresholdMap *GetThresholdMap(const char *map_id, ExceptionInfo *exception) { const StringInfo *option; LinkedListInfo *options; ThresholdMap *map; map=GetThresholdMapFile(MinimalThresholdMap,"built-in",map_id,exception); if (map != (ThresholdMap *) NULL) return(map); options=GetConfigureOptions(ThresholdsFilename,exception); option=(const StringInfo *) GetNextValueInLinkedList(options); while (option != (const StringInfo *) NULL) { map=GetThresholdMapFile((const char *) GetStringInfoDatum(option), GetStringInfoPath(option),map_id,exception); if (map != (ThresholdMap *) NULL) break; option=(const StringInfo *) GetNextValueInLinkedList(options); } options=DestroyConfigureOptions(options); return(map); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t T h r e s h o l d M a p F i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetThresholdMapFile() look for a given threshold map name or alias in the % given XML file data, and return the allocated the map when found. % % The format of the ListThresholdMaps method is: % % ThresholdMap *GetThresholdMap(const char *xml,const char *filename, % const char *map_id,ExceptionInfo *exception) % % A description of each parameter follows. % % o xml: The threshold map list in XML format. % % o filename: The threshold map XML filename. % % o map_id: ID of the map to look for in XML list. % % o exception: return any errors or warnings in this structure. % */ static ThresholdMap *GetThresholdMapFile(const char *xml,const char *filename, const char *map_id,ExceptionInfo *exception) { char *p; const char *attribute, *content; double value; register ssize_t i; ThresholdMap *map; XMLTreeInfo *description, *levels, *threshold, *thresholds; (void) LogMagickEvent(ConfigureEvent,GetMagickModule(), "Loading threshold map file \"%s\" ...",filename); map=(ThresholdMap *) NULL; thresholds=NewXMLTree(xml,exception); if (thresholds == (XMLTreeInfo *) NULL) return(map); for (threshold=GetXMLTreeChild(thresholds,"threshold"); threshold != (XMLTreeInfo *) NULL; threshold=GetNextXMLTreeTag(threshold)) { attribute=GetXMLTreeAttribute(threshold,"map"); if ((attribute != (char *) NULL) && (LocaleCompare(map_id,attribute) == 0)) break; attribute=GetXMLTreeAttribute(threshold,"alias"); if ((attribute != (char *) NULL) && (LocaleCompare(map_id,attribute) == 0)) break; } if (threshold == (XMLTreeInfo *) NULL) { thresholds=DestroyXMLTree(thresholds); return(map); } description=GetXMLTreeChild(threshold,"description"); if (description == (XMLTreeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingElement", "<description>, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); return(map); } levels=GetXMLTreeChild(threshold,"levels"); if (levels == (XMLTreeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingElement", "<levels>, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); return(map); } map=(ThresholdMap *) AcquireMagickMemory(sizeof(ThresholdMap)); if (map == (ThresholdMap *) NULL) ThrowFatalException(ResourceLimitFatalError,"UnableToAcquireThresholdMap"); map->map_id=(char *) NULL; map->description=(char *) NULL; map->levels=(ssize_t *) NULL; attribute=GetXMLTreeAttribute(threshold,"map"); if (attribute != (char *) NULL) map->map_id=ConstantString(attribute); content=GetXMLTreeContent(description); if (content != (char *) NULL) map->description=ConstantString(content); attribute=GetXMLTreeAttribute(levels,"width"); if (attribute == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute", "<levels width>, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } map->width=StringToUnsignedLong(attribute); if (map->width == 0) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidAttribute", "<levels width>, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } attribute=GetXMLTreeAttribute(levels,"height"); if (attribute == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute", "<levels height>, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } map->height=StringToUnsignedLong(attribute); if (map->height == 0) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidAttribute", "<levels height>, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } attribute=GetXMLTreeAttribute(levels,"divisor"); if (attribute == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute", "<levels divisor>, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } map->divisor=(ssize_t) StringToLong(attribute); if (map->divisor < 2) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidAttribute", "<levels divisor>, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } content=GetXMLTreeContent(levels); if (content == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingContent", "<levels>, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } map->levels=(ssize_t *) AcquireQuantumMemory((size_t) map->width,map->height* sizeof(*map->levels)); if (map->levels == (ssize_t *) NULL) ThrowFatalException(ResourceLimitFatalError,"UnableToAcquireThresholdMap"); for (i=0; i < (ssize_t) (map->width*map->height); i++) { map->levels[i]=(ssize_t) strtol(content,&p,10); if (p == content) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidContent", "<level> too few values, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } if ((map->levels[i] < 0) || (map->levels[i] > map->divisor)) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidContent", "<level> %.20g out of range, map \"%s\"", (double) map->levels[i],map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } content=p; } value=(double) strtol(content,&p,10); (void) value; if (p != content) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidContent", "<level> too many values, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } thresholds=DestroyXMLTree(thresholds); return(map); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + L i s t T h r e s h o l d M a p F i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ListThresholdMapFile() lists the threshold maps and their descriptions % in the given XML file data. % % The format of the ListThresholdMaps method is: % % MagickBooleanType ListThresholdMaps(FILE *file,const char*xml, % const char *filename,ExceptionInfo *exception) % % A description of each parameter follows. % % o file: An pointer to the output FILE. % % o xml: The threshold map list in XML format. % % o filename: The threshold map XML filename. % % o exception: return any errors or warnings in this structure. % */ MagickBooleanType ListThresholdMapFile(FILE *file,const char *xml, const char *filename,ExceptionInfo *exception) { const char *alias, *content, *map; XMLTreeInfo *description, *threshold, *thresholds; assert( xml != (char *) NULL ); assert( file != (FILE *) NULL ); (void) LogMagickEvent(ConfigureEvent,GetMagickModule(), "Loading threshold map file \"%s\" ...",filename); thresholds=NewXMLTree(xml,exception); if ( thresholds == (XMLTreeInfo *) NULL ) return(MagickFalse); (void) FormatLocaleFile(file,"%-16s %-12s %s\n","Map","Alias","Description"); (void) FormatLocaleFile(file, "----------------------------------------------------\n"); threshold=GetXMLTreeChild(thresholds,"threshold"); for ( ; threshold != (XMLTreeInfo *) NULL; threshold=GetNextXMLTreeTag(threshold)) { map=GetXMLTreeAttribute(threshold,"map"); if (map == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute", "<map>"); thresholds=DestroyXMLTree(thresholds); return(MagickFalse); } alias=GetXMLTreeAttribute(threshold,"alias"); description=GetXMLTreeChild(threshold,"description"); if (description == (XMLTreeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingElement", "<description>, map \"%s\"",map); thresholds=DestroyXMLTree(thresholds); return(MagickFalse); } content=GetXMLTreeContent(description); if (content == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingContent", "<description>, map \"%s\"", map); thresholds=DestroyXMLTree(thresholds); return(MagickFalse); } (void) FormatLocaleFile(file,"%-16s %-12s %s\n",map,alias ? alias : "", content); } thresholds=DestroyXMLTree(thresholds); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L i s t T h r e s h o l d M a p s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ListThresholdMaps() lists the threshold maps and their descriptions % as defined by "threshold.xml" to a file. % % The format of the ListThresholdMaps method is: % % MagickBooleanType ListThresholdMaps(FILE *file,ExceptionInfo *exception) % % A description of each parameter follows. % % o file: An pointer to the output FILE. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ListThresholdMaps(FILE *file, ExceptionInfo *exception) { const StringInfo *option; LinkedListInfo *options; MagickStatusType status; status=MagickTrue; if (file == (FILE *) NULL) file=stdout; options=GetConfigureOptions(ThresholdsFilename,exception); (void) FormatLocaleFile(file, "\n Threshold Maps for Ordered Dither Operations\n"); option=(const StringInfo *) GetNextValueInLinkedList(options); while (option != (const StringInfo *) NULL) { (void) FormatLocaleFile(file,"\nPath: %s\n\n",GetStringInfoPath(option)); status&=ListThresholdMapFile(file,(const char *) GetStringInfoDatum(option), GetStringInfoPath(option),exception); option=(const StringInfo *) GetNextValueInLinkedList(options); } options=DestroyConfigureOptions(options); return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O r d e r e d P o s t e r i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OrderedPosterizeImage() will perform a ordered dither based on a number % of pre-defined dithering threshold maps, but over multiple intensity % levels, which can be different for different channels, according to the % input argument. % % The format of the OrderedPosterizeImage method is: % % MagickBooleanType OrderedPosterizeImage(Image *image, % const char *threshold_map,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o threshold_map: A string containing the name of the threshold dither % map to use, followed by zero or more numbers representing the number % of color levels tho dither between. % % Any level number less than 2 will be equivalent to 2, and means only % binary dithering will be applied to each color channel. % % No numbers also means a 2 level (bitmap) dither will be applied to all % channels, while a single number is the number of levels applied to each % channel in sequence. More numbers will be applied in turn to each of % the color channels. % % For example: "o3x3,6" will generate a 6 level posterization of the % image with a ordered 3x3 diffused pixel dither being applied between % each level. While checker,8,8,4 will produce a 332 colormaped image % with only a single checkerboard hash pattern (50% grey) between each % color level, to basically double the number of color levels with % a bare minimim of dithering. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType OrderedPosterizeImage(Image *image, const char *threshold_map,ExceptionInfo *exception) { #define DitherImageTag "Dither/Image" CacheView *image_view; char token[MaxTextExtent]; const char *p; double levels[CompositePixelChannel]; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t y; ThresholdMap *map; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); if (threshold_map == (const char *) NULL) return(MagickTrue); p=(char *) threshold_map; while (((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) && (*p != '\0')) p++; threshold_map=p; while (((isspace((int) ((unsigned char) *p)) == 0) && (*p != ',')) && (*p != '\0')) { if ((p-threshold_map) >= (MaxTextExtent-1)) break; token[p-threshold_map]=(*p); p++; } token[p-threshold_map]='\0'; map=GetThresholdMap(token,exception); if (map == (ThresholdMap *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "InvalidArgument","%s : '%s'","ordered-dither",threshold_map); return(MagickFalse); } for (i=0; i < MaxPixelChannels; i++) levels[i]=2.0; p=strchr((char *) threshold_map,','); if ((p != (char *) NULL) && (isdigit((int) ((unsigned char) *(++p))) != 0)) for (i=0; (*p != '\0') && (i < MaxPixelChannels); i++) { GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); levels[i]=StringToDouble(token,(char **) NULL); } for (i=0; i < MaxPixelChannels; i++) if (fabs(levels[i]) >= 1) levels[i]-=1.0; if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; ssize_t n; n=0; if (GetPixelReadMask(image,q) == 0) { q+=GetPixelChannels(image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { ssize_t level, threshold; PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; if (fabs(levels[n++]) < MagickEpsilon) continue; threshold=(ssize_t) (QuantumScale*q[i]*(levels[n]*(map->divisor-1)+1)); level=threshold/(map->divisor-1); threshold-=level*(map->divisor-1); q[i]=ClampToQuantum((double) (level+(threshold >= map->levels[(x % map->width)+map->width*(y % map->height)]))* QuantumRange/levels[n]); n++; } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_OrderedPosterizeImage) #endif proceed=SetImageProgress(image,DitherImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); map=DestroyThresholdMap(map); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P e r c e p t i b l e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PerceptibleImage() set each pixel whose value is less than |epsilon| to % epsilon or -epsilon (whichever is closer) otherwise the pixel value remains % unchanged. % % The format of the PerceptibleImage method is: % % MagickBooleanType PerceptibleImage(Image *image,const double epsilon, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o epsilon: the epsilon threshold (e.g. 1.0e-9). % % o exception: return any errors or warnings in this structure. % */ static inline Quantum PerceptibleThreshold(const Quantum quantum, const double epsilon) { double sign; sign=(double) quantum < 0.0 ? -1.0 : 1.0; if ((sign*quantum) >= epsilon) return(quantum); return((Quantum) (sign*epsilon)); } MagickExport MagickBooleanType PerceptibleImage(Image *image, const double epsilon,ExceptionInfo *exception) { #define PerceptibleImageTag "Perceptible/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) { register ssize_t i; register PixelInfo *restrict q; q=image->colormap; for (i=0; i < (ssize_t) image->colors; i++) { q->red=(double) PerceptibleThreshold(ClampToQuantum(q->red), epsilon); q->green=(double) PerceptibleThreshold(ClampToQuantum(q->green), epsilon); q->blue=(double) PerceptibleThreshold(ClampToQuantum(q->blue), epsilon); q->alpha=(double) PerceptibleThreshold(ClampToQuantum(q->alpha), epsilon); q++; } return(SyncImage(image,exception)); } /* Perceptible image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; if (GetPixelReadMask(image,q) == 0) { q+=GetPixelChannels(image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; q[i]=PerceptibleThreshold(q[i],epsilon); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_PerceptibleImage) #endif proceed=SetImageProgress(image,PerceptibleImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R a n d o m T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RandomThresholdImage() changes the value of individual pixels based on the % intensity of each pixel compared to a random threshold. The result is a % low-contrast, two color image. % % The format of the RandomThresholdImage method is: % % MagickBooleanType RandomThresholdImage(Image *image, % const char *thresholds,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o thresholds: a geometry string containing low,high thresholds. If the % string contains 2x2, 3x3, or 4x4, an ordered dither of order 2, 3, or 4 % is performed instead. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType RandomThresholdImage(Image *image, const char *thresholds,ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view; double min_threshold, max_threshold; GeometryInfo geometry_info; MagickStatusType flags; MagickBooleanType status; MagickOffsetType progress; PixelInfo threshold; RandomInfo **restrict random_info; ssize_t y; #if defined(MAGICKCORE_OPENMP_SUPPORT) unsigned long key; #endif assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); if (thresholds == (const char *) NULL) return(MagickTrue); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); GetPixelInfo(image,&threshold); min_threshold=0.0; max_threshold=(double) QuantumRange; flags=ParseGeometry(thresholds,&geometry_info); min_threshold=geometry_info.rho; max_threshold=geometry_info.sigma; if ((flags & SigmaValue) == 0) max_threshold=min_threshold; if (strchr(thresholds,'%') != (char *) NULL) { max_threshold*=(double) (0.01*QuantumRange); min_threshold*=(double) (0.01*QuantumRange); } /* Random threshold image. */ status=MagickTrue; progress=0; random_info=AcquireRandomInfoThreadSet(); #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #endif image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); register Quantum *restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; if (GetPixelReadMask(image,q) == 0) { q+=GetPixelChannels(image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double threshold; PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; if ((double) q[i] < min_threshold) threshold=min_threshold; else if ((double) q[i] > max_threshold) threshold=max_threshold; else threshold=(double) (QuantumRange* GetPseudoRandomValue(random_info[id])); q[i]=(double) q[i] <= threshold ? 0 : QuantumRange; } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_RandomThresholdImage) #endif proceed=SetImageProgress(image,ThresholdImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); random_info=DestroyRandomInfoThreadSet(random_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W h i t e T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WhiteThresholdImage() is like ThresholdImage() but forces all pixels above % the threshold into white while leaving all pixels at or below the threshold % unchanged. % % The format of the WhiteThresholdImage method is: % % MagickBooleanType WhiteThresholdImage(Image *image, % const char *threshold,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o threshold: Define the threshold value. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType WhiteThresholdImage(Image *image, const char *thresholds,ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view; GeometryInfo geometry_info; MagickBooleanType status; MagickOffsetType progress; PixelInfo threshold; MagickStatusType flags; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (thresholds == (const char *) NULL) return(MagickTrue); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if (IsGrayColorspace(image->colorspace) != MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace,exception); GetPixelInfo(image,&threshold); flags=ParseGeometry(thresholds,&geometry_info); threshold.red=geometry_info.rho; threshold.green=geometry_info.rho; threshold.blue=geometry_info.rho; threshold.black=geometry_info.rho; threshold.alpha=100.0; if ((flags & SigmaValue) != 0) threshold.green=geometry_info.sigma; if ((flags & XiValue) != 0) threshold.blue=geometry_info.xi; if ((flags & PsiValue) != 0) threshold.alpha=geometry_info.psi; if (threshold.colorspace == CMYKColorspace) { if ((flags & PsiValue) != 0) threshold.black=geometry_info.psi; if ((flags & ChiValue) != 0) threshold.alpha=geometry_info.chi; } if ((flags & PercentValue) != 0) { threshold.red*=(MagickRealType) (QuantumRange/100.0); threshold.green*=(MagickRealType) (QuantumRange/100.0); threshold.blue*=(MagickRealType) (QuantumRange/100.0); threshold.black*=(MagickRealType) (QuantumRange/100.0); threshold.alpha*=(MagickRealType) (QuantumRange/100.0); } /* White threshold image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double pixel; register ssize_t i; if (GetPixelReadMask(image,q) == 0) { q+=GetPixelChannels(image); continue; } pixel=GetPixelIntensity(image,q); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; if (image->channel_mask != DefaultChannels) pixel=(double) q[i]; if (pixel > GetPixelInfoChannel(&threshold,channel)) q[i]=QuantumRange; } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_WhiteThresholdImage) #endif proceed=SetImageProgress(image,ThresholdImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); }
./CrossVul/dataset_final_sorted/CWE-119/c/good_1848_2
crossvul-cpp_data_bad_5733_3
/* * Copyright (c) 2011 Mark Himsley * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * video field order filter, heavily influenced by vf_pad.c */ #include "libavutil/opt.h" #include "libavutil/imgutils.h" #include "libavutil/internal.h" #include "libavutil/opt.h" #include "libavutil/pixdesc.h" #include "avfilter.h" #include "formats.h" #include "internal.h" #include "video.h" typedef struct { const AVClass *class; int dst_tff; ///< output bff/tff int line_size[4]; ///< bytes of pixel data per line for each plane } FieldOrderContext; static int query_formats(AVFilterContext *ctx) { AVFilterFormats *formats; enum AVPixelFormat pix_fmt; int ret; /** accept any input pixel format that is not hardware accelerated, not * a bitstream format, and does not have vertically sub-sampled chroma */ if (ctx->inputs[0]) { formats = NULL; for (pix_fmt = 0; pix_fmt < AV_PIX_FMT_NB; pix_fmt++) { const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt); if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL || desc->flags & AV_PIX_FMT_FLAG_BITSTREAM) && desc->nb_components && !desc->log2_chroma_h && (ret = ff_add_format(&formats, pix_fmt)) < 0) { ff_formats_unref(&formats); return ret; } } ff_formats_ref(formats, &ctx->inputs[0]->out_formats); ff_formats_ref(formats, &ctx->outputs[0]->in_formats); } return 0; } static int config_input(AVFilterLink *inlink) { AVFilterContext *ctx = inlink->dst; FieldOrderContext *s = ctx->priv; int plane; /** full an array with the number of bytes that the video * data occupies per line for each plane of the input video */ for (plane = 0; plane < 4; plane++) { s->line_size[plane] = av_image_get_linesize(inlink->format, inlink->w, plane); } return 0; } static AVFrame *get_video_buffer(AVFilterLink *inlink, int w, int h) { AVFilterContext *ctx = inlink->dst; AVFilterLink *outlink = ctx->outputs[0]; return ff_get_video_buffer(outlink, w, h); } static int filter_frame(AVFilterLink *inlink, AVFrame *frame) { AVFilterContext *ctx = inlink->dst; FieldOrderContext *s = ctx->priv; AVFilterLink *outlink = ctx->outputs[0]; int h, plane, line_step, line_size, line; uint8_t *data; if (!frame->interlaced_frame || frame->top_field_first == s->dst_tff) return ff_filter_frame(outlink, frame); av_dlog(ctx, "picture will move %s one line\n", s->dst_tff ? "up" : "down"); h = frame->height; for (plane = 0; plane < 4 && frame->data[plane]; plane++) { line_step = frame->linesize[plane]; line_size = s->line_size[plane]; data = frame->data[plane]; if (s->dst_tff) { /** Move every line up one line, working from * the top to the bottom of the frame. * The original top line is lost. * The new last line is created as a copy of the * penultimate line from that field. */ for (line = 0; line < h; line++) { if (1 + line < frame->height) { memcpy(data, data + line_step, line_size); } else { memcpy(data, data - line_step - line_step, line_size); } data += line_step; } } else { /** Move every line down one line, working from * the bottom to the top of the frame. * The original bottom line is lost. * The new first line is created as a copy of the * second line from that field. */ data += (h - 1) * line_step; for (line = h - 1; line >= 0 ; line--) { if (line > 0) { memcpy(data, data - line_step, line_size); } else { memcpy(data, data + line_step + line_step, line_size); } data -= line_step; } } } frame->top_field_first = s->dst_tff; return ff_filter_frame(outlink, frame); } #define OFFSET(x) offsetof(FieldOrderContext, x) #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM static const AVOption fieldorder_options[] = { { "order", "output field order", OFFSET(dst_tff), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, FLAGS, "order" }, { "bff", "bottom field first", 0, AV_OPT_TYPE_CONST, { .i64 = 0 }, .flags=FLAGS, .unit = "order" }, { "tff", "top field first", 0, AV_OPT_TYPE_CONST, { .i64 = 1 }, .flags=FLAGS, .unit = "order" }, { NULL }, }; AVFILTER_DEFINE_CLASS(fieldorder); static const AVFilterPad avfilter_vf_fieldorder_inputs[] = { { .name = "default", .type = AVMEDIA_TYPE_VIDEO, .config_props = config_input, .get_video_buffer = get_video_buffer, .filter_frame = filter_frame, .needs_writable = 1, }, { NULL } }; static const AVFilterPad avfilter_vf_fieldorder_outputs[] = { { .name = "default", .type = AVMEDIA_TYPE_VIDEO, }, { NULL } }; AVFilter avfilter_vf_fieldorder = { .name = "fieldorder", .description = NULL_IF_CONFIG_SMALL("Set the field order."), .priv_size = sizeof(FieldOrderContext), .priv_class = &fieldorder_class, .query_formats = query_formats, .inputs = avfilter_vf_fieldorder_inputs, .outputs = avfilter_vf_fieldorder_outputs, };
./CrossVul/dataset_final_sorted/CWE-119/c/bad_5733_3
crossvul-cpp_data_bad_5828_0
/* * JPEG 2000 image decoder * Copyright (c) 2007 Kamil Nowosad * Copyright (c) 2013 Nicolas Bertrand <nicoinattendu@gmail.com> * * 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 * JPEG 2000 image decoder */ #include "libavutil/avassert.h" #include "libavutil/common.h" #include "libavutil/opt.h" #include "libavutil/pixdesc.h" #include "avcodec.h" #include "bytestream.h" #include "internal.h" #include "thread.h" #include "jpeg2000.h" #define JP2_SIG_TYPE 0x6A502020 #define JP2_SIG_VALUE 0x0D0A870A #define JP2_CODESTREAM 0x6A703263 #define JP2_HEADER 0x6A703268 #define HAD_COC 0x01 #define HAD_QCC 0x02 typedef struct Jpeg2000TilePart { uint8_t tile_index; // Tile index who refers the tile-part const uint8_t *tp_end; GetByteContext tpg; // bit stream in tile-part } Jpeg2000TilePart; /* RMK: For JPEG2000 DCINEMA 3 tile-parts in a tile * one per component, so tile_part elements have a size of 3 */ typedef struct Jpeg2000Tile { Jpeg2000Component *comp; uint8_t properties[4]; Jpeg2000CodingStyle codsty[4]; Jpeg2000QuantStyle qntsty[4]; Jpeg2000TilePart tile_part[4]; uint16_t tp_idx; // Tile-part index } Jpeg2000Tile; typedef struct Jpeg2000DecoderContext { AVClass *class; AVCodecContext *avctx; GetByteContext g; int width, height; int image_offset_x, image_offset_y; int tile_offset_x, tile_offset_y; uint8_t cbps[4]; // bits per sample in particular components uint8_t sgnd[4]; // if a component is signed uint8_t properties[4]; int cdx[4], cdy[4]; int precision; int ncomponents; int colour_space; uint32_t palette[256]; int8_t pal8; int cdef[4]; int tile_width, tile_height; unsigned numXtiles, numYtiles; int maxtilelen; Jpeg2000CodingStyle codsty[4]; Jpeg2000QuantStyle qntsty[4]; int bit_index; int curtileno; Jpeg2000Tile *tile; /*options parameters*/ int reduction_factor; } Jpeg2000DecoderContext; /* get_bits functions for JPEG2000 packet bitstream * It is a get_bit function with a bit-stuffing routine. If the value of the * byte is 0xFF, the next byte includes an extra zero bit stuffed into the MSB. * cf. ISO-15444-1:2002 / B.10.1 Bit-stuffing routine */ static int get_bits(Jpeg2000DecoderContext *s, int n) { int res = 0; while (--n >= 0) { res <<= 1; if (s->bit_index == 0) { s->bit_index = 7 + (bytestream2_get_byte(&s->g) != 0xFFu); } s->bit_index--; res |= (bytestream2_peek_byte(&s->g) >> s->bit_index) & 1; } return res; } static void jpeg2000_flush(Jpeg2000DecoderContext *s) { if (bytestream2_get_byte(&s->g) == 0xff) bytestream2_skip(&s->g, 1); s->bit_index = 8; } /* decode the value stored in node */ static int tag_tree_decode(Jpeg2000DecoderContext *s, Jpeg2000TgtNode *node, int threshold) { Jpeg2000TgtNode *stack[30]; int sp = -1, curval = 0; if (!node) return AVERROR_INVALIDDATA; while (node && !node->vis) { stack[++sp] = node; node = node->parent; } if (node) curval = node->val; else curval = stack[sp]->val; while (curval < threshold && sp >= 0) { if (curval < stack[sp]->val) curval = stack[sp]->val; while (curval < threshold) { int ret; if ((ret = get_bits(s, 1)) > 0) { stack[sp]->vis++; break; } else if (!ret) curval++; else return ret; } stack[sp]->val = curval; sp--; } return curval; } static int pix_fmt_match(enum AVPixelFormat pix_fmt, int components, int bpc, uint32_t log2_chroma_wh, int pal8) { int match = 1; const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt); if (desc->nb_components != components) { return 0; } switch (components) { case 4: match = match && desc->comp[3].depth_minus1 + 1 >= bpc && (log2_chroma_wh >> 14 & 3) == 0 && (log2_chroma_wh >> 12 & 3) == 0; case 3: match = match && desc->comp[2].depth_minus1 + 1 >= bpc && (log2_chroma_wh >> 10 & 3) == desc->log2_chroma_w && (log2_chroma_wh >> 8 & 3) == desc->log2_chroma_h; case 2: match = match && desc->comp[1].depth_minus1 + 1 >= bpc && (log2_chroma_wh >> 6 & 3) == desc->log2_chroma_w && (log2_chroma_wh >> 4 & 3) == desc->log2_chroma_h; case 1: match = match && desc->comp[0].depth_minus1 + 1 >= bpc && (log2_chroma_wh >> 2 & 3) == 0 && (log2_chroma_wh & 3) == 0 && (desc->flags & AV_PIX_FMT_FLAG_PAL) == pal8 * AV_PIX_FMT_FLAG_PAL; } return match; } // pix_fmts with lower bpp have to be listed before // similar pix_fmts with higher bpp. #define RGB_PIXEL_FORMATS AV_PIX_FMT_PAL8,AV_PIX_FMT_RGB24,AV_PIX_FMT_RGBA,AV_PIX_FMT_RGB48,AV_PIX_FMT_RGBA64 #define GRAY_PIXEL_FORMATS AV_PIX_FMT_GRAY8,AV_PIX_FMT_GRAY8A,AV_PIX_FMT_GRAY16 #define YUV_PIXEL_FORMATS AV_PIX_FMT_YUV410P,AV_PIX_FMT_YUV411P,AV_PIX_FMT_YUVA420P, \ AV_PIX_FMT_YUV420P,AV_PIX_FMT_YUV422P,AV_PIX_FMT_YUVA422P, \ AV_PIX_FMT_YUV440P,AV_PIX_FMT_YUV444P,AV_PIX_FMT_YUVA444P, \ AV_PIX_FMT_YUV420P9,AV_PIX_FMT_YUV422P9,AV_PIX_FMT_YUV444P9, \ AV_PIX_FMT_YUVA420P9,AV_PIX_FMT_YUVA422P9,AV_PIX_FMT_YUVA444P9, \ AV_PIX_FMT_YUV420P10,AV_PIX_FMT_YUV422P10,AV_PIX_FMT_YUV444P10, \ AV_PIX_FMT_YUVA420P10,AV_PIX_FMT_YUVA422P10,AV_PIX_FMT_YUVA444P10, \ AV_PIX_FMT_YUV420P12,AV_PIX_FMT_YUV422P12,AV_PIX_FMT_YUV444P12, \ AV_PIX_FMT_YUV420P14,AV_PIX_FMT_YUV422P14,AV_PIX_FMT_YUV444P14, \ AV_PIX_FMT_YUV420P16,AV_PIX_FMT_YUV422P16,AV_PIX_FMT_YUV444P16, \ AV_PIX_FMT_YUVA420P16,AV_PIX_FMT_YUVA422P16,AV_PIX_FMT_YUVA444P16 #define XYZ_PIXEL_FORMATS AV_PIX_FMT_XYZ12 static const enum AVPixelFormat rgb_pix_fmts[] = {RGB_PIXEL_FORMATS}; static const enum AVPixelFormat gray_pix_fmts[] = {GRAY_PIXEL_FORMATS}; static const enum AVPixelFormat yuv_pix_fmts[] = {YUV_PIXEL_FORMATS}; static const enum AVPixelFormat xyz_pix_fmts[] = {XYZ_PIXEL_FORMATS}; static const enum AVPixelFormat all_pix_fmts[] = {RGB_PIXEL_FORMATS, GRAY_PIXEL_FORMATS, YUV_PIXEL_FORMATS, XYZ_PIXEL_FORMATS}; /* marker segments */ /* get sizes and offsets of image, tiles; number of components */ static int get_siz(Jpeg2000DecoderContext *s) { int i; int ncomponents; uint32_t log2_chroma_wh = 0; const enum AVPixelFormat *possible_fmts = NULL; int possible_fmts_nb = 0; if (bytestream2_get_bytes_left(&s->g) < 36) return AVERROR_INVALIDDATA; s->avctx->profile = bytestream2_get_be16u(&s->g); // Rsiz s->width = bytestream2_get_be32u(&s->g); // Width s->height = bytestream2_get_be32u(&s->g); // Height s->image_offset_x = bytestream2_get_be32u(&s->g); // X0Siz s->image_offset_y = bytestream2_get_be32u(&s->g); // Y0Siz s->tile_width = bytestream2_get_be32u(&s->g); // XTSiz s->tile_height = bytestream2_get_be32u(&s->g); // YTSiz s->tile_offset_x = bytestream2_get_be32u(&s->g); // XT0Siz s->tile_offset_y = bytestream2_get_be32u(&s->g); // YT0Siz ncomponents = bytestream2_get_be16u(&s->g); // CSiz if (ncomponents <= 0) { av_log(s->avctx, AV_LOG_ERROR, "Invalid number of components: %d\n", s->ncomponents); return AVERROR_INVALIDDATA; } if (ncomponents > 4) { avpriv_request_sample(s->avctx, "Support for %d components", s->ncomponents); return AVERROR_PATCHWELCOME; } s->ncomponents = ncomponents; if (s->tile_width <= 0 || s->tile_height <= 0) { av_log(s->avctx, AV_LOG_ERROR, "Invalid tile dimension %dx%d.\n", s->tile_width, s->tile_height); return AVERROR_INVALIDDATA; } if (bytestream2_get_bytes_left(&s->g) < 3 * s->ncomponents) return AVERROR_INVALIDDATA; for (i = 0; i < s->ncomponents; i++) { // Ssiz_i XRsiz_i, YRsiz_i uint8_t x = bytestream2_get_byteu(&s->g); s->cbps[i] = (x & 0x7f) + 1; s->precision = FFMAX(s->cbps[i], s->precision); s->sgnd[i] = !!(x & 0x80); s->cdx[i] = bytestream2_get_byteu(&s->g); s->cdy[i] = bytestream2_get_byteu(&s->g); if ( !s->cdx[i] || s->cdx[i] == 3 || s->cdx[i] > 4 || !s->cdy[i] || s->cdy[i] == 3 || s->cdy[i] > 4) { av_log(s->avctx, AV_LOG_ERROR, "Invalid sample separation %d/%d\n", s->cdx[i], s->cdy[i]); return AVERROR_INVALIDDATA; } log2_chroma_wh |= s->cdy[i] >> 1 << i * 4 | s->cdx[i] >> 1 << i * 4 + 2; } s->numXtiles = ff_jpeg2000_ceildiv(s->width - s->tile_offset_x, s->tile_width); s->numYtiles = ff_jpeg2000_ceildiv(s->height - s->tile_offset_y, s->tile_height); if (s->numXtiles * (uint64_t)s->numYtiles > INT_MAX/sizeof(*s->tile)) { s->numXtiles = s->numYtiles = 0; return AVERROR(EINVAL); } s->tile = av_mallocz_array(s->numXtiles * s->numYtiles, sizeof(*s->tile)); if (!s->tile) { s->numXtiles = s->numYtiles = 0; return AVERROR(ENOMEM); } for (i = 0; i < s->numXtiles * s->numYtiles; i++) { Jpeg2000Tile *tile = s->tile + i; tile->comp = av_mallocz(s->ncomponents * sizeof(*tile->comp)); if (!tile->comp) return AVERROR(ENOMEM); } /* compute image size with reduction factor */ s->avctx->width = ff_jpeg2000_ceildivpow2(s->width - s->image_offset_x, s->reduction_factor); s->avctx->height = ff_jpeg2000_ceildivpow2(s->height - s->image_offset_y, s->reduction_factor); if (s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_2K || s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_4K) { possible_fmts = xyz_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(xyz_pix_fmts); } else { switch (s->colour_space) { case 16: possible_fmts = rgb_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(rgb_pix_fmts); break; case 17: possible_fmts = gray_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(gray_pix_fmts); break; case 18: possible_fmts = yuv_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(yuv_pix_fmts); break; default: possible_fmts = all_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(all_pix_fmts); break; } } for (i = 0; i < possible_fmts_nb; ++i) { if (pix_fmt_match(possible_fmts[i], ncomponents, s->precision, log2_chroma_wh, s->pal8)) { s->avctx->pix_fmt = possible_fmts[i]; break; } } if (s->avctx->pix_fmt == AV_PIX_FMT_NONE) { av_log(s->avctx, AV_LOG_ERROR, "Unknown pix_fmt, profile: %d, colour_space: %d, " "components: %d, precision: %d, " "cdx[1]: %d, cdy[1]: %d, cdx[2]: %d, cdy[2]: %d\n", s->avctx->profile, s->colour_space, ncomponents, s->precision, ncomponents > 2 ? s->cdx[1] : 0, ncomponents > 2 ? s->cdy[1] : 0, ncomponents > 2 ? s->cdx[2] : 0, ncomponents > 2 ? s->cdy[2] : 0); } s->avctx->bits_per_raw_sample = s->precision; return 0; } /* get common part for COD and COC segments */ static int get_cox(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c) { uint8_t byte; if (bytestream2_get_bytes_left(&s->g) < 5) return AVERROR_INVALIDDATA; /* nreslevels = number of resolution levels = number of decomposition level +1 */ c->nreslevels = bytestream2_get_byteu(&s->g) + 1; if (c->nreslevels >= JPEG2000_MAX_RESLEVELS) { av_log(s->avctx, AV_LOG_ERROR, "nreslevels %d is invalid\n", c->nreslevels); return AVERROR_INVALIDDATA; } /* compute number of resolution levels to decode */ if (c->nreslevels < s->reduction_factor) c->nreslevels2decode = 1; else c->nreslevels2decode = c->nreslevels - s->reduction_factor; c->log2_cblk_width = (bytestream2_get_byteu(&s->g) & 15) + 2; // cblk width c->log2_cblk_height = (bytestream2_get_byteu(&s->g) & 15) + 2; // cblk height if (c->log2_cblk_width > 10 || c->log2_cblk_height > 10 || c->log2_cblk_width + c->log2_cblk_height > 12) { av_log(s->avctx, AV_LOG_ERROR, "cblk size invalid\n"); return AVERROR_INVALIDDATA; } if (c->log2_cblk_width > 6 || c->log2_cblk_height > 6) { avpriv_request_sample(s->avctx, "cblk size > 64"); return AVERROR_PATCHWELCOME; } c->cblk_style = bytestream2_get_byteu(&s->g); if (c->cblk_style != 0) { // cblk style av_log(s->avctx, AV_LOG_WARNING, "extra cblk styles %X\n", c->cblk_style); } c->transform = bytestream2_get_byteu(&s->g); // DWT transformation type /* set integer 9/7 DWT in case of BITEXACT flag */ if ((s->avctx->flags & CODEC_FLAG_BITEXACT) && (c->transform == FF_DWT97)) c->transform = FF_DWT97_INT; if (c->csty & JPEG2000_CSTY_PREC) { int i; for (i = 0; i < c->nreslevels; i++) { byte = bytestream2_get_byte(&s->g); c->log2_prec_widths[i] = byte & 0x0F; // precinct PPx c->log2_prec_heights[i] = (byte >> 4) & 0x0F; // precinct PPy } } else { memset(c->log2_prec_widths , 15, sizeof(c->log2_prec_widths )); memset(c->log2_prec_heights, 15, sizeof(c->log2_prec_heights)); } return 0; } /* get coding parameters for a particular tile or whole image*/ static int get_cod(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c, uint8_t *properties) { Jpeg2000CodingStyle tmp; int compno, ret; if (bytestream2_get_bytes_left(&s->g) < 5) return AVERROR_INVALIDDATA; tmp.csty = bytestream2_get_byteu(&s->g); // get progression order tmp.prog_order = bytestream2_get_byteu(&s->g); tmp.nlayers = bytestream2_get_be16u(&s->g); tmp.mct = bytestream2_get_byteu(&s->g); // multiple component transformation if (tmp.mct && s->ncomponents < 3) { av_log(s->avctx, AV_LOG_ERROR, "MCT %d with too few components (%d)\n", tmp.mct, s->ncomponents); return AVERROR_INVALIDDATA; } if ((ret = get_cox(s, &tmp)) < 0) return ret; for (compno = 0; compno < s->ncomponents; compno++) if (!(properties[compno] & HAD_COC)) memcpy(c + compno, &tmp, sizeof(tmp)); return 0; } /* Get coding parameters for a component in the whole image or a * particular tile. */ static int get_coc(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c, uint8_t *properties) { int compno, ret; if (bytestream2_get_bytes_left(&s->g) < 2) return AVERROR_INVALIDDATA; compno = bytestream2_get_byteu(&s->g); if (compno >= s->ncomponents) { av_log(s->avctx, AV_LOG_ERROR, "Invalid compno %d. There are %d components in the image.\n", compno, s->ncomponents); return AVERROR_INVALIDDATA; } c += compno; c->csty = bytestream2_get_byteu(&s->g); if ((ret = get_cox(s, c)) < 0) return ret; properties[compno] |= HAD_COC; return 0; } /* Get common part for QCD and QCC segments. */ static int get_qcx(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q) { int i, x; if (bytestream2_get_bytes_left(&s->g) < 1) return AVERROR_INVALIDDATA; x = bytestream2_get_byteu(&s->g); // Sqcd q->nguardbits = x >> 5; q->quantsty = x & 0x1f; if (q->quantsty == JPEG2000_QSTY_NONE) { n -= 3; if (bytestream2_get_bytes_left(&s->g) < n || n > JPEG2000_MAX_DECLEVELS*3) return AVERROR_INVALIDDATA; for (i = 0; i < n; i++) q->expn[i] = bytestream2_get_byteu(&s->g) >> 3; } else if (q->quantsty == JPEG2000_QSTY_SI) { if (bytestream2_get_bytes_left(&s->g) < 2) return AVERROR_INVALIDDATA; x = bytestream2_get_be16u(&s->g); q->expn[0] = x >> 11; q->mant[0] = x & 0x7ff; for (i = 1; i < JPEG2000_MAX_DECLEVELS * 3; i++) { int curexpn = FFMAX(0, q->expn[0] - (i - 1) / 3); q->expn[i] = curexpn; q->mant[i] = q->mant[0]; } } else { n = (n - 3) >> 1; if (bytestream2_get_bytes_left(&s->g) < 2 * n || n > JPEG2000_MAX_DECLEVELS*3) return AVERROR_INVALIDDATA; for (i = 0; i < n; i++) { x = bytestream2_get_be16u(&s->g); q->expn[i] = x >> 11; q->mant[i] = x & 0x7ff; } } return 0; } /* Get quantization parameters for a particular tile or a whole image. */ static int get_qcd(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q, uint8_t *properties) { Jpeg2000QuantStyle tmp; int compno, ret; if ((ret = get_qcx(s, n, &tmp)) < 0) return ret; for (compno = 0; compno < s->ncomponents; compno++) if (!(properties[compno] & HAD_QCC)) memcpy(q + compno, &tmp, sizeof(tmp)); return 0; } /* Get quantization parameters for a component in the whole image * on in a particular tile. */ static int get_qcc(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q, uint8_t *properties) { int compno; if (bytestream2_get_bytes_left(&s->g) < 1) return AVERROR_INVALIDDATA; compno = bytestream2_get_byteu(&s->g); if (compno >= s->ncomponents) { av_log(s->avctx, AV_LOG_ERROR, "Invalid compno %d. There are %d components in the image.\n", compno, s->ncomponents); return AVERROR_INVALIDDATA; } properties[compno] |= HAD_QCC; return get_qcx(s, n - 1, q + compno); } /* Get start of tile segment. */ static int get_sot(Jpeg2000DecoderContext *s, int n) { Jpeg2000TilePart *tp; uint16_t Isot; uint32_t Psot; uint8_t TPsot; if (bytestream2_get_bytes_left(&s->g) < 8) return AVERROR_INVALIDDATA; s->curtileno = 0; Isot = bytestream2_get_be16u(&s->g); // Isot if (Isot >= s->numXtiles * s->numYtiles) return AVERROR_INVALIDDATA; s->curtileno = Isot; Psot = bytestream2_get_be32u(&s->g); // Psot TPsot = bytestream2_get_byteu(&s->g); // TPsot /* Read TNSot but not used */ bytestream2_get_byteu(&s->g); // TNsot if (Psot > bytestream2_get_bytes_left(&s->g) + n + 2) { av_log(s->avctx, AV_LOG_ERROR, "Psot %d too big\n", Psot); return AVERROR_INVALIDDATA; } if (TPsot >= FF_ARRAY_ELEMS(s->tile[Isot].tile_part)) { avpriv_request_sample(s->avctx, "Support for %d components", TPsot); return AVERROR_PATCHWELCOME; } s->tile[Isot].tp_idx = TPsot; tp = s->tile[Isot].tile_part + TPsot; tp->tile_index = Isot; tp->tp_end = s->g.buffer + Psot - n - 2; if (!TPsot) { Jpeg2000Tile *tile = s->tile + s->curtileno; /* copy defaults */ memcpy(tile->codsty, s->codsty, s->ncomponents * sizeof(Jpeg2000CodingStyle)); memcpy(tile->qntsty, s->qntsty, s->ncomponents * sizeof(Jpeg2000QuantStyle)); } return 0; } /* Tile-part lengths: see ISO 15444-1:2002, section A.7.1 * Used to know the number of tile parts and lengths. * There may be multiple TLMs in the header. * TODO: The function is not used for tile-parts management, nor anywhere else. * It can be useful to allocate memory for tile parts, before managing the SOT * markers. Parsing the TLM header is needed to increment the input header * buffer. * This marker is mandatory for DCI. */ static uint8_t get_tlm(Jpeg2000DecoderContext *s, int n) { uint8_t Stlm, ST, SP, tile_tlm, i; bytestream2_get_byte(&s->g); /* Ztlm: skipped */ Stlm = bytestream2_get_byte(&s->g); // too complex ? ST = ((Stlm >> 4) & 0x01) + ((Stlm >> 4) & 0x02); ST = (Stlm >> 4) & 0x03; // TODO: Manage case of ST = 0b11 --> raise error SP = (Stlm >> 6) & 0x01; tile_tlm = (n - 4) / ((SP + 1) * 2 + ST); for (i = 0; i < tile_tlm; i++) { switch (ST) { case 0: break; case 1: bytestream2_get_byte(&s->g); break; case 2: bytestream2_get_be16(&s->g); break; case 3: bytestream2_get_be32(&s->g); break; } if (SP == 0) { bytestream2_get_be16(&s->g); } else { bytestream2_get_be32(&s->g); } } return 0; } static int init_tile(Jpeg2000DecoderContext *s, int tileno) { int compno; int tilex = tileno % s->numXtiles; int tiley = tileno / s->numXtiles; Jpeg2000Tile *tile = s->tile + tileno; if (!tile->comp) return AVERROR(ENOMEM); for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000Component *comp = tile->comp + compno; Jpeg2000CodingStyle *codsty = tile->codsty + compno; Jpeg2000QuantStyle *qntsty = tile->qntsty + compno; int ret; // global bandno comp->coord_o[0][0] = FFMAX(tilex * s->tile_width + s->tile_offset_x, s->image_offset_x); comp->coord_o[0][1] = FFMIN((tilex + 1) * s->tile_width + s->tile_offset_x, s->width); comp->coord_o[1][0] = FFMAX(tiley * s->tile_height + s->tile_offset_y, s->image_offset_y); comp->coord_o[1][1] = FFMIN((tiley + 1) * s->tile_height + s->tile_offset_y, s->height); comp->coord[0][0] = ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], s->reduction_factor); comp->coord[0][1] = ff_jpeg2000_ceildivpow2(comp->coord_o[0][1], s->reduction_factor); comp->coord[1][0] = ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], s->reduction_factor); comp->coord[1][1] = ff_jpeg2000_ceildivpow2(comp->coord_o[1][1], s->reduction_factor); if (ret = ff_jpeg2000_init_component(comp, codsty, qntsty, s->cbps[compno], s->cdx[compno], s->cdy[compno], s->avctx)) return ret; } return 0; } /* Read the number of coding passes. */ static int getnpasses(Jpeg2000DecoderContext *s) { int num; if (!get_bits(s, 1)) return 1; if (!get_bits(s, 1)) return 2; if ((num = get_bits(s, 2)) != 3) return num < 0 ? num : 3 + num; if ((num = get_bits(s, 5)) != 31) return num < 0 ? num : 6 + num; num = get_bits(s, 7); return num < 0 ? num : 37 + num; } static int getlblockinc(Jpeg2000DecoderContext *s) { int res = 0, ret; while (ret = get_bits(s, 1)) { if (ret < 0) return ret; res++; } return res; } static int jpeg2000_decode_packet(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *codsty, Jpeg2000ResLevel *rlevel, int precno, int layno, uint8_t *expn, int numgbits) { int bandno, cblkno, ret, nb_code_blocks; if (!(ret = get_bits(s, 1))) { jpeg2000_flush(s); return 0; } else if (ret < 0) return ret; for (bandno = 0; bandno < rlevel->nbands; bandno++) { Jpeg2000Band *band = rlevel->band + bandno; Jpeg2000Prec *prec = band->prec + precno; if (band->coord[0][0] == band->coord[0][1] || band->coord[1][0] == band->coord[1][1]) continue; nb_code_blocks = prec->nb_codeblocks_height * prec->nb_codeblocks_width; for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) { Jpeg2000Cblk *cblk = prec->cblk + cblkno; int incl, newpasses, llen; if (cblk->npasses) incl = get_bits(s, 1); else incl = tag_tree_decode(s, prec->cblkincl + cblkno, layno + 1) == layno; if (!incl) continue; else if (incl < 0) return incl; if (!cblk->npasses) { int v = expn[bandno] + numgbits - 1 - tag_tree_decode(s, prec->zerobits + cblkno, 100); if (v < 0) { av_log(s->avctx, AV_LOG_ERROR, "nonzerobits %d invalid\n", v); return AVERROR_INVALIDDATA; } cblk->nonzerobits = v; } if ((newpasses = getnpasses(s)) < 0) return newpasses; if ((llen = getlblockinc(s)) < 0) return llen; cblk->lblock += llen; if ((ret = get_bits(s, av_log2(newpasses) + cblk->lblock)) < 0) return ret; if (ret > sizeof(cblk->data)) { avpriv_request_sample(s->avctx, "Block with lengthinc greater than %zu", sizeof(cblk->data)); return AVERROR_PATCHWELCOME; } cblk->lengthinc = ret; cblk->npasses += newpasses; } } jpeg2000_flush(s); if (codsty->csty & JPEG2000_CSTY_EPH) { if (bytestream2_peek_be16(&s->g) == JPEG2000_EPH) bytestream2_skip(&s->g, 2); else av_log(s->avctx, AV_LOG_ERROR, "EPH marker not found.\n"); } for (bandno = 0; bandno < rlevel->nbands; bandno++) { Jpeg2000Band *band = rlevel->band + bandno; Jpeg2000Prec *prec = band->prec + precno; nb_code_blocks = prec->nb_codeblocks_height * prec->nb_codeblocks_width; for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) { Jpeg2000Cblk *cblk = prec->cblk + cblkno; if ( bytestream2_get_bytes_left(&s->g) < cblk->lengthinc || sizeof(cblk->data) < cblk->length + cblk->lengthinc + 2 ) { av_log(s->avctx, AV_LOG_ERROR, "Block length %d or lengthinc %d is too large\n", cblk->length, cblk->lengthinc); return AVERROR_INVALIDDATA; } bytestream2_get_bufferu(&s->g, cblk->data + cblk->length, cblk->lengthinc); cblk->length += cblk->lengthinc; cblk->lengthinc = 0; } } return 0; } static int jpeg2000_decode_packets(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile) { int ret = 0; int layno, reslevelno, compno, precno, ok_reslevel; int x, y; s->bit_index = 8; switch (tile->codsty[0].prog_order) { case JPEG2000_PGOD_RLCP: avpriv_request_sample(s->avctx, "Progression order RLCP"); case JPEG2000_PGOD_LRCP: for (layno = 0; layno < tile->codsty[0].nlayers; layno++) { ok_reslevel = 1; for (reslevelno = 0; ok_reslevel; reslevelno++) { ok_reslevel = 0; for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000CodingStyle *codsty = tile->codsty + compno; Jpeg2000QuantStyle *qntsty = tile->qntsty + compno; if (reslevelno < codsty->nreslevels) { Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel + reslevelno; ok_reslevel = 1; for (precno = 0; precno < rlevel->num_precincts_x * rlevel->num_precincts_y; precno++) if ((ret = jpeg2000_decode_packet(s, codsty, rlevel, precno, layno, qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0), qntsty->nguardbits)) < 0) return ret; } } } } break; case JPEG2000_PGOD_CPRL: for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000CodingStyle *codsty = tile->codsty + compno; Jpeg2000QuantStyle *qntsty = tile->qntsty + compno; /* Set bit stream buffer address according to tile-part. * For DCinema one tile-part per component, so can be * indexed by component. */ s->g = tile->tile_part[compno].tpg; /* Position loop (y axis) * TODO: Automate computing of step 256. * Fixed here, but to be computed before entering here. */ for (y = 0; y < s->height; y += 256) { /* Position loop (y axis) * TODO: automate computing of step 256. * Fixed here, but to be computed before entering here. */ for (x = 0; x < s->width; x += 256) { for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) { uint16_t prcx, prcy; uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; // ==> N_L - r Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel + reslevelno; if (!((y % (1 << (rlevel->log2_prec_height + reducedresno)) == 0) || (y == 0))) // TODO: 2nd condition simplified as try0 always =0 for dcinema continue; if (!((x % (1 << (rlevel->log2_prec_width + reducedresno)) == 0) || (x == 0))) // TODO: 2nd condition simplified as try0 always =0 for dcinema continue; // check if a precinct exists prcx = ff_jpeg2000_ceildivpow2(x, reducedresno) >> rlevel->log2_prec_width; prcy = ff_jpeg2000_ceildivpow2(y, reducedresno) >> rlevel->log2_prec_height; precno = prcx + rlevel->num_precincts_x * prcy; for (layno = 0; layno < tile->codsty[0].nlayers; layno++) { if ((ret = jpeg2000_decode_packet(s, codsty, rlevel, precno, layno, qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0), qntsty->nguardbits)) < 0) return ret; } } } } } break; case JPEG2000_PGOD_RPCL: avpriv_request_sample(s->avctx, "Progression order RPCL"); ret = AVERROR_PATCHWELCOME; break; case JPEG2000_PGOD_PCRL: avpriv_request_sample(s->avctx, "Progression order PCRL"); ret = AVERROR_PATCHWELCOME; break; default: break; } /* EOC marker reached */ bytestream2_skip(&s->g, 2); return ret; } /* TIER-1 routines */ static void decode_sigpass(Jpeg2000T1Context *t1, int width, int height, int bpno, int bandno, int bpass_csty_symbol, int vert_causal_ctx_csty_symbol) { int mask = 3 << (bpno - 1), y0, x, y; for (y0 = 0; y0 < height; y0 += 4) for (x = 0; x < width; x++) for (y = y0; y < height && y < y0 + 4; y++) { if ((t1->flags[y+1][x+1] & JPEG2000_T1_SIG_NB) && !(t1->flags[y+1][x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))) { int flags_mask = -1; if (vert_causal_ctx_csty_symbol && y == y0 + 3) flags_mask &= ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | JPEG2000_T1_SIG_SE); if (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ff_jpeg2000_getsigctxno(t1->flags[y+1][x+1] & flags_mask, bandno))) { int xorbit, ctxno = ff_jpeg2000_getsgnctxno(t1->flags[y+1][x+1], &xorbit); if (bpass_csty_symbol) t1->data[y][x] = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ? -mask : mask; else t1->data[y][x] = (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ^ xorbit) ? -mask : mask; ff_jpeg2000_set_significance(t1, x, y, t1->data[y][x] < 0); } t1->flags[y + 1][x + 1] |= JPEG2000_T1_VIS; } } } static void decode_refpass(Jpeg2000T1Context *t1, int width, int height, int bpno) { int phalf, nhalf; int y0, x, y; phalf = 1 << (bpno - 1); nhalf = -phalf; for (y0 = 0; y0 < height; y0 += 4) for (x = 0; x < width; x++) for (y = y0; y < height && y < y0 + 4; y++) if ((t1->flags[y + 1][x + 1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS)) == JPEG2000_T1_SIG) { int ctxno = ff_jpeg2000_getrefctxno(t1->flags[y + 1][x + 1]); int r = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ? phalf : nhalf; t1->data[y][x] += t1->data[y][x] < 0 ? -r : r; t1->flags[y + 1][x + 1] |= JPEG2000_T1_REF; } } static void decode_clnpass(Jpeg2000DecoderContext *s, Jpeg2000T1Context *t1, int width, int height, int bpno, int bandno, int seg_symbols, int vert_causal_ctx_csty_symbol) { int mask = 3 << (bpno - 1), y0, x, y, runlen, dec; for (y0 = 0; y0 < height; y0 += 4) { for (x = 0; x < width; x++) { if (y0 + 3 < height && !((t1->flags[y0 + 1][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) || (t1->flags[y0 + 2][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) || (t1->flags[y0 + 3][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) || (t1->flags[y0 + 4][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)))) { if (!ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_RL)) continue; runlen = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI); runlen = (runlen << 1) | ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI); dec = 1; } else { runlen = 0; dec = 0; } for (y = y0 + runlen; y < y0 + 4 && y < height; y++) { if (!dec) { if (!(t1->flags[y+1][x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))) { int flags_mask = -1; if (vert_causal_ctx_csty_symbol && y == y0 + 3) flags_mask &= ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | JPEG2000_T1_SIG_SE); dec = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ff_jpeg2000_getsigctxno(t1->flags[y+1][x+1] & flags_mask, bandno)); } } if (dec) { int xorbit; int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[y + 1][x + 1], &xorbit); t1->data[y][x] = (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ^ xorbit) ? -mask : mask; ff_jpeg2000_set_significance(t1, x, y, t1->data[y][x] < 0); } dec = 0; t1->flags[y + 1][x + 1] &= ~JPEG2000_T1_VIS; } } } if (seg_symbols) { int val; val = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI); val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI); val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI); val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI); if (val != 0xa) av_log(s->avctx, AV_LOG_ERROR, "Segmentation symbol value incorrect\n"); } } static int decode_cblk(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *codsty, Jpeg2000T1Context *t1, Jpeg2000Cblk *cblk, int width, int height, int bandpos) { int passno = cblk->npasses, pass_t = 2, bpno = cblk->nonzerobits - 1, y; int clnpass_cnt = 0; int bpass_csty_symbol = codsty->cblk_style & JPEG2000_CBLK_BYPASS; int vert_causal_ctx_csty_symbol = codsty->cblk_style & JPEG2000_CBLK_VSC; av_assert0(width <= JPEG2000_MAX_CBLKW); av_assert0(height <= JPEG2000_MAX_CBLKH); for (y = 0; y < height; y++) memset(t1->data[y], 0, width * sizeof(**t1->data)); /* If code-block contains no compressed data: nothing to do. */ if (!cblk->length) return 0; for (y = 0; y < height + 2; y++) memset(t1->flags[y], 0, (width + 2) * sizeof(**t1->flags)); cblk->data[cblk->length] = 0xff; cblk->data[cblk->length+1] = 0xff; ff_mqc_initdec(&t1->mqc, cblk->data); while (passno--) { switch(pass_t) { case 0: decode_sigpass(t1, width, height, bpno + 1, bandpos, bpass_csty_symbol && (clnpass_cnt >= 4), vert_causal_ctx_csty_symbol); break; case 1: decode_refpass(t1, width, height, bpno + 1); if (bpass_csty_symbol && clnpass_cnt >= 4) ff_mqc_initdec(&t1->mqc, cblk->data); break; case 2: decode_clnpass(s, t1, width, height, bpno + 1, bandpos, codsty->cblk_style & JPEG2000_CBLK_SEGSYM, vert_causal_ctx_csty_symbol); clnpass_cnt = clnpass_cnt + 1; if (bpass_csty_symbol && clnpass_cnt >= 4) ff_mqc_initdec(&t1->mqc, cblk->data); break; } pass_t++; if (pass_t == 3) { bpno--; pass_t = 0; } } return 0; } /* TODO: Verify dequantization for lossless case * comp->data can be float or int * band->stepsize can be float or int * depending on the type of DWT transformation. * see ISO/IEC 15444-1:2002 A.6.1 */ /* Float dequantization of a codeblock.*/ static void dequantization_float(int x, int y, Jpeg2000Cblk *cblk, Jpeg2000Component *comp, Jpeg2000T1Context *t1, Jpeg2000Band *band) { int i, j; int w = cblk->coord[0][1] - cblk->coord[0][0]; for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j) { float *datap = &comp->f_data[(comp->coord[0][1] - comp->coord[0][0]) * (y + j) + x]; int *src = t1->data[j]; for (i = 0; i < w; ++i) datap[i] = src[i] * band->f_stepsize; } } /* Integer dequantization of a codeblock.*/ static void dequantization_int(int x, int y, Jpeg2000Cblk *cblk, Jpeg2000Component *comp, Jpeg2000T1Context *t1, Jpeg2000Band *band) { int i, j; int w = cblk->coord[0][1] - cblk->coord[0][0]; for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j) { int32_t *datap = &comp->i_data[(comp->coord[0][1] - comp->coord[0][0]) * (y + j) + x]; int *src = t1->data[j]; for (i = 0; i < w; ++i) datap[i] = (src[i] * band->i_stepsize + (1 << 14)) >> 15; } } /* Inverse ICT parameters in float and integer. * int value = (float value) * (1<<16) */ static const float f_ict_params[4] = { 1.402f, 0.34413f, 0.71414f, 1.772f }; static const int i_ict_params[4] = { 91881, 22553, 46802, 116130 }; static void mct_decode(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile) { int i, csize = 1; int32_t *src[3], i0, i1, i2; float *srcf[3], i0f, i1f, i2f; for (i = 1; i < 3; i++) if (tile->codsty[0].transform != tile->codsty[i].transform) { av_log(s->avctx, AV_LOG_ERROR, "Transforms mismatch, MCT not supported\n"); return; } for (i = 0; i < 3; i++) if (tile->codsty[0].transform == FF_DWT97) srcf[i] = tile->comp[i].f_data; else src [i] = tile->comp[i].i_data; for (i = 0; i < 2; i++) csize *= tile->comp[0].coord[i][1] - tile->comp[0].coord[i][0]; switch (tile->codsty[0].transform) { case FF_DWT97: for (i = 0; i < csize; i++) { i0f = *srcf[0] + (f_ict_params[0] * *srcf[2]); i1f = *srcf[0] - (f_ict_params[1] * *srcf[1]) - (f_ict_params[2] * *srcf[2]); i2f = *srcf[0] + (f_ict_params[3] * *srcf[1]); *srcf[0]++ = i0f; *srcf[1]++ = i1f; *srcf[2]++ = i2f; } break; case FF_DWT97_INT: for (i = 0; i < csize; i++) { i0 = *src[0] + (((i_ict_params[0] * *src[2]) + (1 << 15)) >> 16); i1 = *src[0] - (((i_ict_params[1] * *src[1]) + (1 << 15)) >> 16) - (((i_ict_params[2] * *src[2]) + (1 << 15)) >> 16); i2 = *src[0] + (((i_ict_params[3] * *src[1]) + (1 << 15)) >> 16); *src[0]++ = i0; *src[1]++ = i1; *src[2]++ = i2; } break; case FF_DWT53: for (i = 0; i < csize; i++) { i1 = *src[0] - (*src[2] + *src[1] >> 2); i0 = i1 + *src[2]; i2 = i1 + *src[1]; *src[0]++ = i0; *src[1]++ = i1; *src[2]++ = i2; } break; } } static int jpeg2000_decode_tile(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile, AVFrame *picture) { int compno, reslevelno, bandno; int x, y; uint8_t *line; Jpeg2000T1Context t1; /* Loop on tile components */ for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000Component *comp = tile->comp + compno; Jpeg2000CodingStyle *codsty = tile->codsty + compno; /* Loop on resolution levels */ for (reslevelno = 0; reslevelno < codsty->nreslevels2decode; reslevelno++) { Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno; /* Loop on bands */ for (bandno = 0; bandno < rlevel->nbands; bandno++) { int nb_precincts, precno; Jpeg2000Band *band = rlevel->band + bandno; int cblkno = 0, bandpos; bandpos = bandno + (reslevelno > 0); if (band->coord[0][0] == band->coord[0][1] || band->coord[1][0] == band->coord[1][1]) continue; nb_precincts = rlevel->num_precincts_x * rlevel->num_precincts_y; /* Loop on precincts */ for (precno = 0; precno < nb_precincts; precno++) { Jpeg2000Prec *prec = band->prec + precno; /* Loop on codeblocks */ for (cblkno = 0; cblkno < prec->nb_codeblocks_width * prec->nb_codeblocks_height; cblkno++) { int x, y; Jpeg2000Cblk *cblk = prec->cblk + cblkno; decode_cblk(s, codsty, &t1, cblk, cblk->coord[0][1] - cblk->coord[0][0], cblk->coord[1][1] - cblk->coord[1][0], bandpos); x = cblk->coord[0][0]; y = cblk->coord[1][0]; if (codsty->transform == FF_DWT97) dequantization_float(x, y, cblk, comp, &t1, band); else dequantization_int(x, y, cblk, comp, &t1, band); } /* end cblk */ } /*end prec */ } /* end band */ } /* end reslevel */ /* inverse DWT */ ff_dwt_decode(&comp->dwt, codsty->transform == FF_DWT97 ? (void*)comp->f_data : (void*)comp->i_data); } /*end comp */ /* inverse MCT transformation */ if (tile->codsty[0].mct) mct_decode(s, tile); if (s->cdef[0] < 0) { for (x = 0; x < s->ncomponents; x++) s->cdef[x] = x + 1; if ((s->ncomponents & 1) == 0) s->cdef[s->ncomponents-1] = 0; } if (s->precision <= 8) { for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000Component *comp = tile->comp + compno; Jpeg2000CodingStyle *codsty = tile->codsty + compno; float *datap = comp->f_data; int32_t *i_datap = comp->i_data; int cbps = s->cbps[compno]; int w = tile->comp[compno].coord[0][1] - s->image_offset_x; int planar = !!picture->data[2]; int pixelsize = planar ? 1 : s->ncomponents; int plane = 0; if (planar) plane = s->cdef[compno] ? s->cdef[compno]-1 : (s->ncomponents-1); y = tile->comp[compno].coord[1][0] - s->image_offset_y; line = picture->data[plane] + y * picture->linesize[plane]; for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) { uint8_t *dst; x = tile->comp[compno].coord[0][0] - s->image_offset_x; dst = line + x * pixelsize + compno*!planar; if (codsty->transform == FF_DWT97) { for (; x < w; x += s->cdx[compno]) { int val = lrintf(*datap) + (1 << (cbps - 1)); /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */ val = av_clip(val, 0, (1 << cbps) - 1); *dst = val << (8 - cbps); datap++; dst += pixelsize; } } else { for (; x < w; x += s->cdx[compno]) { int val = *i_datap + (1 << (cbps - 1)); /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */ val = av_clip(val, 0, (1 << cbps) - 1); *dst = val << (8 - cbps); i_datap++; dst += pixelsize; } } line += picture->linesize[plane]; } } } else { for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000Component *comp = tile->comp + compno; Jpeg2000CodingStyle *codsty = tile->codsty + compno; float *datap = comp->f_data; int32_t *i_datap = comp->i_data; uint16_t *linel; int cbps = s->cbps[compno]; int w = tile->comp[compno].coord[0][1] - s->image_offset_x; int planar = !!picture->data[2]; int pixelsize = planar ? 1 : s->ncomponents; int plane = 0; if (planar) plane = s->cdef[compno] ? s->cdef[compno]-1 : (s->ncomponents-1); y = tile->comp[compno].coord[1][0] - s->image_offset_y; linel = (uint16_t *)picture->data[plane] + y * (picture->linesize[plane] >> 1); for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) { uint16_t *dst; x = tile->comp[compno].coord[0][0] - s->image_offset_x; dst = linel + (x * pixelsize + compno*!planar); if (codsty->transform == FF_DWT97) { for (; x < w; x += s-> cdx[compno]) { int val = lrintf(*datap) + (1 << (cbps - 1)); /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */ val = av_clip(val, 0, (1 << cbps) - 1); /* align 12 bit values in little-endian mode */ *dst = val << (16 - cbps); datap++; dst += pixelsize; } } else { for (; x < w; x += s-> cdx[compno]) { int val = *i_datap + (1 << (cbps - 1)); /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */ val = av_clip(val, 0, (1 << cbps) - 1); /* align 12 bit values in little-endian mode */ *dst = val << (16 - cbps); i_datap++; dst += pixelsize; } } linel += picture->linesize[plane] >> 1; } } } return 0; } static void jpeg2000_dec_cleanup(Jpeg2000DecoderContext *s) { int tileno, compno; for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) { if (s->tile[tileno].comp) { for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000Component *comp = s->tile[tileno].comp + compno; Jpeg2000CodingStyle *codsty = s->tile[tileno].codsty + compno; ff_jpeg2000_cleanup(comp, codsty); } av_freep(&s->tile[tileno].comp); } } av_freep(&s->tile); memset(s->codsty, 0, sizeof(s->codsty)); memset(s->qntsty, 0, sizeof(s->qntsty)); s->numXtiles = s->numYtiles = 0; } static int jpeg2000_read_main_headers(Jpeg2000DecoderContext *s) { Jpeg2000CodingStyle *codsty = s->codsty; Jpeg2000QuantStyle *qntsty = s->qntsty; uint8_t *properties = s->properties; for (;;) { int len, ret = 0; uint16_t marker; int oldpos; if (bytestream2_get_bytes_left(&s->g) < 2) { av_log(s->avctx, AV_LOG_ERROR, "Missing EOC\n"); break; } marker = bytestream2_get_be16u(&s->g); oldpos = bytestream2_tell(&s->g); if (marker == JPEG2000_SOD) { Jpeg2000Tile *tile; Jpeg2000TilePart *tp; if (!s->tile) { av_log(s->avctx, AV_LOG_ERROR, "Missing SIZ\n"); return AVERROR_INVALIDDATA; } if (s->curtileno < 0) { av_log(s->avctx, AV_LOG_ERROR, "Missing SOT\n"); return AVERROR_INVALIDDATA; } tile = s->tile + s->curtileno; tp = tile->tile_part + tile->tp_idx; if (tp->tp_end < s->g.buffer) { av_log(s->avctx, AV_LOG_ERROR, "Invalid tpend\n"); return AVERROR_INVALIDDATA; } bytestream2_init(&tp->tpg, s->g.buffer, tp->tp_end - s->g.buffer); bytestream2_skip(&s->g, tp->tp_end - s->g.buffer); continue; } if (marker == JPEG2000_EOC) break; len = bytestream2_get_be16(&s->g); if (len < 2 || bytestream2_get_bytes_left(&s->g) < len - 2) return AVERROR_INVALIDDATA; switch (marker) { case JPEG2000_SIZ: ret = get_siz(s); if (!s->tile) s->numXtiles = s->numYtiles = 0; break; case JPEG2000_COC: ret = get_coc(s, codsty, properties); break; case JPEG2000_COD: ret = get_cod(s, codsty, properties); break; case JPEG2000_QCC: ret = get_qcc(s, len, qntsty, properties); break; case JPEG2000_QCD: ret = get_qcd(s, len, qntsty, properties); break; case JPEG2000_SOT: if (!(ret = get_sot(s, len))) { av_assert1(s->curtileno >= 0); codsty = s->tile[s->curtileno].codsty; qntsty = s->tile[s->curtileno].qntsty; properties = s->tile[s->curtileno].properties; } break; case JPEG2000_COM: // the comment is ignored bytestream2_skip(&s->g, len - 2); break; case JPEG2000_TLM: // Tile-part lengths ret = get_tlm(s, len); break; default: av_log(s->avctx, AV_LOG_ERROR, "unsupported marker 0x%.4X at pos 0x%X\n", marker, bytestream2_tell(&s->g) - 4); bytestream2_skip(&s->g, len - 2); break; } if (bytestream2_tell(&s->g) - oldpos != len || ret) { av_log(s->avctx, AV_LOG_ERROR, "error during processing marker segment %.4x\n", marker); return ret ? ret : -1; } } return 0; } /* Read bit stream packets --> T2 operation. */ static int jpeg2000_read_bitstream_packets(Jpeg2000DecoderContext *s) { int ret = 0; int tileno; for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) { Jpeg2000Tile *tile = s->tile + tileno; if (ret = init_tile(s, tileno)) return ret; s->g = tile->tile_part[0].tpg; if (ret = jpeg2000_decode_packets(s, tile)) return ret; } return 0; } static int jp2_find_codestream(Jpeg2000DecoderContext *s) { uint32_t atom_size, atom, atom_end; int search_range = 10; while (search_range && bytestream2_get_bytes_left(&s->g) >= 8) { atom_size = bytestream2_get_be32u(&s->g); atom = bytestream2_get_be32u(&s->g); atom_end = bytestream2_tell(&s->g) + atom_size - 8; if (atom == JP2_CODESTREAM) return 1; if (bytestream2_get_bytes_left(&s->g) < atom_size || atom_end < atom_size) return 0; if (atom == JP2_HEADER && atom_size >= 16) { uint32_t atom2_size, atom2, atom2_end; do { atom2_size = bytestream2_get_be32u(&s->g); atom2 = bytestream2_get_be32u(&s->g); atom2_end = bytestream2_tell(&s->g) + atom2_size - 8; if (atom2_size < 8 || atom2_end > atom_end || atom2_end < atom2_size) break; if (atom2 == JP2_CODESTREAM) { return 1; } else if (atom2 == MKBETAG('c','o','l','r') && atom2_size >= 7) { int method = bytestream2_get_byteu(&s->g); bytestream2_skipu(&s->g, 2); if (method == 1) { s->colour_space = bytestream2_get_be32u(&s->g); } } else if (atom2 == MKBETAG('p','c','l','r') && atom2_size >= 6) { int i, size, colour_count, colour_channels, colour_depth[3]; uint32_t r, g, b; colour_count = bytestream2_get_be16u(&s->g); colour_channels = bytestream2_get_byteu(&s->g); // FIXME: Do not ignore channel_sign colour_depth[0] = (bytestream2_get_byteu(&s->g) & 0x7f) + 1; colour_depth[1] = (bytestream2_get_byteu(&s->g) & 0x7f) + 1; colour_depth[2] = (bytestream2_get_byteu(&s->g) & 0x7f) + 1; size = (colour_depth[0] + 7 >> 3) * colour_count + (colour_depth[1] + 7 >> 3) * colour_count + (colour_depth[2] + 7 >> 3) * colour_count; if (colour_count > 256 || colour_channels != 3 || colour_depth[0] > 16 || colour_depth[1] > 16 || colour_depth[2] > 16 || atom2_size < size) { avpriv_request_sample(s->avctx, "Unknown palette"); bytestream2_seek(&s->g, atom2_end, SEEK_SET); continue; } s->pal8 = 1; for (i = 0; i < colour_count; i++) { if (colour_depth[0] <= 8) { r = bytestream2_get_byteu(&s->g) << 8 - colour_depth[0]; r |= r >> colour_depth[0]; } else { r = bytestream2_get_be16u(&s->g) >> colour_depth[0] - 8; } if (colour_depth[1] <= 8) { g = bytestream2_get_byteu(&s->g) << 8 - colour_depth[1]; r |= r >> colour_depth[1]; } else { g = bytestream2_get_be16u(&s->g) >> colour_depth[1] - 8; } if (colour_depth[2] <= 8) { b = bytestream2_get_byteu(&s->g) << 8 - colour_depth[2]; r |= r >> colour_depth[2]; } else { b = bytestream2_get_be16u(&s->g) >> colour_depth[2] - 8; } s->palette[i] = 0xffu << 24 | r << 16 | g << 8 | b; } } else if (atom2 == MKBETAG('c','d','e','f') && atom2_size >= 2) { int n = bytestream2_get_be16u(&s->g); for (; n>0; n--) { int cn = bytestream2_get_be16(&s->g); int av_unused typ = bytestream2_get_be16(&s->g); int asoc = bytestream2_get_be16(&s->g); if (cn < 4 || asoc < 4) s->cdef[cn] = asoc; } } bytestream2_seek(&s->g, atom2_end, SEEK_SET); } while (atom_end - atom2_end >= 8); } else { search_range--; } bytestream2_seek(&s->g, atom_end, SEEK_SET); } return 0; } static int jpeg2000_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { Jpeg2000DecoderContext *s = avctx->priv_data; ThreadFrame frame = { .f = data }; AVFrame *picture = data; int tileno, ret; s->avctx = avctx; bytestream2_init(&s->g, avpkt->data, avpkt->size); s->curtileno = -1; memset(s->cdef, -1, sizeof(s->cdef)); if (bytestream2_get_bytes_left(&s->g) < 2) { ret = AVERROR_INVALIDDATA; goto end; } // check if the image is in jp2 format if (bytestream2_get_bytes_left(&s->g) >= 12 && (bytestream2_get_be32u(&s->g) == 12) && (bytestream2_get_be32u(&s->g) == JP2_SIG_TYPE) && (bytestream2_get_be32u(&s->g) == JP2_SIG_VALUE)) { if (!jp2_find_codestream(s)) { av_log(avctx, AV_LOG_ERROR, "Could not find Jpeg2000 codestream atom.\n"); ret = AVERROR_INVALIDDATA; goto end; } } else { bytestream2_seek(&s->g, 0, SEEK_SET); } while (bytestream2_get_bytes_left(&s->g) >= 3 && bytestream2_peek_be16(&s->g) != JPEG2000_SOC) bytestream2_skip(&s->g, 1); if (bytestream2_get_be16u(&s->g) != JPEG2000_SOC) { av_log(avctx, AV_LOG_ERROR, "SOC marker not present\n"); ret = AVERROR_INVALIDDATA; goto end; } if (ret = jpeg2000_read_main_headers(s)) goto end; /* get picture buffer */ if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0) goto end; picture->pict_type = AV_PICTURE_TYPE_I; picture->key_frame = 1; if (ret = jpeg2000_read_bitstream_packets(s)) goto end; for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) if (ret = jpeg2000_decode_tile(s, s->tile + tileno, picture)) goto end; jpeg2000_dec_cleanup(s); *got_frame = 1; if (s->avctx->pix_fmt == AV_PIX_FMT_PAL8) memcpy(picture->data[1], s->palette, 256 * sizeof(uint32_t)); return bytestream2_tell(&s->g); end: jpeg2000_dec_cleanup(s); return ret; } static void jpeg2000_init_static_data(AVCodec *codec) { ff_jpeg2000_init_tier1_luts(); ff_mqc_init_context_tables(); } #define OFFSET(x) offsetof(Jpeg2000DecoderContext, x) #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM static const AVOption options[] = { { "lowres", "Lower the decoding resolution by a power of two", OFFSET(reduction_factor), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, JPEG2000_MAX_RESLEVELS - 1, VD }, { NULL }, }; static const AVProfile profiles[] = { { FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_0, "JPEG 2000 codestream restriction 0" }, { FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_1, "JPEG 2000 codestream restriction 1" }, { FF_PROFILE_JPEG2000_CSTREAM_NO_RESTRICTION, "JPEG 2000 no codestream restrictions" }, { FF_PROFILE_JPEG2000_DCINEMA_2K, "JPEG 2000 digital cinema 2K" }, { FF_PROFILE_JPEG2000_DCINEMA_4K, "JPEG 2000 digital cinema 4K" }, { FF_PROFILE_UNKNOWN }, }; static const AVClass jpeg2000_class = { .class_name = "jpeg2000", .item_name = av_default_item_name, .option = options, .version = LIBAVUTIL_VERSION_INT, }; AVCodec ff_jpeg2000_decoder = { .name = "jpeg2000", .long_name = NULL_IF_CONFIG_SMALL("JPEG 2000"), .type = AVMEDIA_TYPE_VIDEO, .id = AV_CODEC_ID_JPEG2000, .capabilities = CODEC_CAP_FRAME_THREADS, .priv_data_size = sizeof(Jpeg2000DecoderContext), .init_static_data = jpeg2000_init_static_data, .decode = jpeg2000_decode_frame, .priv_class = &jpeg2000_class, .max_lowres = 5, .profiles = NULL_IF_CONFIG_SMALL(profiles) };
./CrossVul/dataset_final_sorted/CWE-119/c/bad_5828_0
crossvul-cpp_data_good_934_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP N N M M % % P P NN N MM MM % % PPPP N N N M M M % % P N NN M M % % P N N M M % % % % % % Read/Write PBMPlus Portable Anymap Image Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/module.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/property.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" /* Typedef declarations. */ typedef struct _CommentInfo { char *comment; size_t extent; } CommentInfo; /* Forward declarations. */ static MagickBooleanType WritePNMImage(const ImageInfo *,Image *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P N M % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPNM() returns MagickTrue if the image format type, identified by the % magick string, is PNM. % % The format of the IsPNM method is: % % MagickBooleanType IsPNM(const unsigned char *magick,const size_t extent) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o extent: Specifies the extent of the magick string. % */ static MagickBooleanType IsPNM(const unsigned char *magick,const size_t extent) { if (extent < 2) return(MagickFalse); if ((*magick == (unsigned char) 'P') && ((magick[1] == '1') || (magick[1] == '2') || (magick[1] == '3') || (magick[1] == '4') || (magick[1] == '5') || (magick[1] == '6') || (magick[1] == '7') || (magick[1] == 'F') || (magick[1] == 'f'))) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P N M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPNMImage() reads a Portable Anymap image file and returns it. % It allocates the memory necessary for the new Image structure and returns % a pointer to the new image. % % The format of the ReadPNMImage method is: % % Image *ReadPNMImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static int PNMComment(Image *image,CommentInfo *comment_info, ExceptionInfo *exception) { int c; register char *p; /* Read comment. */ p=comment_info->comment+strlen(comment_info->comment); for (c='#'; (c != EOF) && (c != (int) '\n') && (c != (int) '\r'); p++) { if ((size_t) (p-comment_info->comment+1) >= comment_info->extent) { comment_info->extent<<=1; comment_info->comment=(char *) ResizeQuantumMemory( comment_info->comment,comment_info->extent, sizeof(*comment_info->comment)); if (comment_info->comment == (char *) NULL) return(-1); p=comment_info->comment+strlen(comment_info->comment); } c=ReadBlobByte(image); if (c != EOF) { *p=(char) c; *(p+1)='\0'; } } return(c); } static unsigned int PNMInteger(Image *image,CommentInfo *comment_info, const unsigned int base,ExceptionInfo *exception) { int c; unsigned int value; /* Skip any leading whitespace. */ do { c=ReadBlobByte(image); if (c == EOF) return(0); if (c == (int) '#') c=PNMComment(image,comment_info,exception); } while ((c == ' ') || (c == '\t') || (c == '\n') || (c == '\r')); if (base == 2) return((unsigned int) (c-(int) '0')); /* Evaluate number. */ value=0; while (isdigit(c) != 0) { if (value <= (unsigned int) (INT_MAX/10)) { value*=10; if (value <= (unsigned int) (INT_MAX-(c-(int) '0'))) value+=c-(int) '0'; } c=ReadBlobByte(image); if (c == EOF) return(0); } if (c == (int) '#') c=PNMComment(image,comment_info,exception); return(value); } static Image *ReadPNMImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define ThrowPNMException(exception,message) \ { \ if (comment_info.comment != (char *) NULL) \ comment_info.comment=DestroyString(comment_info.comment); \ ThrowReaderException((exception),(message)); \ } char format; CommentInfo comment_info; double quantum_scale; Image *image; MagickBooleanType status; QuantumAny max_value; QuantumInfo *quantum_info; QuantumType quantum_type; size_t depth, extent, packet_size; ssize_t count, row, y; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read PNM image. */ count=ReadBlob(image,1,(unsigned char *) &format); do { /* Initialize image structure. */ comment_info.comment=AcquireString(NULL); comment_info.extent=MagickPathExtent; if ((count != 1) || (format != 'P')) ThrowPNMException(CorruptImageError,"ImproperImageHeader"); max_value=1; quantum_type=RGBQuantum; quantum_scale=1.0; format=(char) ReadBlobByte(image); if (format != '7') { /* PBM, PGM, PPM, and PNM. */ image->columns=(size_t) PNMInteger(image,&comment_info,10,exception); image->rows=(size_t) PNMInteger(image,&comment_info,10,exception); if ((format == 'f') || (format == 'F')) { char scale[MagickPathExtent]; if (ReadBlobString(image,scale) != (char *) NULL) quantum_scale=StringToDouble(scale,(char **) NULL); } else { if ((format == '1') || (format == '4')) max_value=1; /* bitmap */ else max_value=(QuantumAny) PNMInteger(image,&comment_info,10, exception); } } else { char keyword[MagickPathExtent], value[MagickPathExtent]; int c; register char *p; /* PAM. */ for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image)) { while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); if (c == '#') { /* Comment. */ c=PNMComment(image,&comment_info,exception); c=ReadBlobByte(image); while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); } p=keyword; do { if ((size_t) (p-keyword) < (MagickPathExtent-1)) *p++=c; c=ReadBlobByte(image); } while (isalnum(c)); *p='\0'; if (LocaleCompare(keyword,"endhdr") == 0) break; while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); p=value; while (isalnum(c) || (c == '_')) { if ((size_t) (p-value) < (MagickPathExtent-1)) *p++=c; c=ReadBlobByte(image); } *p='\0'; /* Assign a value to the specified keyword. */ if (LocaleCompare(keyword,"depth") == 0) packet_size=StringToUnsignedLong(value); (void) packet_size; if (LocaleCompare(keyword,"height") == 0) image->rows=StringToUnsignedLong(value); if (LocaleCompare(keyword,"maxval") == 0) max_value=StringToUnsignedLong(value); if (LocaleCompare(keyword,"TUPLTYPE") == 0) { if (LocaleCompare(value,"BLACKANDWHITE") == 0) { (void) SetImageColorspace(image,GRAYColorspace,exception); quantum_type=GrayQuantum; } if (LocaleCompare(value,"BLACKANDWHITE_ALPHA") == 0) { (void) SetImageColorspace(image,GRAYColorspace,exception); image->alpha_trait=BlendPixelTrait; quantum_type=GrayAlphaQuantum; } if (LocaleCompare(value,"GRAYSCALE") == 0) { quantum_type=GrayQuantum; (void) SetImageColorspace(image,GRAYColorspace,exception); } if (LocaleCompare(value,"GRAYSCALE_ALPHA") == 0) { (void) SetImageColorspace(image,GRAYColorspace,exception); image->alpha_trait=BlendPixelTrait; quantum_type=GrayAlphaQuantum; } if (LocaleCompare(value,"RGB_ALPHA") == 0) { image->alpha_trait=BlendPixelTrait; quantum_type=RGBAQuantum; } if (LocaleCompare(value,"CMYK") == 0) { (void) SetImageColorspace(image,CMYKColorspace,exception); quantum_type=CMYKQuantum; } if (LocaleCompare(value,"CMYK_ALPHA") == 0) { (void) SetImageColorspace(image,CMYKColorspace,exception); image->alpha_trait=BlendPixelTrait; quantum_type=CMYKAQuantum; } } if (LocaleCompare(keyword,"width") == 0) image->columns=StringToUnsignedLong(value); } } if ((image->columns == 0) || (image->rows == 0)) ThrowPNMException(CorruptImageError,"NegativeOrZeroImageSize"); if ((max_value == 0) || (max_value > 4294967295UL)) ThrowPNMException(CorruptImageError,"ImproperImageHeader"); for (depth=1; GetQuantumRange(depth) < max_value; depth++) ; image->depth=depth; if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if ((MagickSizeType) (image->columns*image->rows/8) > GetBlobSize(image)) ThrowPNMException(CorruptImageError,"InsufficientImageDataInFile"); status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) { comment_info.comment=DestroyString(comment_info.comment); \ return(DestroyImageList(image)); } (void) ResetImagePixels(image,exception); /* Convert PNM pixels to runextent-encoded MIFF packets. */ row=0; y=0; switch (format) { case '1': { /* Convert PBM image to pixel packets. */ (void) SetImageColorspace(image,GRAYColorspace,exception); for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelGray(image,PNMInteger(image,&comment_info,2,exception) == 0 ? QuantumRange : 0,q); if (EOFBlob(image) != MagickFalse) break; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (EOFBlob(image) != MagickFalse) break; } image->type=BilevelType; break; } case '2': { Quantum intensity; /* Convert PGM image to pixel packets. */ (void) SetImageColorspace(image,GRAYColorspace,exception); for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { intensity=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10, exception),max_value); if (EOFBlob(image) != MagickFalse) break; SetPixelGray(image,intensity,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (EOFBlob(image) != MagickFalse) break; } image->type=GrayscaleType; break; } case '3': { /* Convert PNM image to pixel packets. */ for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Quantum pixel; pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10, exception),max_value); if (EOFBlob(image) != MagickFalse) break; SetPixelRed(image,pixel,q); pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10, exception),max_value); SetPixelGreen(image,pixel,q); pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10, exception),max_value); SetPixelBlue(image,pixel,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (EOFBlob(image) != MagickFalse) break; } break; } case '4': { /* Convert PBM raw image to pixel packets. */ (void) SetImageColorspace(image,GRAYColorspace,exception); quantum_type=GrayQuantum; if (image->storage_class == PseudoClass) quantum_type=IndexQuantum; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); SetQuantumMinIsWhite(quantum_info,MagickTrue); extent=GetQuantumExtent(image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register Quantum *magick_restrict q; ssize_t offset; size_t length; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception); if (q == (Quantum *) NULL) break; length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (length != extent) break; sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); SetQuantumImageType(image,quantum_type); break; } case '5': { /* Convert PGM raw image to pixel packets. */ (void) SetImageColorspace(image,GRAYColorspace,exception); quantum_type=GrayQuantum; extent=(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)* image->columns; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register const unsigned char *magick_restrict p; register ssize_t x; register Quantum *magick_restrict q; ssize_t offset; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception); if (q == (Quantum *) NULL) break; p=pixels; switch (image->depth) { case 8: case 16: case 32: { (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } default: { if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value),q); q+=GetPixelChannels(image); } } else if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value),q); q+=GetPixelChannels(image); } } else { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value),q); q+=GetPixelChannels(image); } } break; } } sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); SetQuantumImageType(image,quantum_type); break; } case '6': { /* Convert PNM raster image to pixel packets. */ quantum_type=RGBQuantum; extent=3*(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)* image->columns; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register const unsigned char *magick_restrict p; register ssize_t x; register Quantum *magick_restrict q; ssize_t offset; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception); if (q == (Quantum *) NULL) break; p=pixels; switch (image->depth) { case 8: { for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelBlue(image,ScaleCharToQuantum(*p++),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } break; } case 16: { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleShortToQuantum(pixel),q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleShortToQuantum(pixel),q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleShortToQuantum(pixel),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } break; } case 32: { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleLongToQuantum(pixel),q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleLongToQuantum(pixel),q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleLongToQuantum(pixel),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } break; } default: { if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushCharPixel(p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushCharPixel(p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } } else if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } } else { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } } break; } } sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '7': { size_t channels; /* Convert PAM raster image to pixel packets. */ switch (quantum_type) { case GrayQuantum: case GrayAlphaQuantum: { channels=1; break; } case CMYKQuantum: case CMYKAQuantum: { channels=4; break; } default: { channels=3; break; } } if (image->alpha_trait != UndefinedPixelTrait) channels++; extent=channels*(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)* image->columns; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register const unsigned char *magick_restrict p; register ssize_t x; register Quantum *magick_restrict q; ssize_t offset; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception); if (q == (Quantum *) NULL) break; p=pixels; switch (image->depth) { case 8: case 16: case 32: { (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } default: { switch (quantum_type) { case GrayQuantum: case GrayAlphaQuantum: { if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushCharPixel(p,&pixel); if (image->depth != 1) SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); else SetPixelAlpha(image,QuantumRange- ScaleAnyToQuantum(pixel,max_value),q); } q+=GetPixelChannels(image); } } else if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } else { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } break; } case CMYKQuantum: case CMYKAQuantum: { if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushCharPixel(p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushCharPixel(p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushCharPixel(p,&pixel); SetPixelBlack(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushCharPixel(p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } else if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlack(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } else { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlack(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } break; } default: { if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushCharPixel(p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushCharPixel(p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushCharPixel(p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } else if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } else { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } break; } } } } sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); SetQuantumImageType(image,quantum_type); break; } case 'F': case 'f': { /* Convert PFM raster image to pixel packets. */ if (format == 'f') (void) SetImageColorspace(image,GRAYColorspace,exception); quantum_type=format == 'f' ? GrayQuantum : RGBQuantum; image->endian=quantum_scale < 0.0 ? LSBEndian : MSBEndian; image->depth=32; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); status=SetQuantumDepth(image,quantum_info,32); if (status == MagickFalse) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); SetQuantumScale(quantum_info,(double) QuantumRange*fabs(quantum_scale)); extent=GetQuantumExtent(image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register Quantum *magick_restrict q; ssize_t offset; size_t length; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,(ssize_t) (image->rows-offset-1), image->columns,1,exception); if (q == (Quantum *) NULL) break; length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (length != extent) break; sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); SetQuantumImageType(image,quantum_type); break; } default: ThrowPNMException(CorruptImageError,"ImproperImageHeader"); } if (*comment_info.comment != '\0') (void) SetImageProperty(image,"comment",comment_info.comment,exception); comment_info.comment=DestroyString(comment_info.comment); if (y < (ssize_t) image->rows) ThrowPNMException(CorruptImageError,"UnableToReadImageData"); if (EOFBlob(image) != MagickFalse) { (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageError,"UnexpectedEndOfFile","`%s'",image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if ((format == '1') || (format == '2') || (format == '3')) do { /* Skip to end of line. */ count=ReadBlob(image,1,(unsigned char *) &format); if (count != 1) break; if (format == 'P') break; } while (format != '\n'); count=ReadBlob(image,1,(unsigned char *) &format); if ((count == 1) && (format == 'P')) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { status=MagickFalse; break; } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while ((count == 1) && (format == 'P')); (void) CloseBlob(image); if (status == MagickFalse) return(DestroyImageList(image)); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P N M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPNMImage() adds properties for the PNM image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterPNMImage method is: % % size_t RegisterPNMImage(void) % */ ModuleExport size_t RegisterPNMImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("PNM","PAM","Common 2-dimensional bitmap format"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->mime_type=ConstantString("image/x-portable-pixmap"); entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNM","PBM", "Portable bitmap format (black and white)"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->mime_type=ConstantString("image/x-portable-bitmap"); entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNM","PFM","Portable float format"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->flags|=CoderEndianSupportFlag; entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNM","PGM","Portable graymap format (gray scale)"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->mime_type=ConstantString("image/x-portable-greymap"); entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNM","PNM","Portable anymap"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->magick=(IsImageFormatHandler *) IsPNM; entry->mime_type=ConstantString("image/x-portable-pixmap"); entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNM","PPM","Portable pixmap format (color)"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->mime_type=ConstantString("image/x-portable-pixmap"); entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P N M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPNMImage() removes format registrations made by the % PNM module from the list of supported formats. % % The format of the UnregisterPNMImage method is: % % UnregisterPNMImage(void) % */ ModuleExport void UnregisterPNMImage(void) { (void) UnregisterMagickInfo("PAM"); (void) UnregisterMagickInfo("PBM"); (void) UnregisterMagickInfo("PGM"); (void) UnregisterMagickInfo("PNM"); (void) UnregisterMagickInfo("PPM"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P N M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePNMImage() writes an image to a file in the PNM rasterfile format. % % The format of the WritePNMImage method is: % % MagickBooleanType WritePNMImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WritePNMImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { char buffer[MagickPathExtent], format, magick[MagickPathExtent]; const char *value; MagickBooleanType status; MagickOffsetType scene; Quantum index; QuantumAny pixel; QuantumInfo *quantum_info; QuantumType quantum_type; register unsigned char *q; size_t extent, imageListLength, packet_size; ssize_t count, y; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); scene=0; imageListLength=GetImageListLength(image); do { QuantumAny max_value; /* Write PNM file header. */ packet_size=3; quantum_type=RGBQuantum; (void) CopyMagickString(magick,image_info->magick,MagickPathExtent); max_value=GetQuantumRange(image->depth); switch (magick[1]) { case 'A': case 'a': { format='7'; break; } case 'B': case 'b': { format='4'; if (image_info->compression == NoCompression) format='1'; break; } case 'F': case 'f': { format='F'; if (SetImageGray(image,exception) != MagickFalse) format='f'; break; } case 'G': case 'g': { format='5'; if (image_info->compression == NoCompression) format='2'; break; } case 'N': case 'n': { if ((image_info->type != TrueColorType) && (SetImageGray(image,exception) != MagickFalse)) { format='5'; if (image_info->compression == NoCompression) format='2'; if (SetImageMonochrome(image,exception) != MagickFalse) { format='4'; if (image_info->compression == NoCompression) format='1'; } break; } } default: { format='6'; if (image_info->compression == NoCompression) format='3'; break; } } (void) FormatLocaleString(buffer,MagickPathExtent,"P%c\n",format); (void) WriteBlobString(image,buffer); value=GetImageProperty(image,"comment",exception); if (value != (const char *) NULL) { register const char *p; /* Write comments to file. */ (void) WriteBlobByte(image,'#'); for (p=value; *p != '\0'; p++) { (void) WriteBlobByte(image,(unsigned char) *p); if ((*p == '\n') || (*p == '\r')) (void) WriteBlobByte(image,'#'); } (void) WriteBlobByte(image,'\n'); } if (format != '7') { (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g %.20g\n", (double) image->columns,(double) image->rows); (void) WriteBlobString(image,buffer); } else { char type[MagickPathExtent]; /* PAM header. */ (void) FormatLocaleString(buffer,MagickPathExtent, "WIDTH %.20g\nHEIGHT %.20g\n",(double) image->columns,(double) image->rows); (void) WriteBlobString(image,buffer); quantum_type=GetQuantumType(image,exception); switch (quantum_type) { case CMYKQuantum: case CMYKAQuantum: { packet_size=4; (void) CopyMagickString(type,"CMYK",MagickPathExtent); break; } case GrayQuantum: case GrayAlphaQuantum: { packet_size=1; (void) CopyMagickString(type,"GRAYSCALE",MagickPathExtent); if (IdentifyImageMonochrome(image,exception) != MagickFalse) (void) CopyMagickString(type,"BLACKANDWHITE",MagickPathExtent); break; } default: { quantum_type=RGBQuantum; if (image->alpha_trait != UndefinedPixelTrait) quantum_type=RGBAQuantum; packet_size=3; (void) CopyMagickString(type,"RGB",MagickPathExtent); break; } } if (image->alpha_trait != UndefinedPixelTrait) { packet_size++; (void) ConcatenateMagickString(type,"_ALPHA",MagickPathExtent); } if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MagickPathExtent, "DEPTH %.20g\nMAXVAL %.20g\n",(double) packet_size,(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent, "TUPLTYPE %s\nENDHDR\n",type); (void) WriteBlobString(image,buffer); } /* Convert runextent encoded to PNM raster pixels. */ switch (format) { case '1': { unsigned char pixels[2048]; /* Convert image to a PBM image. */ (void) SetImageType(image,BilevelType,exception); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=(unsigned char) (GetPixelLuma(image,p) >= (QuantumRange/2.0) ? '0' : '1'); if ((q-pixels+1) >= (ssize_t) sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } *q++=' '; p+=GetPixelChannels(image); } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '2': { unsigned char pixels[2048]; /* Convert image to a PGM image. */ if (image->depth <= 8) (void) WriteBlobString(image,"255\n"); else if (image->depth <= 16) (void) WriteBlobString(image,"65535\n"); else (void) WriteBlobString(image,"4294967295\n"); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { index=ClampToQuantum(GetPixelLuma(image,p)); if (image->depth <= 8) count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,"%u ", ScaleQuantumToChar(index)); else if (image->depth <= 16) count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u ",ScaleQuantumToShort(index)); else count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u ",ScaleQuantumToLong(index)); extent=(size_t) count; if ((q-pixels+extent+1) >= sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } (void) strncpy((char *) q,buffer,extent); q+=extent; p+=GetPixelChannels(image); } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '3': { unsigned char pixels[2048]; /* Convert image to a PNM image. */ (void) TransformImageColorspace(image,sRGBColorspace,exception); if (image->depth <= 8) (void) WriteBlobString(image,"255\n"); else if (image->depth <= 16) (void) WriteBlobString(image,"65535\n"); else (void) WriteBlobString(image,"4294967295\n"); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->depth <= 8) count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u %u %u ",ScaleQuantumToChar(GetPixelRed(image,p)), ScaleQuantumToChar(GetPixelGreen(image,p)), ScaleQuantumToChar(GetPixelBlue(image,p))); else if (image->depth <= 16) count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u %u %u ",ScaleQuantumToShort(GetPixelRed(image,p)), ScaleQuantumToShort(GetPixelGreen(image,p)), ScaleQuantumToShort(GetPixelBlue(image,p))); else count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u %u %u ",ScaleQuantumToLong(GetPixelRed(image,p)), ScaleQuantumToLong(GetPixelGreen(image,p)), ScaleQuantumToLong(GetPixelBlue(image,p))); extent=(size_t) count; if ((q-pixels+extent+2) >= sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } (void) strncpy((char *) q,buffer,extent); q+=extent; p+=GetPixelChannels(image); } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '4': { register unsigned char *pixels; /* Convert image to a PBM image. */ (void) SetImageType(image,BilevelType,exception); image->depth=1; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); quantum_info->min_is_white=MagickTrue; pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayQuantum,pixels,exception); count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '5': { register unsigned char *pixels; /* Convert image to a PGM image. */ if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); quantum_info->min_is_white=MagickTrue; pixels=GetQuantumPixels(quantum_info); extent=GetQuantumExtent(image,quantum_info,GrayQuantum); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayQuantum,pixels,exception); break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { if (IsPixelGray(image,p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma( image,p)),max_value); else { if (image->depth == 8) pixel=ScaleQuantumToChar(GetPixelRed(image,p)); else pixel=ScaleQuantumToAny(GetPixelRed(image,p), max_value); } q=PopCharPixel((unsigned char) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { if (IsPixelGray(image,p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image, p)),max_value); else { if (image->depth == 16) pixel=ScaleQuantumToShort(GetPixelRed(image,p)); else pixel=ScaleQuantumToAny(GetPixelRed(image,p), max_value); } q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } for (x=0; x < (ssize_t) image->columns; x++) { if (IsPixelGray(image,p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image,p)), max_value); else { if (image->depth == 16) pixel=ScaleQuantumToLong(GetPixelRed(image,p)); else pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); } q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '6': { register unsigned char *pixels; /* Convert image to a PNM image. */ (void) TransformImageColorspace(image,sRGBColorspace,exception); if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); pixels=GetQuantumPixels(quantum_info); extent=GetQuantumExtent(image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '7': { register unsigned char *pixels; /* Convert image to a PAM. */ if (image->depth > 32) image->depth=32; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } default: { switch (quantum_type) { case GrayQuantum: case GrayAlphaQuantum: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma( image,p)),max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelAlpha(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); } p+=GetPixelChannels(image); } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma( image,p)),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelAlpha(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image, p)),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelAlpha(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p+=GetPixelChannels(image); } break; } case CMYKQuantum: case CMYKAQuantum: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlack(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); } p+=GetPixelChannels(image); } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlack(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlack(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p+=GetPixelChannels(image); } break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); } p+=GetPixelChannels(image); } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p+=GetPixelChannels(image); } break; } } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case 'F': case 'f': { register unsigned char *pixels; (void) WriteBlobString(image,image->endian == LSBEndian ? "-1.0\n" : "1.0\n"); image->depth=32; quantum_type=format == 'f' ? GrayQuantum : RGBQuantum; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); pixels=GetQuantumPixels(quantum_info); for (y=(ssize_t) image->rows-1; y >= 0; y--) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); (void) WriteBlob(image,extent,pixels); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } } if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(MagickTrue); }
./CrossVul/dataset_final_sorted/CWE-119/c/good_934_0
crossvul-cpp_data_good_1358_0
/** * @file resolve.c * @author Michal Vasko <mvasko@cesnet.cz> * @brief libyang resolve functions * * Copyright (c) 2015 - 2018 CESNET, z.s.p.o. * * This source code is licensed under BSD 3-Clause License (the "License"). * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/BSD-3-Clause */ #define _GNU_SOURCE #include <stdlib.h> #include <assert.h> #include <string.h> #include <ctype.h> #include <limits.h> #include "libyang.h" #include "resolve.h" #include "common.h" #include "xpath.h" #include "parser.h" #include "parser_yang.h" #include "xml_internal.h" #include "hash_table.h" #include "tree_internal.h" #include "extensions.h" #include "validation.h" /* internal parsed predicate structure */ struct parsed_pred { const struct lys_node *schema; int len; struct { const char *mod_name; int mod_name_len; const char *name; int nam_len; const char *value; int val_len; } *pred; }; int parse_range_dec64(const char **str_num, uint8_t dig, int64_t *num) { const char *ptr; int minus = 0; int64_t ret = 0, prev_ret; int8_t str_exp, str_dig = -1, trailing_zeros = 0; ptr = *str_num; if (ptr[0] == '-') { minus = 1; ++ptr; } else if (ptr[0] == '+') { ++ptr; } if (!isdigit(ptr[0])) { /* there must be at least one */ return 1; } for (str_exp = 0; isdigit(ptr[0]) || ((ptr[0] == '.') && (str_dig < 0)); ++ptr) { if (str_exp > 18) { return 1; } if (ptr[0] == '.') { if (ptr[1] == '.') { /* it's the next interval */ break; } ++str_dig; } else { prev_ret = ret; if (minus) { ret = ret * 10 - (ptr[0] - '0'); if (ret > prev_ret) { return 1; } } else { ret = ret * 10 + (ptr[0] - '0'); if (ret < prev_ret) { return 1; } } if (str_dig > -1) { ++str_dig; if (ptr[0] == '0') { /* possibly trailing zero */ trailing_zeros++; } else { trailing_zeros = 0; } } ++str_exp; } } if (str_dig == 0) { /* no digits after '.' */ return 1; } else if (str_dig == -1) { /* there are 0 numbers after the floating point */ str_dig = 0; } /* remove trailing zeros */ if (trailing_zeros) { str_dig -= trailing_zeros; str_exp -= trailing_zeros; ret = ret / dec_pow(trailing_zeros); } /* it's parsed, now adjust the number based on fraction-digits, if needed */ if (str_dig < dig) { if ((str_exp - 1) + (dig - str_dig) > 18) { return 1; } prev_ret = ret; ret *= dec_pow(dig - str_dig); if ((minus && (ret > prev_ret)) || (!minus && (ret < prev_ret))) { return 1; } } if (str_dig > dig) { return 1; } *str_num = ptr; *num = ret; return 0; } /** * @brief Parse an identifier. * * ;; An identifier MUST NOT start with (('X'|'x') ('M'|'m') ('L'|'l')) * identifier = (ALPHA / "_") * *(ALPHA / DIGIT / "_" / "-" / ".") * * @param[in] id Identifier to use. * * @return Number of characters successfully parsed. */ unsigned int parse_identifier(const char *id) { unsigned int parsed = 0; assert(id); if (!isalpha(id[0]) && (id[0] != '_')) { return -parsed; } ++parsed; ++id; while (isalnum(id[0]) || (id[0] == '_') || (id[0] == '-') || (id[0] == '.')) { ++parsed; ++id; } return parsed; } /** * @brief Parse a node-identifier. * * node-identifier = [module-name ":"] identifier * * @param[in] id Identifier to use. * @param[out] mod_name Points to the module name, NULL if there is not any. * @param[out] mod_name_len Length of the module name, 0 if there is not any. * @param[out] name Points to the node name. * @param[out] nam_len Length of the node name. * @param[out] all_desc Whether the path starts with '/', only supported in extended paths. * @param[in] extended Whether to accept an extended path (support for [prefix:]*, /[prefix:]*, /[prefix:]., prefix:#identifier). * * @return Number of characters successfully parsed, * positive on success, negative on failure. */ static int parse_node_identifier(const char *id, const char **mod_name, int *mod_name_len, const char **name, int *nam_len, int *all_desc, int extended) { int parsed = 0, ret, all_desc_local = 0, first_id_len; const char *first_id; assert(id); assert((mod_name && mod_name_len) || (!mod_name && !mod_name_len)); assert((name && nam_len) || (!name && !nam_len)); if (mod_name) { *mod_name = NULL; *mod_name_len = 0; } if (name) { *name = NULL; *nam_len = 0; } if (extended) { /* try to parse only the extended expressions */ if (id[parsed] == '/') { if (all_desc) { *all_desc = 1; } all_desc_local = 1; } else { if (all_desc) { *all_desc = 0; } } /* is there a prefix? */ ret = parse_identifier(id + all_desc_local); if (ret > 0) { if (id[all_desc_local + ret] != ':') { /* this is not a prefix, so not an extended id */ goto standard_id; } if (mod_name) { *mod_name = id + all_desc_local; *mod_name_len = ret; } /* "/" and ":" */ ret += all_desc_local + 1; } else { ret = all_desc_local; } /* parse either "*" or "." */ if (*(id + ret) == '*') { if (name) { *name = id + ret; *nam_len = 1; } ++ret; return ret; } else if (*(id + ret) == '.') { if (!all_desc_local) { /* /. is redundant expression, we do not accept it */ return -ret; } if (name) { *name = id + ret; *nam_len = 1; } ++ret; return ret; } else if (*(id + ret) == '#') { if (all_desc_local || !ret) { /* no prefix */ return 0; } parsed = ret + 1; if ((ret = parse_identifier(id + parsed)) < 1) { return -parsed + ret; } *name = id + parsed - 1; *nam_len = ret + 1; return parsed + ret; } /* else a standard id, parse it all again */ } standard_id: if ((ret = parse_identifier(id)) < 1) { return ret; } first_id = id; first_id_len = ret; parsed += ret; id += ret; /* there is prefix */ if (id[0] == ':') { ++parsed; ++id; /* there isn't */ } else { if (name) { *name = first_id; *nam_len = first_id_len; } return parsed; } /* identifier (node name) */ if ((ret = parse_identifier(id)) < 1) { return -parsed + ret; } if (mod_name) { *mod_name = first_id; *mod_name_len = first_id_len; } if (name) { *name = id; *nam_len = ret; } return parsed + ret; } /** * @brief Parse a path-predicate (leafref). * * path-predicate = "[" *WSP path-equality-expr *WSP "]" * path-equality-expr = node-identifier *WSP "=" *WSP path-key-expr * * @param[in] id Identifier to use. * @param[out] prefix Points to the prefix, NULL if there is not any. * @param[out] pref_len Length of the prefix, 0 if there is not any. * @param[out] name Points to the node name. * @param[out] nam_len Length of the node name. * @param[out] path_key_expr Points to the path-key-expr. * @param[out] pke_len Length of the path-key-expr. * @param[out] has_predicate Flag to mark whether there is another predicate following. * * @return Number of characters successfully parsed, * positive on success, negative on failure. */ static int parse_path_predicate(const char *id, const char **prefix, int *pref_len, const char **name, int *nam_len, const char **path_key_expr, int *pke_len, int *has_predicate) { const char *ptr; int parsed = 0, ret; assert(id); if (prefix) { *prefix = NULL; } if (pref_len) { *pref_len = 0; } if (name) { *name = NULL; } if (nam_len) { *nam_len = 0; } if (path_key_expr) { *path_key_expr = NULL; } if (pke_len) { *pke_len = 0; } if (has_predicate) { *has_predicate = 0; } if (id[0] != '[') { return -parsed; } ++parsed; ++id; while (isspace(id[0])) { ++parsed; ++id; } if ((ret = parse_node_identifier(id, prefix, pref_len, name, nam_len, NULL, 0)) < 1) { return -parsed+ret; } parsed += ret; id += ret; while (isspace(id[0])) { ++parsed; ++id; } if (id[0] != '=') { return -parsed; } ++parsed; ++id; while (isspace(id[0])) { ++parsed; ++id; } if ((ptr = strchr(id, ']')) == NULL) { return -parsed; } --ptr; while (isspace(ptr[0])) { --ptr; } ++ptr; ret = ptr-id; if (path_key_expr) { *path_key_expr = id; } if (pke_len) { *pke_len = ret; } parsed += ret; id += ret; while (isspace(id[0])) { ++parsed; ++id; } assert(id[0] == ']'); if (id[1] == '[') { *has_predicate = 1; } return parsed+1; } /** * @brief Parse a path-key-expr (leafref). First call parses "current()", all * the ".." and the first node-identifier, other calls parse a single * node-identifier each. * * path-key-expr = current-function-invocation *WSP "/" *WSP * rel-path-keyexpr * rel-path-keyexpr = 1*(".." *WSP "/" *WSP) * *(node-identifier *WSP "/" *WSP) * node-identifier * * @param[in] id Identifier to use. * @param[out] prefix Points to the prefix, NULL if there is not any. * @param[out] pref_len Length of the prefix, 0 if there is not any. * @param[out] name Points to the node name. * @param[out] nam_len Length of the node name. * @param[out] parent_times Number of ".." in the path. Must be 0 on the first call, * must not be changed between consecutive calls. * @return Number of characters successfully parsed, * positive on success, negative on failure. */ static int parse_path_key_expr(const char *id, const char **prefix, int *pref_len, const char **name, int *nam_len, int *parent_times) { int parsed = 0, ret, par_times = 0; assert(id); assert(parent_times); if (prefix) { *prefix = NULL; } if (pref_len) { *pref_len = 0; } if (name) { *name = NULL; } if (nam_len) { *nam_len = 0; } if (!*parent_times) { /* current-function-invocation *WSP "/" *WSP rel-path-keyexpr */ if (strncmp(id, "current()", 9)) { return -parsed; } parsed += 9; id += 9; while (isspace(id[0])) { ++parsed; ++id; } if (id[0] != '/') { return -parsed; } ++parsed; ++id; while (isspace(id[0])) { ++parsed; ++id; } /* rel-path-keyexpr */ if (strncmp(id, "..", 2)) { return -parsed; } ++par_times; parsed += 2; id += 2; while (isspace(id[0])) { ++parsed; ++id; } } /* 1*(".." *WSP "/" *WSP) *(node-identifier *WSP "/" *WSP) node-identifier * * first parent reference with whitespaces already parsed */ if (id[0] != '/') { return -parsed; } ++parsed; ++id; while (isspace(id[0])) { ++parsed; ++id; } while (!strncmp(id, "..", 2) && !*parent_times) { ++par_times; parsed += 2; id += 2; while (isspace(id[0])) { ++parsed; ++id; } if (id[0] != '/') { return -parsed; } ++parsed; ++id; while (isspace(id[0])) { ++parsed; ++id; } } if (!*parent_times) { *parent_times = par_times; } /* all parent references must be parsed at this point */ if ((ret = parse_node_identifier(id, prefix, pref_len, name, nam_len, NULL, 0)) < 1) { return -parsed + ret; } parsed += ret; id += ret; return parsed; } /** * @brief Parse path-arg (leafref). * * path-arg = absolute-path / relative-path * absolute-path = 1*("/" (node-identifier *path-predicate)) * relative-path = 1*(".." "/") descendant-path * * @param[in] mod Module of the context node to get correct prefix in case it is not explicitly specified * @param[in] id Identifier to use. * @param[out] prefix Points to the prefix, NULL if there is not any. * @param[out] pref_len Length of the prefix, 0 if there is not any. * @param[out] name Points to the node name. * @param[out] nam_len Length of the node name. * @param[out] parent_times Number of ".." in the path. Must be 0 on the first call, * must not be changed between consecutive calls. -1 if the * path is relative. * @param[out] has_predicate Flag to mark whether there is a predicate specified. * * @return Number of characters successfully parsed, * positive on success, negative on failure. */ static int parse_path_arg(const struct lys_module *mod, const char *id, const char **prefix, int *pref_len, const char **name, int *nam_len, int *parent_times, int *has_predicate) { int parsed = 0, ret, par_times = 0; assert(id); assert(parent_times); if (prefix) { *prefix = NULL; } if (pref_len) { *pref_len = 0; } if (name) { *name = NULL; } if (nam_len) { *nam_len = 0; } if (has_predicate) { *has_predicate = 0; } if (!*parent_times && !strncmp(id, "..", 2)) { ++par_times; parsed += 2; id += 2; while (!strncmp(id, "/..", 3)) { ++par_times; parsed += 3; id += 3; } } if (!*parent_times) { if (par_times) { *parent_times = par_times; } else { *parent_times = -1; } } if (id[0] != '/') { return -parsed; } /* skip '/' */ ++parsed; ++id; /* node-identifier ([prefix:]identifier) */ if ((ret = parse_node_identifier(id, prefix, pref_len, name, nam_len, NULL, 0)) < 1) { return -parsed - ret; } if (prefix && !(*prefix)) { /* actually we always need prefix even it is not specified */ *prefix = lys_main_module(mod)->name; *pref_len = strlen(*prefix); } parsed += ret; id += ret; /* there is no predicate */ if ((id[0] == '/') || !id[0]) { return parsed; } else if (id[0] != '[') { return -parsed; } if (has_predicate) { *has_predicate = 1; } return parsed; } /** * @brief Parse instance-identifier in JSON data format. That means that prefixes * are actually model names. * * instance-identifier = 1*("/" (node-identifier *predicate)) * * @param[in] id Identifier to use. * @param[out] model Points to the model name. * @param[out] mod_len Length of the model name. * @param[out] name Points to the node name. * @param[out] nam_len Length of the node name. * @param[out] has_predicate Flag to mark whether there is a predicate specified. * * @return Number of characters successfully parsed, * positive on success, negative on failure. */ static int parse_instance_identifier(const char *id, const char **model, int *mod_len, const char **name, int *nam_len, int *has_predicate) { int parsed = 0, ret; assert(id && model && mod_len && name && nam_len); if (has_predicate) { *has_predicate = 0; } if (id[0] != '/') { return -parsed; } ++parsed; ++id; if ((ret = parse_identifier(id)) < 1) { return ret; } *name = id; *nam_len = ret; parsed += ret; id += ret; if (id[0] == ':') { /* we have prefix */ *model = *name; *mod_len = *nam_len; ++parsed; ++id; if ((ret = parse_identifier(id)) < 1) { return ret; } *name = id; *nam_len = ret; parsed += ret; id += ret; } if (id[0] == '[' && has_predicate) { *has_predicate = 1; } return parsed; } /** * @brief Parse predicate (instance-identifier) in JSON data format. That means that prefixes * (which are mandatory) are actually model names. * * predicate = "[" *WSP (predicate-expr / pos) *WSP "]" * predicate-expr = (node-identifier / ".") *WSP "=" *WSP * ((DQUOTE string DQUOTE) / * (SQUOTE string SQUOTE)) * pos = non-negative-integer-value * * @param[in] id Identifier to use. * @param[out] model Points to the model name. * @param[out] mod_len Length of the model name. * @param[out] name Points to the node name. Can be identifier (from node-identifier), "." or pos. * @param[out] nam_len Length of the node name. * @param[out] value Value the node-identifier must have (string from the grammar), * NULL if there is not any. * @param[out] val_len Length of the value, 0 if there is not any. * @param[out] has_predicate Flag to mark whether there is a predicate specified. * * @return Number of characters successfully parsed, * positive on success, negative on failure. */ static int parse_predicate(const char *id, const char **model, int *mod_len, const char **name, int *nam_len, const char **value, int *val_len, int *has_predicate) { const char *ptr; int parsed = 0, ret; char quote; assert(id); if (model) { assert(mod_len); *model = NULL; *mod_len = 0; } if (name) { assert(nam_len); *name = NULL; *nam_len = 0; } if (value) { assert(val_len); *value = NULL; *val_len = 0; } if (has_predicate) { *has_predicate = 0; } if (id[0] != '[') { return -parsed; } ++parsed; ++id; while (isspace(id[0])) { ++parsed; ++id; } /* pos */ if (isdigit(id[0])) { if (name) { *name = id; } if (id[0] == '0') { return -parsed; } while (isdigit(id[0])) { ++parsed; ++id; } if (nam_len) { *nam_len = id-(*name); } /* "." or node-identifier */ } else { if (id[0] == '.') { if (name) { *name = id; } if (nam_len) { *nam_len = 1; } ++parsed; ++id; } else { if ((ret = parse_node_identifier(id, model, mod_len, name, nam_len, NULL, 0)) < 1) { return -parsed + ret; } parsed += ret; id += ret; } while (isspace(id[0])) { ++parsed; ++id; } if (id[0] != '=') { return -parsed; } ++parsed; ++id; while (isspace(id[0])) { ++parsed; ++id; } /* ((DQUOTE string DQUOTE) / (SQUOTE string SQUOTE)) */ if ((id[0] == '\"') || (id[0] == '\'')) { quote = id[0]; ++parsed; ++id; if ((ptr = strchr(id, quote)) == NULL) { return -parsed; } ret = ptr - id; if (value) { *value = id; } if (val_len) { *val_len = ret; } parsed += ret + 1; id += ret + 1; } else { return -parsed; } } while (isspace(id[0])) { ++parsed; ++id; } if (id[0] != ']') { return -parsed; } ++parsed; ++id; if ((id[0] == '[') && has_predicate) { *has_predicate = 1; } return parsed; } /** * @brief Parse schema-nodeid. * * schema-nodeid = absolute-schema-nodeid / * descendant-schema-nodeid * absolute-schema-nodeid = 1*("/" node-identifier) * descendant-schema-nodeid = ["." "/"] * node-identifier * absolute-schema-nodeid * * @param[in] id Identifier to use. * @param[out] mod_name Points to the module name, NULL if there is not any. * @param[out] mod_name_len Length of the module name, 0 if there is not any. * @param[out] name Points to the node name. * @param[out] nam_len Length of the node name. * @param[out] is_relative Flag to mark whether the nodeid is absolute or descendant. Must be -1 * on the first call, must not be changed between consecutive calls. * @param[out] has_predicate Flag to mark whether there is a predicate specified. It cannot be * based on the grammar, in those cases use NULL. * @param[in] extended Whether to accept an extended path (support for /[prefix:]*, //[prefix:]*, //[prefix:].). * * @return Number of characters successfully parsed, * positive on success, negative on failure. */ int parse_schema_nodeid(const char *id, const char **mod_name, int *mod_name_len, const char **name, int *nam_len, int *is_relative, int *has_predicate, int *all_desc, int extended) { int parsed = 0, ret; assert(id); assert(is_relative); if (has_predicate) { *has_predicate = 0; } if (id[0] != '/') { if (*is_relative != -1) { return -parsed; } else { *is_relative = 1; } if (!strncmp(id, "./", 2)) { parsed += 2; id += 2; } } else { if (*is_relative == -1) { *is_relative = 0; } ++parsed; ++id; } if ((ret = parse_node_identifier(id, mod_name, mod_name_len, name, nam_len, all_desc, extended)) < 1) { return -parsed + ret; } parsed += ret; id += ret; if ((id[0] == '[') && has_predicate) { *has_predicate = 1; } return parsed; } /** * @brief Parse schema predicate (special format internally used). * * predicate = "[" *WSP predicate-expr *WSP "]" * predicate-expr = "." / [prefix:]identifier / positive-integer / key-with-value * key-with-value = identifier *WSP "=" *WSP * ((DQUOTE string DQUOTE) / * (SQUOTE string SQUOTE)) * * @param[in] id Identifier to use. * @param[out] mod_name Points to the list key module name. * @param[out] mod_name_len Length of \p mod_name. * @param[out] name Points to the list key name. * @param[out] nam_len Length of \p name. * @param[out] value Points to the key value. If specified, key-with-value is expected. * @param[out] val_len Length of \p value. * @param[out] has_predicate Flag to mark whether there is another predicate specified. */ int parse_schema_json_predicate(const char *id, const char **mod_name, int *mod_name_len, const char **name, int *nam_len, const char **value, int *val_len, int *has_predicate) { const char *ptr; int parsed = 0, ret; char quote; assert(id); if (mod_name) { *mod_name = NULL; } if (mod_name_len) { *mod_name_len = 0; } if (name) { *name = NULL; } if (nam_len) { *nam_len = 0; } if (value) { *value = NULL; } if (val_len) { *val_len = 0; } if (has_predicate) { *has_predicate = 0; } if (id[0] != '[') { return -parsed; } ++parsed; ++id; while (isspace(id[0])) { ++parsed; ++id; } /* identifier */ if (id[0] == '.') { ret = 1; if (name) { *name = id; } if (nam_len) { *nam_len = ret; } } else if (isdigit(id[0])) { if (id[0] == '0') { return -parsed; } ret = 1; while (isdigit(id[ret])) { ++ret; } if (name) { *name = id; } if (nam_len) { *nam_len = ret; } } else if ((ret = parse_node_identifier(id, mod_name, mod_name_len, name, nam_len, NULL, 0)) < 1) { return -parsed + ret; } parsed += ret; id += ret; while (isspace(id[0])) { ++parsed; ++id; } /* there is value as well */ if (id[0] == '=') { if (name && isdigit(**name)) { return -parsed; } ++parsed; ++id; while (isspace(id[0])) { ++parsed; ++id; } /* ((DQUOTE string DQUOTE) / (SQUOTE string SQUOTE)) */ if ((id[0] == '\"') || (id[0] == '\'')) { quote = id[0]; ++parsed; ++id; if ((ptr = strchr(id, quote)) == NULL) { return -parsed; } ret = ptr - id; if (value) { *value = id; } if (val_len) { *val_len = ret; } parsed += ret + 1; id += ret + 1; } else { return -parsed; } while (isspace(id[0])) { ++parsed; ++id; } } if (id[0] != ']') { return -parsed; } ++parsed; ++id; if ((id[0] == '[') && has_predicate) { *has_predicate = 1; } return parsed; } #ifdef LY_ENABLED_CACHE static int resolve_hash_table_find_equal(void *val1_p, void *val2_p, int mod, void *UNUSED(cb_data)) { struct lyd_node *val2, *elem2; struct parsed_pred pp; const char *str; int i; assert(!mod); (void)mod; pp = *((struct parsed_pred *)val1_p); val2 = *((struct lyd_node **)val2_p); if (val2->schema != pp.schema) { return 0; } switch (val2->schema->nodetype) { case LYS_CONTAINER: case LYS_LEAF: case LYS_ANYXML: case LYS_ANYDATA: return 1; case LYS_LEAFLIST: str = ((struct lyd_node_leaf_list *)val2)->value_str; if (!strncmp(str, pp.pred[0].value, pp.pred[0].val_len) && !str[pp.pred[0].val_len]) { return 1; } return 0; case LYS_LIST: assert(((struct lys_node_list *)val2->schema)->keys_size); assert(((struct lys_node_list *)val2->schema)->keys_size == pp.len); /* lists with keys, their equivalence is based on their keys */ elem2 = val2->child; /* the exact data order is guaranteed */ for (i = 0; elem2 && (i < pp.len); ++i) { /* module check */ if (pp.pred[i].mod_name) { if (strncmp(lyd_node_module(elem2)->name, pp.pred[i].mod_name, pp.pred[i].mod_name_len) || lyd_node_module(elem2)->name[pp.pred[i].mod_name_len]) { break; } } else { if (lyd_node_module(elem2) != lys_node_module(pp.schema)) { break; } } /* name check */ if (strncmp(elem2->schema->name, pp.pred[i].name, pp.pred[i].nam_len) || elem2->schema->name[pp.pred[i].nam_len]) { break; } /* value check */ str = ((struct lyd_node_leaf_list *)elem2)->value_str; if (strncmp(str, pp.pred[i].value, pp.pred[i].val_len) || str[pp.pred[i].val_len]) { break; } /* next key */ elem2 = elem2->next; } if (i == pp.len) { return 1; } return 0; default: break; } LOGINT(val2->schema->module->ctx); return 0; } static struct lyd_node * resolve_json_data_node_hash(struct lyd_node *parent, struct parsed_pred pp) { values_equal_cb prev_cb; struct lyd_node **ret = NULL; uint32_t hash; int i; assert(parent && parent->hash); /* set our value equivalence callback that does not require data nodes */ prev_cb = lyht_set_cb(parent->ht, resolve_hash_table_find_equal); /* get the hash of the searched node */ hash = dict_hash_multi(0, lys_node_module(pp.schema)->name, strlen(lys_node_module(pp.schema)->name)); hash = dict_hash_multi(hash, pp.schema->name, strlen(pp.schema->name)); if (pp.schema->nodetype == LYS_LEAFLIST) { assert((pp.len == 1) && (pp.pred[0].name[0] == '.') && (pp.pred[0].nam_len == 1)); /* leaf-list value in predicate */ hash = dict_hash_multi(hash, pp.pred[0].value, pp.pred[0].val_len); } else if (pp.schema->nodetype == LYS_LIST) { /* list keys in predicates */ for (i = 0; i < pp.len; ++i) { hash = dict_hash_multi(hash, pp.pred[i].value, pp.pred[i].val_len); } } hash = dict_hash_multi(hash, NULL, 0); /* try to find the node */ i = lyht_find(parent->ht, &pp, hash, (void **)&ret); assert(i || *ret); /* restore the original callback */ lyht_set_cb(parent->ht, prev_cb); return (i ? NULL : *ret); } #endif /** * @brief Resolve (find) a feature definition. Logs directly. * * @param[in] feat_name Feature name to resolve. * @param[in] len Length of \p feat_name. * @param[in] node Node with the if-feature expression. * @param[out] feature Pointer to be set to point to the feature definition, if feature not found * (return code 1), the pointer is untouched. * * @return 0 on success, 1 on forward reference, -1 on error. */ static int resolve_feature(const char *feat_name, uint16_t len, const struct lys_node *node, struct lys_feature **feature) { char *str; const char *mod_name, *name; int mod_name_len, nam_len, i, j; const struct lys_module *module; assert(feature); /* check prefix */ if ((i = parse_node_identifier(feat_name, &mod_name, &mod_name_len, &name, &nam_len, NULL, 0)) < 1) { LOGVAL(node->module->ctx, LYE_INCHAR, LY_VLOG_NONE, NULL, feat_name[-i], &feat_name[-i]); return -1; } module = lyp_get_module(lys_node_module(node), NULL, 0, mod_name, mod_name_len, 0); if (!module) { /* identity refers unknown data model */ LOGVAL(node->module->ctx, LYE_INMOD_LEN, LY_VLOG_NONE, NULL, mod_name_len, mod_name); return -1; } if (module != node->module && module == lys_node_module(node)) { /* first, try to search directly in submodule where the feature was mentioned */ for (j = 0; j < node->module->features_size; j++) { if (!strncmp(name, node->module->features[j].name, nam_len) && !node->module->features[j].name[nam_len]) { /* check status */ if (lyp_check_status(node->flags, lys_node_module(node), node->name, node->module->features[j].flags, node->module->features[j].module, node->module->features[j].name, NULL)) { return -1; } *feature = &node->module->features[j]; return 0; } } } /* search in the identified module ... */ for (j = 0; j < module->features_size; j++) { if (!strncmp(name, module->features[j].name, nam_len) && !module->features[j].name[nam_len]) { /* check status */ if (lyp_check_status(node->flags, lys_node_module(node), node->name, module->features[j].flags, module->features[j].module, module->features[j].name, NULL)) { return -1; } *feature = &module->features[j]; return 0; } } /* ... and all its submodules */ for (i = 0; i < module->inc_size && module->inc[i].submodule; i++) { for (j = 0; j < module->inc[i].submodule->features_size; j++) { if (!strncmp(name, module->inc[i].submodule->features[j].name, nam_len) && !module->inc[i].submodule->features[j].name[nam_len]) { /* check status */ if (lyp_check_status(node->flags, lys_node_module(node), node->name, module->inc[i].submodule->features[j].flags, module->inc[i].submodule->features[j].module, module->inc[i].submodule->features[j].name, NULL)) { return -1; } *feature = &module->inc[i].submodule->features[j]; return 0; } } } /* not found */ str = strndup(feat_name, len); LOGVAL(node->module->ctx, LYE_INRESOLV, LY_VLOG_NONE, NULL, "feature", str); free(str); return 1; } /* * @return * - 1 if enabled * - 0 if disabled */ static int resolve_feature_value(const struct lys_feature *feat) { int i; for (i = 0; i < feat->iffeature_size; i++) { if (!resolve_iffeature(&feat->iffeature[i])) { return 0; } } return feat->flags & LYS_FENABLED ? 1 : 0; } static int resolve_iffeature_recursive(struct lys_iffeature *expr, int *index_e, int *index_f) { uint8_t op; int a, b; op = iff_getop(expr->expr, *index_e); (*index_e)++; switch (op) { case LYS_IFF_F: /* resolve feature */ return resolve_feature_value(expr->features[(*index_f)++]); case LYS_IFF_NOT: /* invert result */ return resolve_iffeature_recursive(expr, index_e, index_f) ? 0 : 1; case LYS_IFF_AND: case LYS_IFF_OR: a = resolve_iffeature_recursive(expr, index_e, index_f); b = resolve_iffeature_recursive(expr, index_e, index_f); if (op == LYS_IFF_AND) { return a && b; } else { /* LYS_IFF_OR */ return a || b; } } return 0; } int resolve_iffeature(struct lys_iffeature *expr) { int index_e = 0, index_f = 0; if (expr->expr && expr->features[0]) { return resolve_iffeature_recursive(expr, &index_e, &index_f); } return 0; } struct iff_stack { int size; int index; /* first empty item */ uint8_t *stack; }; static int iff_stack_push(struct iff_stack *stack, uint8_t value) { if (stack->index == stack->size) { stack->size += 4; stack->stack = ly_realloc(stack->stack, stack->size * sizeof *stack->stack); LY_CHECK_ERR_RETURN(!stack->stack, LOGMEM(NULL); stack->size = 0, EXIT_FAILURE); } stack->stack[stack->index++] = value; return EXIT_SUCCESS; } static uint8_t iff_stack_pop(struct iff_stack *stack) { stack->index--; return stack->stack[stack->index]; } static void iff_stack_clean(struct iff_stack *stack) { stack->size = 0; free(stack->stack); } static void iff_setop(uint8_t *list, uint8_t op, int pos) { uint8_t *item; uint8_t mask = 3; assert(pos >= 0); assert(op <= 3); /* max 2 bits */ item = &list[pos / 4]; mask = mask << 2 * (pos % 4); *item = (*item) & ~mask; *item = (*item) | (op << 2 * (pos % 4)); } uint8_t iff_getop(uint8_t *list, int pos) { uint8_t *item; uint8_t mask = 3, result; assert(pos >= 0); item = &list[pos / 4]; result = (*item) & (mask << 2 * (pos % 4)); return result >> 2 * (pos % 4); } #define LYS_IFF_LP 0x04 /* ( */ #define LYS_IFF_RP 0x08 /* ) */ /* internal structure for passing data for UNRES_IFFEAT */ struct unres_iffeat_data { struct lys_node *node; const char *fname; int infeature; }; void resolve_iffeature_getsizes(struct lys_iffeature *iffeat, unsigned int *expr_size, unsigned int *feat_size) { unsigned int e = 0, f = 0, r = 0; uint8_t op; assert(iffeat); if (!iffeat->expr) { goto result; } do { op = iff_getop(iffeat->expr, e++); switch (op) { case LYS_IFF_NOT: if (!r) { r += 1; } break; case LYS_IFF_AND: case LYS_IFF_OR: if (!r) { r += 2; } else { r += 1; } break; case LYS_IFF_F: f++; if (r) { r--; } break; } } while(r); result: if (expr_size) { *expr_size = e; } if (feat_size) { *feat_size = f; } } int resolve_iffeature_compile(struct lys_iffeature *iffeat_expr, const char *value, struct lys_node *node, int infeature, struct unres_schema *unres) { const char *c = value; int r, rc = EXIT_FAILURE; int i, j, last_not, checkversion = 0; unsigned int f_size = 0, expr_size = 0, f_exp = 1; uint8_t op; struct iff_stack stack = {0, 0, NULL}; struct unres_iffeat_data *iff_data; struct ly_ctx *ctx = node->module->ctx; assert(c); if (isspace(c[0])) { LOGVAL(ctx, LYE_INCHAR, LY_VLOG_NONE, NULL, c[0], c); return EXIT_FAILURE; } /* pre-parse the expression to get sizes for arrays, also do some syntax checks of the expression */ for (i = j = last_not = 0; c[i]; i++) { if (c[i] == '(') { checkversion = 1; j++; continue; } else if (c[i] == ')') { j--; continue; } else if (isspace(c[i])) { continue; } if (!strncmp(&c[i], "not", r = 3) || !strncmp(&c[i], "and", r = 3) || !strncmp(&c[i], "or", r = 2)) { if (c[i + r] == '\0') { LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, value, "if-feature"); return EXIT_FAILURE; } else if (!isspace(c[i + r])) { /* feature name starting with the not/and/or */ last_not = 0; f_size++; } else if (c[i] == 'n') { /* not operation */ if (last_not) { /* double not */ expr_size = expr_size - 2; last_not = 0; } else { last_not = 1; } } else { /* and, or */ f_exp++; /* not a not operation */ last_not = 0; } i += r; } else { f_size++; last_not = 0; } expr_size++; while (!isspace(c[i])) { if (c[i] == '(') { LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, value, "if-feature"); return EXIT_FAILURE; } else if (!c[i] || c[i] == ')') { i--; break; } i++; } } if (j || f_exp != f_size) { /* not matching count of ( and ) */ LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, value, "if-feature"); return EXIT_FAILURE; } if (checkversion || expr_size > 1) { /* check that we have 1.1 module */ if (node->module->version != LYS_VERSION_1_1) { LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, value, "if-feature"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "YANG 1.1 if-feature expression found in 1.0 module."); return EXIT_FAILURE; } } /* allocate the memory */ iffeat_expr->expr = calloc((j = (expr_size / 4) + ((expr_size % 4) ? 1 : 0)), sizeof *iffeat_expr->expr); iffeat_expr->features = calloc(f_size, sizeof *iffeat_expr->features); stack.stack = malloc(expr_size * sizeof *stack.stack); LY_CHECK_ERR_GOTO(!stack.stack || !iffeat_expr->expr || !iffeat_expr->features, LOGMEM(ctx), error); stack.size = expr_size; f_size--; expr_size--; /* used as indexes from now */ for (i--; i >= 0; i--) { if (c[i] == ')') { /* push it on stack */ iff_stack_push(&stack, LYS_IFF_RP); continue; } else if (c[i] == '(') { /* pop from the stack into result all operators until ) */ while((op = iff_stack_pop(&stack)) != LYS_IFF_RP) { iff_setop(iffeat_expr->expr, op, expr_size--); } continue; } else if (isspace(c[i])) { continue; } /* end operator or operand -> find beginning and get what is it */ j = i + 1; while (i >= 0 && !isspace(c[i]) && c[i] != '(') { i--; } i++; /* get back by one step */ if (!strncmp(&c[i], "not", 3) && isspace(c[i + 3])) { if (stack.index && stack.stack[stack.index - 1] == LYS_IFF_NOT) { /* double not */ iff_stack_pop(&stack); } else { /* not has the highest priority, so do not pop from the stack * as in case of AND and OR */ iff_stack_push(&stack, LYS_IFF_NOT); } } else if (!strncmp(&c[i], "and", 3) && isspace(c[i + 3])) { /* as for OR - pop from the stack all operators with the same or higher * priority and store them to the result, then push the AND to the stack */ while (stack.index && stack.stack[stack.index - 1] <= LYS_IFF_AND) { op = iff_stack_pop(&stack); iff_setop(iffeat_expr->expr, op, expr_size--); } iff_stack_push(&stack, LYS_IFF_AND); } else if (!strncmp(&c[i], "or", 2) && isspace(c[i + 2])) { while (stack.index && stack.stack[stack.index - 1] <= LYS_IFF_OR) { op = iff_stack_pop(&stack); iff_setop(iffeat_expr->expr, op, expr_size--); } iff_stack_push(&stack, LYS_IFF_OR); } else { /* feature name, length is j - i */ /* add it to the result */ iff_setop(iffeat_expr->expr, LYS_IFF_F, expr_size--); /* now get the link to the feature definition. Since it can be * forward referenced, we have to keep the feature name in auxiliary * structure passed into unres */ iff_data = malloc(sizeof *iff_data); LY_CHECK_ERR_GOTO(!iff_data, LOGMEM(ctx), error); iff_data->node = node; iff_data->fname = lydict_insert(node->module->ctx, &c[i], j - i); iff_data->infeature = infeature; r = unres_schema_add_node(node->module, unres, &iffeat_expr->features[f_size], UNRES_IFFEAT, (struct lys_node *)iff_data); f_size--; if (r == -1) { lydict_remove(node->module->ctx, iff_data->fname); free(iff_data); goto error; } } } while (stack.index) { op = iff_stack_pop(&stack); iff_setop(iffeat_expr->expr, op, expr_size--); } if (++expr_size || ++f_size) { /* not all expected operators and operands found */ LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, value, "if-feature"); rc = EXIT_FAILURE; } else { rc = EXIT_SUCCESS; } error: /* cleanup */ iff_stack_clean(&stack); return rc; } /** * @brief Resolve (find) a data node based on a schema-nodeid. * * Used for resolving unique statements - so id is expected to be relative and local (without reference to a different * module). * */ struct lyd_node * resolve_data_descendant_schema_nodeid(const char *nodeid, struct lyd_node *start) { char *str, *token, *p; struct lyd_node *result = NULL, *iter; const struct lys_node *schema = NULL; assert(nodeid && start); if (nodeid[0] == '/') { return NULL; } str = p = strdup(nodeid); LY_CHECK_ERR_RETURN(!str, LOGMEM(start->schema->module->ctx), NULL); while (p) { token = p; p = strchr(p, '/'); if (p) { *p = '\0'; p++; } if (p) { /* inner node */ if (resolve_descendant_schema_nodeid(token, schema ? schema->child : start->schema, LYS_CONTAINER | LYS_CHOICE | LYS_CASE | LYS_LEAF, 0, &schema) || !schema) { result = NULL; break; } if (schema->nodetype & (LYS_CHOICE | LYS_CASE)) { continue; } } else { /* final node */ if (resolve_descendant_schema_nodeid(token, schema ? schema->child : start->schema, LYS_LEAF, 0, &schema) || !schema) { result = NULL; break; } } LY_TREE_FOR(result ? result->child : start, iter) { if (iter->schema == schema) { /* move in data tree according to returned schema */ result = iter; break; } } if (!iter) { /* instance not found */ result = NULL; break; } } free(str); return result; } int schema_nodeid_siblingcheck(const struct lys_node *sibling, const struct lys_module *cur_module, const char *mod_name, int mod_name_len, const char *name, int nam_len) { const struct lys_module *prefix_mod; /* handle special names */ if (name[0] == '*') { return 2; } else if (name[0] == '.') { return 3; } /* name check */ if (strncmp(name, sibling->name, nam_len) || sibling->name[nam_len]) { return 1; } /* module check */ if (mod_name) { prefix_mod = lyp_get_module(cur_module, NULL, 0, mod_name, mod_name_len, 0); if (!prefix_mod) { return -1; } } else { prefix_mod = cur_module; } if (prefix_mod != lys_node_module(sibling)) { return 1; } /* match */ return 0; } /* keys do not have to be ordered and do not have to be all of them */ static int resolve_extended_schema_nodeid_predicate(const char *nodeid, const struct lys_node *node, const struct lys_module *cur_module, int *nodeid_end) { int mod_len, nam_len, has_predicate, r, i; const char *model, *name; struct lys_node_list *list; if (!(node->nodetype & (LYS_LIST | LYS_LEAFLIST))) { return 1; } list = (struct lys_node_list *)node; do { r = parse_schema_json_predicate(nodeid, &model, &mod_len, &name, &nam_len, NULL, NULL, &has_predicate); if (r < 1) { LOGVAL(cur_module->ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, nodeid[r], &nodeid[r]); return -1; } nodeid += r; if (node->nodetype == LYS_LEAFLIST) { /* just check syntax */ if (model || !name || (name[0] != '.') || has_predicate) { return 1; } break; } else { /* check the key */ for (i = 0; i < list->keys_size; ++i) { if (strncmp(list->keys[i]->name, name, nam_len) || list->keys[i]->name[nam_len]) { continue; } if (model) { if (strncmp(lys_node_module((struct lys_node *)list->keys[i])->name, model, mod_len) || lys_node_module((struct lys_node *)list->keys[i])->name[mod_len]) { continue; } } else { if (lys_node_module((struct lys_node *)list->keys[i]) != cur_module) { continue; } } /* match */ break; } if (i == list->keys_size) { return 1; } } } while (has_predicate); if (!nodeid[0]) { *nodeid_end = 1; } return 0; } /* start_parent - relative, module - absolute, -1 error (logged), EXIT_SUCCESS ok */ int resolve_schema_nodeid(const char *nodeid, const struct lys_node *start_parent, const struct lys_module *cur_module, struct ly_set **ret, int extended, int no_node_error) { const char *name, *mod_name, *id, *backup_mod_name = NULL, *yang_data_name = NULL; const struct lys_node *sibling, *next, *elem; struct lys_node_augment *last_aug; int r, nam_len, mod_name_len = 0, is_relative = -1, all_desc, has_predicate, nodeid_end = 0; int yang_data_name_len, backup_mod_name_len = 0; /* resolved import module from the start module, it must match the next node-name-match sibling */ const struct lys_module *start_mod, *aux_mod = NULL; char *str; struct ly_ctx *ctx; assert(nodeid && (start_parent || cur_module) && ret); *ret = NULL; if (!cur_module) { cur_module = lys_node_module(start_parent); } ctx = cur_module->ctx; id = nodeid; r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, NULL, NULL, 1); if (r < 1) { LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[r], &id[r]); return -1; } if (name[0] == '#') { if (is_relative) { LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, '#', name); return -1; } yang_data_name = name + 1; yang_data_name_len = nam_len - 1; backup_mod_name = mod_name; backup_mod_name_len = mod_name_len; id += r; } else { is_relative = -1; } r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, &has_predicate, (extended ? &all_desc : NULL), extended); if (r < 1) { LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[r], &id[r]); return -1; } id += r; if (backup_mod_name) { mod_name = backup_mod_name; mod_name_len = backup_mod_name_len; } if (is_relative && !start_parent) { LOGVAL(ctx, LYE_SPEC, LY_VLOG_STR, nodeid, "Starting node must be provided for relative paths."); return -1; } /* descendant-schema-nodeid */ if (is_relative) { cur_module = start_mod = lys_node_module(start_parent); /* absolute-schema-nodeid */ } else { start_mod = lyp_get_module(cur_module, NULL, 0, mod_name, mod_name_len, 0); if (!start_mod) { str = strndup(mod_name, mod_name_len); LOGVAL(ctx, LYE_PATH_INMOD, LY_VLOG_STR, str); free(str); return -1; } start_parent = NULL; if (yang_data_name) { start_parent = lyp_get_yang_data_template(start_mod, yang_data_name, yang_data_name_len); if (!start_parent) { str = strndup(nodeid, (yang_data_name + yang_data_name_len) - nodeid); LOGVAL(ctx, LYE_PATH_INNODE, LY_VLOG_STR, str); free(str); return -1; } } } while (1) { sibling = NULL; last_aug = NULL; if (start_parent) { if (mod_name && (strncmp(mod_name, cur_module->name, mod_name_len) || (mod_name_len != (signed)strlen(cur_module->name)))) { /* we are getting into another module (augment) */ aux_mod = lyp_get_module(cur_module, NULL, 0, mod_name, mod_name_len, 0); if (!aux_mod) { str = strndup(mod_name, mod_name_len); LOGVAL(ctx, LYE_PATH_INMOD, LY_VLOG_STR, str); free(str); return -1; } } else { /* there is no mod_name, so why are we checking augments again? * because this module may be not implemented and it augments something in another module and * there is another augment augmenting that previous one */ aux_mod = cur_module; } /* look into augments */ if (!extended) { get_next_augment: last_aug = lys_getnext_target_aug(last_aug, aux_mod, start_parent); } } while ((sibling = lys_getnext(sibling, (last_aug ? (struct lys_node *)last_aug : start_parent), start_mod, LYS_GETNEXT_WITHCHOICE | LYS_GETNEXT_WITHCASE | LYS_GETNEXT_WITHINOUT | LYS_GETNEXT_PARENTUSES | LYS_GETNEXT_NOSTATECHECK))) { r = schema_nodeid_siblingcheck(sibling, cur_module, mod_name, mod_name_len, name, nam_len); /* resolve predicate */ if (extended && ((r == 0) || (r == 2) || (r == 3)) && has_predicate) { r = resolve_extended_schema_nodeid_predicate(id, sibling, cur_module, &nodeid_end); if (r == 1) { continue; } else if (r == -1) { return -1; } } else if (!id[0]) { nodeid_end = 1; } if (r == 0) { /* one matching result */ if (nodeid_end) { *ret = ly_set_new(); LY_CHECK_ERR_RETURN(!*ret, LOGMEM(ctx), -1); ly_set_add(*ret, (void *)sibling, LY_SET_OPT_USEASLIST); } else { if (sibling->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA)) { return -1; } start_parent = sibling; } break; } else if (r == 1) { continue; } else if (r == 2) { /* "*" */ if (!*ret) { *ret = ly_set_new(); LY_CHECK_ERR_RETURN(!*ret, LOGMEM(ctx), -1); } ly_set_add(*ret, (void *)sibling, LY_SET_OPT_USEASLIST); if (all_desc) { LY_TREE_DFS_BEGIN(sibling, next, elem) { if (elem != sibling) { ly_set_add(*ret, (void *)elem, LY_SET_OPT_USEASLIST); } LY_TREE_DFS_END(sibling, next, elem); } } } else if (r == 3) { /* "." */ if (!*ret) { *ret = ly_set_new(); LY_CHECK_ERR_RETURN(!*ret, LOGMEM(ctx), -1); ly_set_add(*ret, (void *)start_parent, LY_SET_OPT_USEASLIST); } ly_set_add(*ret, (void *)sibling, LY_SET_OPT_USEASLIST); if (all_desc) { LY_TREE_DFS_BEGIN(sibling, next, elem) { if (elem != sibling) { ly_set_add(*ret, (void *)elem, LY_SET_OPT_USEASLIST); } LY_TREE_DFS_END(sibling, next, elem); } } } else { LOGINT(ctx); return -1; } } /* skip predicate */ if (extended && has_predicate) { while (id[0] == '[') { id = strchr(id, ']'); if (!id) { LOGINT(ctx); return -1; } ++id; } } if (nodeid_end && ((r == 0) || (r == 2) || (r == 3))) { return EXIT_SUCCESS; } /* no match */ if (!sibling) { if (last_aug) { /* it still could be in another augment */ goto get_next_augment; } if (no_node_error) { str = strndup(nodeid, (name - nodeid) + nam_len); LOGVAL(ctx, LYE_PATH_INNODE, LY_VLOG_STR, str); free(str); return -1; } *ret = NULL; return EXIT_SUCCESS; } r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, &has_predicate, (extended ? &all_desc : NULL), extended); if (r < 1) { LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[r], &id[r]); return -1; } id += r; } /* cannot get here */ LOGINT(ctx); return -1; } /* unique, refine, * >0 - unexpected char on position (ret - 1), * 0 - ok (but ret can still be NULL), * -1 - error, * -2 - violated no_innerlist */ int resolve_descendant_schema_nodeid(const char *nodeid, const struct lys_node *start, int ret_nodetype, int no_innerlist, const struct lys_node **ret) { const char *name, *mod_name, *id; const struct lys_node *sibling, *start_parent; int r, nam_len, mod_name_len, is_relative = -1; /* resolved import module from the start module, it must match the next node-name-match sibling */ const struct lys_module *module; assert(nodeid && ret); assert(!(ret_nodetype & (LYS_USES | LYS_AUGMENT | LYS_GROUPING))); if (!start) { /* leaf not found */ return 0; } id = nodeid; module = lys_node_module(start); if ((r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, NULL, NULL, 0)) < 1) { return ((id - nodeid) - r) + 1; } id += r; if (!is_relative) { return -1; } start_parent = lys_parent(start); while ((start_parent->nodetype == LYS_USES) && lys_parent(start_parent)) { start_parent = lys_parent(start_parent); } while (1) { sibling = NULL; while ((sibling = lys_getnext(sibling, start_parent, module, LYS_GETNEXT_WITHCHOICE | LYS_GETNEXT_WITHCASE | LYS_GETNEXT_PARENTUSES | LYS_GETNEXT_NOSTATECHECK))) { r = schema_nodeid_siblingcheck(sibling, module, mod_name, mod_name_len, name, nam_len); if (r == 0) { if (!id[0]) { if (!(sibling->nodetype & ret_nodetype)) { /* wrong node type, too bad */ continue; } *ret = sibling; return EXIT_SUCCESS; } start_parent = sibling; break; } else if (r == 1) { continue; } else { return -1; } } /* no match */ if (!sibling) { *ret = NULL; return EXIT_SUCCESS; } else if (no_innerlist && sibling->nodetype == LYS_LIST) { *ret = NULL; return -2; } if ((r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, NULL, NULL, 0)) < 1) { return ((id - nodeid) - r) + 1; } id += r; } /* cannot get here */ LOGINT(module->ctx); return -1; } /* choice default */ int resolve_choice_default_schema_nodeid(const char *nodeid, const struct lys_node *start, const struct lys_node **ret) { /* cannot actually be a path */ if (strchr(nodeid, '/')) { return -1; } return resolve_descendant_schema_nodeid(nodeid, start, LYS_NO_RPC_NOTIF_NODE, 0, ret); } /* uses, -1 error, EXIT_SUCCESS ok (but ret can still be NULL), >0 unexpected char on ret - 1 */ static int resolve_uses_schema_nodeid(const char *nodeid, const struct lys_node *start, const struct lys_node_grp **ret) { const struct lys_module *module; const char *mod_prefix, *name; int i, mod_prefix_len, nam_len; /* parse the identifier, it must be parsed on one call */ if (((i = parse_node_identifier(nodeid, &mod_prefix, &mod_prefix_len, &name, &nam_len, NULL, 0)) < 1) || nodeid[i]) { return -i + 1; } module = lyp_get_module(start->module, mod_prefix, mod_prefix_len, NULL, 0, 0); if (!module) { return -1; } if (module != lys_main_module(start->module)) { start = module->data; } *ret = lys_find_grouping_up(name, (struct lys_node *)start); return EXIT_SUCCESS; } int resolve_absolute_schema_nodeid(const char *nodeid, const struct lys_module *module, int ret_nodetype, const struct lys_node **ret) { const char *name, *mod_name, *id; const struct lys_node *sibling, *start_parent; int r, nam_len, mod_name_len, is_relative = -1; const struct lys_module *abs_start_mod; assert(nodeid && module && ret); assert(!(ret_nodetype & (LYS_USES | LYS_AUGMENT)) && ((ret_nodetype == LYS_GROUPING) || !(ret_nodetype & LYS_GROUPING))); id = nodeid; start_parent = NULL; if ((r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, NULL, NULL, 0)) < 1) { return ((id - nodeid) - r) + 1; } id += r; if (is_relative) { return -1; } abs_start_mod = lyp_get_module(module, NULL, 0, mod_name, mod_name_len, 0); if (!abs_start_mod) { return -1; } while (1) { sibling = NULL; while ((sibling = lys_getnext(sibling, start_parent, abs_start_mod, LYS_GETNEXT_WITHCHOICE | LYS_GETNEXT_WITHCASE | LYS_GETNEXT_WITHINOUT | LYS_GETNEXT_WITHGROUPING | LYS_GETNEXT_NOSTATECHECK))) { r = schema_nodeid_siblingcheck(sibling, module, mod_name, mod_name_len, name, nam_len); if (r == 0) { if (!id[0]) { if (!(sibling->nodetype & ret_nodetype)) { /* wrong node type, too bad */ continue; } *ret = sibling; return EXIT_SUCCESS; } start_parent = sibling; break; } else if (r == 1) { continue; } else { return -1; } } /* no match */ if (!sibling) { *ret = NULL; return EXIT_SUCCESS; } if ((r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, NULL, NULL, 0)) < 1) { return ((id - nodeid) - r) + 1; } id += r; } /* cannot get here */ LOGINT(module->ctx); return -1; } static int resolve_json_schema_list_predicate(const char *predicate, const struct lys_node_list *list, int *parsed) { const char *mod_name, *name; int mod_name_len, nam_len, has_predicate, i; struct lys_node *key; if (((i = parse_schema_json_predicate(predicate, &mod_name, &mod_name_len, &name, &nam_len, NULL, NULL, &has_predicate)) < 1) || !strncmp(name, ".", nam_len)) { LOGVAL(list->module->ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, predicate[-i], &predicate[-i]); return -1; } predicate += i; *parsed += i; if (!isdigit(name[0])) { for (i = 0; i < list->keys_size; ++i) { key = (struct lys_node *)list->keys[i]; if (!strncmp(key->name, name, nam_len) && !key->name[nam_len]) { break; } } if (i == list->keys_size) { LOGVAL(list->module->ctx, LYE_PATH_INKEY, LY_VLOG_NONE, NULL, name); return -1; } } /* more predicates? */ if (has_predicate) { return resolve_json_schema_list_predicate(predicate, list, parsed); } return 0; } /* cannot return LYS_GROUPING, LYS_AUGMENT, LYS_USES, logs directly */ const struct lys_node * resolve_json_nodeid(const char *nodeid, struct ly_ctx *ctx, const struct lys_node *start, int output) { char *str; const char *name, *mod_name, *id, *backup_mod_name = NULL, *yang_data_name = NULL; const struct lys_node *sibling, *start_parent, *parent; int r, nam_len, mod_name_len, is_relative = -1, has_predicate; int yang_data_name_len, backup_mod_name_len; /* resolved import module from the start module, it must match the next node-name-match sibling */ const struct lys_module *prefix_mod, *module, *prev_mod; assert(nodeid && (ctx || start)); if (!ctx) { ctx = start->module->ctx; } id = nodeid; if ((r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, NULL, NULL, 1)) < 1) { LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[-r], &id[-r]); return NULL; } if (name[0] == '#') { if (is_relative) { LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, '#', name); return NULL; } yang_data_name = name + 1; yang_data_name_len = nam_len - 1; backup_mod_name = mod_name; backup_mod_name_len = mod_name_len; id += r; } else { is_relative = -1; } if ((r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, &has_predicate, NULL, 0)) < 1) { LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[-r], &id[-r]); return NULL; } id += r; if (backup_mod_name) { mod_name = backup_mod_name; mod_name_len = backup_mod_name_len; } if (is_relative) { assert(start); start_parent = start; while (start_parent && (start_parent->nodetype == LYS_USES)) { start_parent = lys_parent(start_parent); } module = start->module; } else { if (!mod_name) { str = strndup(nodeid, (name + nam_len) - nodeid); LOGVAL(ctx, LYE_PATH_MISSMOD, LY_VLOG_STR, nodeid); free(str); return NULL; } str = strndup(mod_name, mod_name_len); module = ly_ctx_get_module(ctx, str, NULL, 1); free(str); if (!module) { str = strndup(nodeid, (mod_name + mod_name_len) - nodeid); LOGVAL(ctx, LYE_PATH_INMOD, LY_VLOG_STR, str); free(str); return NULL; } start_parent = NULL; if (yang_data_name) { start_parent = lyp_get_yang_data_template(module, yang_data_name, yang_data_name_len); if (!start_parent) { str = strndup(nodeid, (yang_data_name + yang_data_name_len) - nodeid); LOGVAL(ctx, LYE_PATH_INNODE, LY_VLOG_STR, str); free(str); return NULL; } } /* now it's as if there was no module name */ mod_name = NULL; mod_name_len = 0; } prev_mod = module; while (1) { sibling = NULL; while ((sibling = lys_getnext(sibling, start_parent, module, 0))) { /* name match */ if (sibling->name && !strncmp(name, sibling->name, nam_len) && !sibling->name[nam_len]) { /* output check */ for (parent = lys_parent(sibling); parent && !(parent->nodetype & (LYS_INPUT | LYS_OUTPUT)); parent = lys_parent(parent)); if (parent) { if (output && (parent->nodetype == LYS_INPUT)) { continue; } else if (!output && (parent->nodetype == LYS_OUTPUT)) { continue; } } /* module check */ if (mod_name) { /* will also find an augment module */ prefix_mod = ly_ctx_nget_module(ctx, mod_name, mod_name_len, NULL, 1); if (!prefix_mod) { str = strndup(nodeid, (mod_name + mod_name_len) - nodeid); LOGVAL(ctx, LYE_PATH_INMOD, LY_VLOG_STR, str); free(str); return NULL; } } else { prefix_mod = prev_mod; } if (prefix_mod != lys_node_module(sibling)) { continue; } /* do we have some predicates on it? */ if (has_predicate) { r = 0; if (sibling->nodetype & (LYS_LEAF | LYS_LEAFLIST)) { if ((r = parse_schema_json_predicate(id, NULL, NULL, NULL, NULL, NULL, NULL, &has_predicate)) < 1) { LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[-r], &id[-r]); return NULL; } } else if (sibling->nodetype == LYS_LIST) { if (resolve_json_schema_list_predicate(id, (const struct lys_node_list *)sibling, &r)) { return NULL; } } else { LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[0], id); return NULL; } id += r; } /* the result node? */ if (!id[0]) { return sibling; } /* move down the tree, if possible */ if (sibling->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA)) { LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[0], id); return NULL; } start_parent = sibling; /* update prev mod */ prev_mod = (start_parent->child ? lys_node_module(start_parent->child) : module); break; } } /* no match */ if (!sibling) { str = strndup(nodeid, (name + nam_len) - nodeid); LOGVAL(ctx, LYE_PATH_INNODE, LY_VLOG_STR, str); free(str); return NULL; } if ((r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, &has_predicate, NULL, 0)) < 1) { LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[-r], &id[-r]); return NULL; } id += r; } /* cannot get here */ LOGINT(ctx); return NULL; } static int resolve_partial_json_data_list_predicate(struct parsed_pred pp, struct lyd_node *node, int position) { uint16_t i; char *val_str; struct lyd_node_leaf_list *key; struct lys_node_list *slist; struct ly_ctx *ctx; assert(node); assert(node->schema->nodetype == LYS_LIST); assert(pp.len); ctx = node->schema->module->ctx; slist = (struct lys_node_list *)node->schema; /* is the predicate a number? */ if (isdigit(pp.pred[0].name[0])) { if (position == atoi(pp.pred[0].name)) { /* match */ return 0; } else { /* not a match */ return 1; } } key = (struct lyd_node_leaf_list *)node->child; if (!key) { /* it is not a position, so we need a key for it to be a match */ return 1; } /* go through all the keys */ for (i = 0; i < slist->keys_size; ++i) { if (strncmp(key->schema->name, pp.pred[i].name, pp.pred[i].nam_len) || key->schema->name[pp.pred[i].nam_len]) { LOGVAL(ctx, LYE_PATH_INKEY, LY_VLOG_NONE, NULL, pp.pred[i].name); return -1; } if (pp.pred[i].mod_name) { /* specific module, check that the found key is from that module */ if (strncmp(lyd_node_module((struct lyd_node *)key)->name, pp.pred[i].mod_name, pp.pred[i].mod_name_len) || lyd_node_module((struct lyd_node *)key)->name[pp.pred[i].mod_name_len]) { LOGVAL(ctx, LYE_PATH_INKEY, LY_VLOG_NONE, NULL, pp.pred[i].name); return -1; } /* but if the module is the same as the parent, it should have been omitted */ if (lyd_node_module((struct lyd_node *)key) == lyd_node_module(node)) { LOGVAL(ctx, LYE_PATH_INKEY, LY_VLOG_NONE, NULL, pp.pred[i].name); return -1; } } else { /* no module, so it must be the same as the list (parent) */ if (lyd_node_module((struct lyd_node *)key) != lyd_node_module(node)) { LOGVAL(ctx, LYE_PATH_INKEY, LY_VLOG_NONE, NULL, pp.pred[i].name); return -1; } } /* get canonical value */ val_str = lyd_make_canonical(key->schema, pp.pred[i].value, pp.pred[i].val_len); if (!val_str) { return -1; } /* value does not match */ if (strcmp(key->value_str, val_str)) { free(val_str); return 1; } free(val_str); key = (struct lyd_node_leaf_list *)key->next; } return 0; } /** * @brief get the closest parent of the node (or the node itself) identified by the nodeid (path) * * @param[in] nodeid Node data path to find * @param[in] llist_value If the \p nodeid identifies leaf-list, this is expected value of the leaf-list instance. * @param[in] options Bitmask of options flags, see @ref pathoptions. * @param[out] parsed Number of characters processed in \p id * @return The closes parent (or the node itself) from the path */ struct lyd_node * resolve_partial_json_data_nodeid(const char *nodeid, const char *llist_value, struct lyd_node *start, int options, int *parsed) { const char *id, *mod_name, *name, *data_val, *llval; int r, ret, mod_name_len, nam_len, is_relative = -1, list_instance_position; int has_predicate, last_parsed = 0, llval_len; struct lyd_node *sibling, *last_match = NULL; struct lyd_node_leaf_list *llist; const struct lys_module *prev_mod; struct ly_ctx *ctx; const struct lys_node *ssibling, *sparent; struct lys_node_list *slist; struct parsed_pred pp; assert(nodeid && start && parsed); memset(&pp, 0, sizeof pp); ctx = start->schema->module->ctx; id = nodeid; /* parse first nodeid in case it is yang-data extension */ if ((r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, NULL, NULL, 1)) < 1) { LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[-r], &id[-r]); goto error; } if (name[0] == '#') { if (is_relative) { LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, '#', name); goto error; } id += r; last_parsed = r; } else { is_relative = -1; } /* parse first nodeid */ if ((r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, &has_predicate, NULL, 0)) < 1) { LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[-r], &id[-r]); goto error; } id += r; /* add it to parsed only after the data node was actually found */ last_parsed += r; if (is_relative) { prev_mod = lyd_node_module(start); start = (start->schema->nodetype & (LYS_CONTAINER | LYS_LIST | LYS_RPC | LYS_ACTION | LYS_NOTIF)) ? start->child : NULL; } else { for (; start->parent; start = start->parent); prev_mod = lyd_node_module(start); } if (!start) { /* there are no siblings to search */ return NULL; } /* do not duplicate code, use predicate parsing from the loop */ goto parse_predicates; while (1) { /* find the correct schema node first */ ssibling = NULL; sparent = (start && start->parent) ? start->parent->schema : NULL; while ((ssibling = lys_getnext(ssibling, sparent, prev_mod, 0))) { /* skip invalid input/output nodes */ if (sparent && (sparent->nodetype & (LYS_RPC | LYS_ACTION))) { if (options & LYD_PATH_OPT_OUTPUT) { if (lys_parent(ssibling)->nodetype == LYS_INPUT) { continue; } } else { if (lys_parent(ssibling)->nodetype == LYS_OUTPUT) { continue; } } } if (!schema_nodeid_siblingcheck(ssibling, prev_mod, mod_name, mod_name_len, name, nam_len)) { break; } } if (!ssibling) { /* there is not even such a schema node */ free(pp.pred); return last_match; } pp.schema = ssibling; /* unify leaf-list value - it is possible to specify last-node value as both a predicate or parameter if * is a leaf-list, unify both cases and the value will in both cases be in the predicate structure */ if (!id[0] && !pp.len && (ssibling->nodetype == LYS_LEAFLIST)) { pp.len = 1; pp.pred = calloc(1, sizeof *pp.pred); LY_CHECK_ERR_GOTO(!pp.pred, LOGMEM(ctx), error); pp.pred[0].name = "."; pp.pred[0].nam_len = 1; pp.pred[0].value = (llist_value ? llist_value : ""); pp.pred[0].val_len = strlen(pp.pred[0].value); } if (ssibling->nodetype & (LYS_LEAFLIST | LYS_LEAF)) { /* check leaf/leaf-list predicate */ if (pp.len > 1) { LOGVAL(ctx, LYE_PATH_PREDTOOMANY, LY_VLOG_NONE, NULL); goto error; } else if (pp.len) { if ((pp.pred[0].name[0] != '.') || (pp.pred[0].nam_len != 1)) { LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, pp.pred[0].name[0], pp.pred[0].name); goto error; } if ((((struct lys_node_leaf *)ssibling)->type.base == LY_TYPE_IDENT) && !strnchr(pp.pred[0].value, ':', pp.pred[0].val_len)) { LOGVAL(ctx, LYE_PATH_INIDENTREF, LY_VLOG_LYS, ssibling, pp.pred[0].val_len, pp.pred[0].value); goto error; } } } else if (ssibling->nodetype == LYS_LIST) { /* list should have predicates for all the keys or position */ slist = (struct lys_node_list *)ssibling; if (!pp.len) { /* none match */ return last_match; } else if (!isdigit(pp.pred[0].name[0])) { /* list predicate is not a position, so there must be all the keys */ if (pp.len > slist->keys_size) { LOGVAL(ctx, LYE_PATH_PREDTOOMANY, LY_VLOG_NONE, NULL); goto error; } else if (pp.len < slist->keys_size) { LOGVAL(ctx, LYE_PATH_MISSKEY, LY_VLOG_NONE, NULL, slist->keys[pp.len]->name); goto error; } /* check that all identityrefs have module name, otherwise the hash of the list instance will never match!! */ for (r = 0; r < pp.len; ++r) { if ((slist->keys[r]->type.base == LY_TYPE_IDENT) && !strnchr(pp.pred[r].value, ':', pp.pred[r].val_len)) { LOGVAL(ctx, LYE_PATH_INIDENTREF, LY_VLOG_LYS, slist->keys[r], pp.pred[r].val_len, pp.pred[r].value); goto error; } } } } else if (pp.pred) { /* no other nodes allow predicates */ LOGVAL(ctx, LYE_PATH_PREDTOOMANY, LY_VLOG_NONE, NULL); goto error; } #ifdef LY_ENABLED_CACHE /* we will not be matching keyless lists or state leaf-lists this way */ if (start->parent && start->parent->ht && ((pp.schema->nodetype != LYS_LIST) || ((struct lys_node_list *)pp.schema)->keys_size) && ((pp.schema->nodetype != LYS_LEAFLIST) || (pp.schema->flags & LYS_CONFIG_W))) { sibling = resolve_json_data_node_hash(start->parent, pp); } else #endif { list_instance_position = 0; LY_TREE_FOR(start, sibling) { /* RPC/action data check, return simply invalid argument, because the data tree is invalid */ if (lys_parent(sibling->schema)) { if (options & LYD_PATH_OPT_OUTPUT) { if (lys_parent(sibling->schema)->nodetype == LYS_INPUT) { LOGERR(ctx, LY_EINVAL, "Provided data tree includes some RPC input nodes (%s).", sibling->schema->name); goto error; } } else { if (lys_parent(sibling->schema)->nodetype == LYS_OUTPUT) { LOGERR(ctx, LY_EINVAL, "Provided data tree includes some RPC output nodes (%s).", sibling->schema->name); goto error; } } } if (sibling->schema != ssibling) { /* wrong schema node */ continue; } /* leaf-list, did we find it with the correct value or not? */ if (ssibling->nodetype == LYS_LEAFLIST) { if (ssibling->flags & LYS_CONFIG_R) { /* state leaf-lists will never match */ continue; } llist = (struct lyd_node_leaf_list *)sibling; /* get the expected leaf-list value */ llval = NULL; llval_len = 0; if (pp.pred) { /* it was already checked that it is correct */ llval = pp.pred[0].value; llval_len = pp.pred[0].val_len; } /* make value canonical (remove module name prefix) unless it was specified with it */ if (llval && !strchr(llval, ':') && (llist->value_type & LY_TYPE_IDENT) && !strncmp(llist->value_str, lyd_node_module(sibling)->name, strlen(lyd_node_module(sibling)->name)) && (llist->value_str[strlen(lyd_node_module(sibling)->name)] == ':')) { data_val = llist->value_str + strlen(lyd_node_module(sibling)->name) + 1; } else { data_val = llist->value_str; } if ((!llval && data_val && data_val[0]) || (llval && (strncmp(llval, data_val, llval_len) || data_val[llval_len]))) { continue; } } else if (ssibling->nodetype == LYS_LIST) { /* list, we likely need predicates'n'stuff then, but if without a predicate, we are always creating it */ ++list_instance_position; ret = resolve_partial_json_data_list_predicate(pp, sibling, list_instance_position); if (ret == -1) { goto error; } else if (ret == 1) { /* this list instance does not match */ continue; } } break; } } /* no match, return last match */ if (!sibling) { free(pp.pred); return last_match; } /* we found a next matching node */ *parsed += last_parsed; last_match = sibling; prev_mod = lyd_node_module(sibling); /* the result node? */ if (!id[0]) { free(pp.pred); return last_match; } /* move down the tree, if possible, and continue */ if (ssibling->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA)) { /* there can be no children even through expected, error */ LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[0], id); goto error; } else if (!sibling->child) { /* there could be some children, but are not, return what we found so far */ free(pp.pred); return last_match; } start = sibling->child; /* parse nodeid */ if ((r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, &has_predicate, NULL, 0)) < 1) { LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[-r], &id[-r]); goto error; } id += r; last_parsed = r; parse_predicates: /* parse all the predicates */ free(pp.pred); pp.schema = NULL; pp.len = 0; pp.pred = NULL; while (has_predicate) { ++pp.len; pp.pred = ly_realloc(pp.pred, pp.len * sizeof *pp.pred); LY_CHECK_ERR_GOTO(!pp.pred, LOGMEM(ctx), error); if ((r = parse_schema_json_predicate(id, &pp.pred[pp.len - 1].mod_name, &pp.pred[pp.len - 1].mod_name_len, &pp.pred[pp.len - 1].name, &pp.pred[pp.len - 1].nam_len, &pp.pred[pp.len - 1].value, &pp.pred[pp.len - 1].val_len, &has_predicate)) < 1) { LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[0], id); goto error; } id += r; last_parsed += r; } } error: *parsed = -1; free(pp.pred); return NULL; } /** * @brief Resolves length or range intervals. Does not log. * Syntax is assumed to be correct, *ret MUST be NULL. * * @param[in] ctx Context for errors. * @param[in] str_restr Restriction as a string. * @param[in] type Type of the restriction. * @param[out] ret Final interval structure that starts with * the interval of the initial type, continues with intervals * of any superior types derived from the initial one, and * finishes with intervals from our \p type. * * @return EXIT_SUCCESS on succes, -1 on error. */ int resolve_len_ran_interval(struct ly_ctx *ctx, const char *str_restr, struct lys_type *type, struct len_ran_intv **ret) { /* 0 - unsigned, 1 - signed, 2 - floating point */ int kind; int64_t local_smin = 0, local_smax = 0, local_fmin, local_fmax; uint64_t local_umin, local_umax = 0; uint8_t local_fdig = 0; const char *seg_ptr, *ptr; struct len_ran_intv *local_intv = NULL, *tmp_local_intv = NULL, *tmp_intv, *intv = NULL; switch (type->base) { case LY_TYPE_BINARY: kind = 0; local_umin = 0; local_umax = 18446744073709551615UL; if (!str_restr && type->info.binary.length) { str_restr = type->info.binary.length->expr; } break; case LY_TYPE_DEC64: kind = 2; local_fmin = __INT64_C(-9223372036854775807) - __INT64_C(1); local_fmax = __INT64_C(9223372036854775807); local_fdig = type->info.dec64.dig; if (!str_restr && type->info.dec64.range) { str_restr = type->info.dec64.range->expr; } break; case LY_TYPE_INT8: kind = 1; local_smin = __INT64_C(-128); local_smax = __INT64_C(127); if (!str_restr && type->info.num.range) { str_restr = type->info.num.range->expr; } break; case LY_TYPE_INT16: kind = 1; local_smin = __INT64_C(-32768); local_smax = __INT64_C(32767); if (!str_restr && type->info.num.range) { str_restr = type->info.num.range->expr; } break; case LY_TYPE_INT32: kind = 1; local_smin = __INT64_C(-2147483648); local_smax = __INT64_C(2147483647); if (!str_restr && type->info.num.range) { str_restr = type->info.num.range->expr; } break; case LY_TYPE_INT64: kind = 1; local_smin = __INT64_C(-9223372036854775807) - __INT64_C(1); local_smax = __INT64_C(9223372036854775807); if (!str_restr && type->info.num.range) { str_restr = type->info.num.range->expr; } break; case LY_TYPE_UINT8: kind = 0; local_umin = __UINT64_C(0); local_umax = __UINT64_C(255); if (!str_restr && type->info.num.range) { str_restr = type->info.num.range->expr; } break; case LY_TYPE_UINT16: kind = 0; local_umin = __UINT64_C(0); local_umax = __UINT64_C(65535); if (!str_restr && type->info.num.range) { str_restr = type->info.num.range->expr; } break; case LY_TYPE_UINT32: kind = 0; local_umin = __UINT64_C(0); local_umax = __UINT64_C(4294967295); if (!str_restr && type->info.num.range) { str_restr = type->info.num.range->expr; } break; case LY_TYPE_UINT64: kind = 0; local_umin = __UINT64_C(0); local_umax = __UINT64_C(18446744073709551615); if (!str_restr && type->info.num.range) { str_restr = type->info.num.range->expr; } break; case LY_TYPE_STRING: kind = 0; local_umin = __UINT64_C(0); local_umax = __UINT64_C(18446744073709551615); if (!str_restr && type->info.str.length) { str_restr = type->info.str.length->expr; } break; default: return -1; } /* process superior types */ if (type->der) { if (resolve_len_ran_interval(ctx, NULL, &type->der->type, &intv)) { return -1; } assert(!intv || (intv->kind == kind)); } if (!str_restr) { /* we do not have any restriction, return superior ones */ *ret = intv; return EXIT_SUCCESS; } /* adjust local min and max */ if (intv) { tmp_intv = intv; if (kind == 0) { local_umin = tmp_intv->value.uval.min; } else if (kind == 1) { local_smin = tmp_intv->value.sval.min; } else if (kind == 2) { local_fmin = tmp_intv->value.fval.min; } while (tmp_intv->next) { tmp_intv = tmp_intv->next; } if (kind == 0) { local_umax = tmp_intv->value.uval.max; } else if (kind == 1) { local_smax = tmp_intv->value.sval.max; } else if (kind == 2) { local_fmax = tmp_intv->value.fval.max; } } /* finally parse our restriction */ seg_ptr = str_restr; tmp_intv = NULL; while (1) { if (!tmp_local_intv) { assert(!local_intv); local_intv = malloc(sizeof *local_intv); tmp_local_intv = local_intv; } else { tmp_local_intv->next = malloc(sizeof *tmp_local_intv); tmp_local_intv = tmp_local_intv->next; } LY_CHECK_ERR_GOTO(!tmp_local_intv, LOGMEM(ctx), error); tmp_local_intv->kind = kind; tmp_local_intv->type = type; tmp_local_intv->next = NULL; /* min */ ptr = seg_ptr; while (isspace(ptr[0])) { ++ptr; } if (isdigit(ptr[0]) || (ptr[0] == '+') || (ptr[0] == '-')) { if (kind == 0) { tmp_local_intv->value.uval.min = strtoull(ptr, (char **)&ptr, 10); } else if (kind == 1) { tmp_local_intv->value.sval.min = strtoll(ptr, (char **)&ptr, 10); } else if (kind == 2) { if (parse_range_dec64(&ptr, local_fdig, &tmp_local_intv->value.fval.min)) { LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, ptr, "range"); goto error; } } } else if (!strncmp(ptr, "min", 3)) { if (kind == 0) { tmp_local_intv->value.uval.min = local_umin; } else if (kind == 1) { tmp_local_intv->value.sval.min = local_smin; } else if (kind == 2) { tmp_local_intv->value.fval.min = local_fmin; } ptr += 3; } else if (!strncmp(ptr, "max", 3)) { if (kind == 0) { tmp_local_intv->value.uval.min = local_umax; } else if (kind == 1) { tmp_local_intv->value.sval.min = local_smax; } else if (kind == 2) { tmp_local_intv->value.fval.min = local_fmax; } ptr += 3; } else { goto error; } while (isspace(ptr[0])) { ptr++; } /* no interval or interval */ if ((ptr[0] == '|') || !ptr[0]) { if (kind == 0) { tmp_local_intv->value.uval.max = tmp_local_intv->value.uval.min; } else if (kind == 1) { tmp_local_intv->value.sval.max = tmp_local_intv->value.sval.min; } else if (kind == 2) { tmp_local_intv->value.fval.max = tmp_local_intv->value.fval.min; } } else if (!strncmp(ptr, "..", 2)) { /* skip ".." */ ptr += 2; while (isspace(ptr[0])) { ++ptr; } /* max */ if (isdigit(ptr[0]) || (ptr[0] == '+') || (ptr[0] == '-')) { if (kind == 0) { tmp_local_intv->value.uval.max = strtoull(ptr, (char **)&ptr, 10); } else if (kind == 1) { tmp_local_intv->value.sval.max = strtoll(ptr, (char **)&ptr, 10); } else if (kind == 2) { if (parse_range_dec64(&ptr, local_fdig, &tmp_local_intv->value.fval.max)) { LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, ptr, "range"); goto error; } } } else if (!strncmp(ptr, "max", 3)) { if (kind == 0) { tmp_local_intv->value.uval.max = local_umax; } else if (kind == 1) { tmp_local_intv->value.sval.max = local_smax; } else if (kind == 2) { tmp_local_intv->value.fval.max = local_fmax; } } else { goto error; } } else { goto error; } /* check min and max in correct order */ if (kind == 0) { /* current segment */ if (tmp_local_intv->value.uval.min > tmp_local_intv->value.uval.max) { goto error; } if (tmp_local_intv->value.uval.min < local_umin || tmp_local_intv->value.uval.max > local_umax) { goto error; } /* segments sholud be ascending order */ if (tmp_intv && (tmp_intv->value.uval.max >= tmp_local_intv->value.uval.min)) { goto error; } } else if (kind == 1) { if (tmp_local_intv->value.sval.min > tmp_local_intv->value.sval.max) { goto error; } if (tmp_local_intv->value.sval.min < local_smin || tmp_local_intv->value.sval.max > local_smax) { goto error; } if (tmp_intv && (tmp_intv->value.sval.max >= tmp_local_intv->value.sval.min)) { goto error; } } else if (kind == 2) { if (tmp_local_intv->value.fval.min > tmp_local_intv->value.fval.max) { goto error; } if (tmp_local_intv->value.fval.min < local_fmin || tmp_local_intv->value.fval.max > local_fmax) { goto error; } if (tmp_intv && (tmp_intv->value.fval.max >= tmp_local_intv->value.fval.min)) { /* fraction-digits value is always the same (it cannot be changed in derived types) */ goto error; } } /* next segment (next OR) */ seg_ptr = strchr(seg_ptr, '|'); if (!seg_ptr) { break; } seg_ptr++; tmp_intv = tmp_local_intv; } /* check local restrictions against superior ones */ if (intv) { tmp_intv = intv; tmp_local_intv = local_intv; while (tmp_local_intv && tmp_intv) { /* reuse local variables */ if (kind == 0) { local_umin = tmp_local_intv->value.uval.min; local_umax = tmp_local_intv->value.uval.max; /* it must be in this interval */ if ((local_umin >= tmp_intv->value.uval.min) && (local_umin <= tmp_intv->value.uval.max)) { /* this interval is covered, next one */ if (local_umax <= tmp_intv->value.uval.max) { tmp_local_intv = tmp_local_intv->next; continue; /* ascending order of restrictions -> fail */ } else { goto error; } } } else if (kind == 1) { local_smin = tmp_local_intv->value.sval.min; local_smax = tmp_local_intv->value.sval.max; if ((local_smin >= tmp_intv->value.sval.min) && (local_smin <= tmp_intv->value.sval.max)) { if (local_smax <= tmp_intv->value.sval.max) { tmp_local_intv = tmp_local_intv->next; continue; } else { goto error; } } } else if (kind == 2) { local_fmin = tmp_local_intv->value.fval.min; local_fmax = tmp_local_intv->value.fval.max; if ((dec64cmp(local_fmin, local_fdig, tmp_intv->value.fval.min, local_fdig) > -1) && (dec64cmp(local_fmin, local_fdig, tmp_intv->value.fval.max, local_fdig) < 1)) { if (dec64cmp(local_fmax, local_fdig, tmp_intv->value.fval.max, local_fdig) < 1) { tmp_local_intv = tmp_local_intv->next; continue; } else { goto error; } } } tmp_intv = tmp_intv->next; } /* some interval left uncovered -> fail */ if (tmp_local_intv) { goto error; } } /* append the local intervals to all the intervals of the superior types, return it all */ if (intv) { for (tmp_intv = intv; tmp_intv->next; tmp_intv = tmp_intv->next); tmp_intv->next = local_intv; } else { intv = local_intv; } *ret = intv; return EXIT_SUCCESS; error: while (intv) { tmp_intv = intv->next; free(intv); intv = tmp_intv; } while (local_intv) { tmp_local_intv = local_intv->next; free(local_intv); local_intv = tmp_local_intv; } return -1; } static int resolve_superior_type_check(struct lys_type *type) { uint32_t i; if (type->base == LY_TYPE_DER) { /* check that the referenced typedef is resolved */ return EXIT_FAILURE; } else if (type->base == LY_TYPE_UNION) { /* check that all union types are resolved */ for (i = 0; i < type->info.uni.count; ++i) { if (resolve_superior_type_check(&type->info.uni.types[i])) { return EXIT_FAILURE; } } } else if (type->base == LY_TYPE_LEAFREF) { /* check there is path in some derived type */ while (!type->info.lref.path) { assert(type->der); type = &type->der->type; } } return EXIT_SUCCESS; } /** * @brief Resolve a typedef, return only resolved typedefs if derived. If leafref, it must be * resolved for this function to return it. Does not log. * * @param[in] name Typedef name. * @param[in] mod_name Typedef name module name. * @param[in] module Main module. * @param[in] parent Parent of the resolved type definition. * @param[out] ret Pointer to the resolved typedef. Can be NULL. * * @return EXIT_SUCCESS on success, EXIT_FAILURE on forward reference, -1 on error. */ int resolve_superior_type(const char *name, const char *mod_name, const struct lys_module *module, const struct lys_node *parent, struct lys_tpdf **ret) { int i, j; struct lys_tpdf *tpdf, *match; int tpdf_size; if (!mod_name) { /* no prefix, try built-in types */ for (i = 1; i < LY_DATA_TYPE_COUNT; i++) { if (!strcmp(ly_types[i]->name, name)) { if (ret) { *ret = ly_types[i]; } return EXIT_SUCCESS; } } } else { if (!strcmp(mod_name, module->name)) { /* prefix refers to the current module, ignore it */ mod_name = NULL; } } if (!mod_name && parent) { /* search in local typedefs */ while (parent) { switch (parent->nodetype) { case LYS_CONTAINER: tpdf_size = ((struct lys_node_container *)parent)->tpdf_size; tpdf = ((struct lys_node_container *)parent)->tpdf; break; case LYS_LIST: tpdf_size = ((struct lys_node_list *)parent)->tpdf_size; tpdf = ((struct lys_node_list *)parent)->tpdf; break; case LYS_GROUPING: tpdf_size = ((struct lys_node_grp *)parent)->tpdf_size; tpdf = ((struct lys_node_grp *)parent)->tpdf; break; case LYS_RPC: case LYS_ACTION: tpdf_size = ((struct lys_node_rpc_action *)parent)->tpdf_size; tpdf = ((struct lys_node_rpc_action *)parent)->tpdf; break; case LYS_NOTIF: tpdf_size = ((struct lys_node_notif *)parent)->tpdf_size; tpdf = ((struct lys_node_notif *)parent)->tpdf; break; case LYS_INPUT: case LYS_OUTPUT: tpdf_size = ((struct lys_node_inout *)parent)->tpdf_size; tpdf = ((struct lys_node_inout *)parent)->tpdf; break; default: parent = lys_parent(parent); continue; } for (i = 0; i < tpdf_size; i++) { if (!strcmp(tpdf[i].name, name)) { match = &tpdf[i]; goto check_typedef; } } parent = lys_parent(parent); } } else { /* get module where to search */ module = lyp_get_module(module, NULL, 0, mod_name, 0, 0); if (!module) { return -1; } } /* search in top level typedefs */ for (i = 0; i < module->tpdf_size; i++) { if (!strcmp(module->tpdf[i].name, name)) { match = &module->tpdf[i]; goto check_typedef; } } /* search in submodules */ for (i = 0; i < module->inc_size && module->inc[i].submodule; i++) { for (j = 0; j < module->inc[i].submodule->tpdf_size; j++) { if (!strcmp(module->inc[i].submodule->tpdf[j].name, name)) { match = &module->inc[i].submodule->tpdf[j]; goto check_typedef; } } } return EXIT_FAILURE; check_typedef: if (resolve_superior_type_check(&match->type)) { return EXIT_FAILURE; } if (ret) { *ret = match; } return EXIT_SUCCESS; } /** * @brief Check the default \p value of the \p type. Logs directly. * * @param[in] type Type definition to use. * @param[in] value Default value to check. * @param[in] module Type module. * * @return EXIT_SUCCESS on success, EXIT_FAILURE on forward reference, -1 on error. */ static int check_default(struct lys_type *type, const char **value, struct lys_module *module, int tpdf) { struct lys_tpdf *base_tpdf = NULL; struct lyd_node_leaf_list node; const char *dflt = NULL; char *s; int ret = EXIT_SUCCESS, r; struct ly_ctx *ctx = module->ctx; assert(value); memset(&node, 0, sizeof node); if (type->base <= LY_TYPE_DER) { /* the type was not resolved yet, nothing to do for now */ ret = EXIT_FAILURE; goto cleanup; } else if (!tpdf && !module->implemented) { /* do not check defaults in not implemented module's data */ goto cleanup; } else if (tpdf && !module->implemented && type->base == LY_TYPE_IDENT) { /* identityrefs are checked when instantiated in data instead of typedef, * but in typedef the value has to be modified to include the prefix */ if (*value) { if (strchr(*value, ':')) { dflt = transform_schema2json(module, *value); } else { /* default prefix of the module where the typedef is defined */ if (asprintf(&s, "%s:%s", lys_main_module(module)->name, *value) == -1) { LOGMEM(ctx); ret = -1; goto cleanup; } dflt = lydict_insert_zc(ctx, s); } lydict_remove(ctx, *value); *value = dflt; dflt = NULL; } goto cleanup; } else if (type->base == LY_TYPE_LEAFREF && tpdf) { /* leafref in typedef cannot be checked */ goto cleanup; } dflt = lydict_insert(ctx, *value, 0); if (!dflt) { /* we do not have a new default value, so is there any to check even, in some base type? */ for (base_tpdf = type->der; base_tpdf->type.der; base_tpdf = base_tpdf->type.der) { if (base_tpdf->dflt) { dflt = lydict_insert(ctx, base_tpdf->dflt, 0); break; } } if (!dflt) { /* no default value, nothing to check, all is well */ goto cleanup; } /* so there is a default value in a base type, but can the default value be no longer valid (did we define some new restrictions)? */ switch (type->base) { case LY_TYPE_IDENT: if (lys_main_module(base_tpdf->type.parent->module)->implemented) { goto cleanup; } else { /* check the default value from typedef, but use also the typedef's module * due to possible searching in imported modules which is expected in * typedef's module instead of module where the typedef is used */ module = base_tpdf->module; } break; case LY_TYPE_INST: case LY_TYPE_LEAFREF: case LY_TYPE_BOOL: case LY_TYPE_EMPTY: /* these have no restrictions, so we would do the exact same work as the unres in the base typedef */ goto cleanup; case LY_TYPE_BITS: /* the default value must match the restricted list of values, if the type was restricted */ if (type->info.bits.count) { break; } goto cleanup; case LY_TYPE_ENUM: /* the default value must match the restricted list of values, if the type was restricted */ if (type->info.enums.count) { break; } goto cleanup; case LY_TYPE_DEC64: if (type->info.dec64.range) { break; } goto cleanup; case LY_TYPE_BINARY: if (type->info.binary.length) { break; } goto cleanup; case LY_TYPE_INT8: case LY_TYPE_INT16: case LY_TYPE_INT32: case LY_TYPE_INT64: case LY_TYPE_UINT8: case LY_TYPE_UINT16: case LY_TYPE_UINT32: case LY_TYPE_UINT64: if (type->info.num.range) { break; } goto cleanup; case LY_TYPE_STRING: if (type->info.str.length || type->info.str.patterns) { break; } goto cleanup; case LY_TYPE_UNION: /* way too much trouble learning whether we need to check the default again, so just do it */ break; default: LOGINT(ctx); ret = -1; goto cleanup; } } else if (type->base == LY_TYPE_EMPTY) { LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_NONE, NULL, "default", type->parent->name); LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "The \"empty\" data type cannot have a default value."); ret = -1; goto cleanup; } /* dummy leaf */ memset(&node, 0, sizeof node); node.value_str = lydict_insert(ctx, dflt, 0); node.value_type = type->base; if (tpdf) { node.schema = calloc(1, sizeof (struct lys_node_leaf)); if (!node.schema) { LOGMEM(ctx); ret = -1; goto cleanup; } r = asprintf((char **)&node.schema->name, "typedef-%s-default", ((struct lys_tpdf *)type->parent)->name); if (r == -1) { LOGMEM(ctx); ret = -1; goto cleanup; } node.schema->module = module; memcpy(&((struct lys_node_leaf *)node.schema)->type, type, sizeof *type); } else { node.schema = (struct lys_node *)type->parent; } if (type->base == LY_TYPE_LEAFREF) { if (!type->info.lref.target) { ret = EXIT_FAILURE; LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Default value \"%s\" cannot be checked in an unresolved leafref.", dflt); goto cleanup; } ret = check_default(&type->info.lref.target->type, &dflt, module, 0); if (!ret) { /* adopt possibly changed default value to its canonical form */ if (*value) { lydict_remove(ctx, *value); *value = dflt; dflt = NULL; } } } else { if (!lyp_parse_value(type, &node.value_str, NULL, &node, NULL, module, 1, 1, 0)) { /* possible forward reference */ ret = EXIT_FAILURE; if (base_tpdf) { /* default value is defined in some base typedef */ if ((type->base == LY_TYPE_BITS && type->der->type.der) || (type->base == LY_TYPE_ENUM && type->der->type.der)) { /* we have refined bits/enums */ LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid value \"%s\" of the default statement inherited to \"%s\" from \"%s\" base type.", dflt, type->parent->name, base_tpdf->name); } } } else { /* success - adopt canonical form from the node into the default value */ if (!ly_strequal(dflt, node.value_str, 1)) { /* this can happen only if we have non-inherited default value, * inherited default values are already in canonical form */ assert(ly_strequal(dflt, *value, 1)); lydict_remove(ctx, *value); *value = node.value_str; node.value_str = NULL; } } } cleanup: lyd_free_value(node.value, node.value_type, node.value_flags, type, node.value_str, NULL, NULL, NULL); lydict_remove(ctx, node.value_str); if (tpdf && node.schema) { free((char *)node.schema->name); free(node.schema); } lydict_remove(ctx, dflt); return ret; } /** * @brief Check a key for mandatory attributes. Logs directly. * * @param[in] key The key to check. * @param[in] flags What flags to check. * @param[in] list The list of all the keys. * @param[in] index Index of the key in the key list. * @param[in] name The name of the keys. * @param[in] len The name length. * * @return EXIT_SUCCESS on success, -1 on error. */ static int check_key(struct lys_node_list *list, int index, const char *name, int len) { struct lys_node_leaf *key = list->keys[index]; char *dup = NULL; int j; struct ly_ctx *ctx = list->module->ctx; /* existence */ if (!key) { if (name[len] != '\0') { dup = strdup(name); LY_CHECK_ERR_RETURN(!dup, LOGMEM(ctx), -1); dup[len] = '\0'; name = dup; } LOGVAL(ctx, LYE_KEY_MISS, LY_VLOG_LYS, list, name); free(dup); return -1; } /* uniqueness */ for (j = index - 1; j >= 0; j--) { if (key == list->keys[j]) { LOGVAL(ctx, LYE_KEY_DUP, LY_VLOG_LYS, list, key->name); return -1; } } /* key is a leaf */ if (key->nodetype != LYS_LEAF) { LOGVAL(ctx, LYE_KEY_NLEAF, LY_VLOG_LYS, list, key->name); return -1; } /* type of the leaf is not built-in empty */ if (key->type.base == LY_TYPE_EMPTY && key->module->version < LYS_VERSION_1_1) { LOGVAL(ctx, LYE_KEY_TYPE, LY_VLOG_LYS, list, key->name); return -1; } /* config attribute is the same as of the list */ if ((key->flags & LYS_CONFIG_MASK) && (list->flags & LYS_CONFIG_MASK) && ((list->flags & LYS_CONFIG_MASK) != (key->flags & LYS_CONFIG_MASK))) { LOGVAL(ctx, LYE_KEY_CONFIG, LY_VLOG_LYS, list, key->name); return -1; } /* key is not placed from augment */ if (key->parent->nodetype == LYS_AUGMENT) { LOGVAL(ctx, LYE_KEY_MISS, LY_VLOG_LYS, key, key->name); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Key inserted from augment."); return -1; } /* key is not when/if-feature -conditional */ j = 0; if (key->when || (key->iffeature_size && (j = 1))) { LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, key, j ? "if-feature" : "when", "leaf"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Key definition cannot depend on a \"%s\" condition.", j ? "if-feature" : "when"); return -1; } return EXIT_SUCCESS; } /** * @brief Resolve (test the target exists) unique. Logs directly. * * @param[in] parent The parent node of the unique structure. * @param[in] uniq_str_path One path from the unique string. * * @return EXIT_SUCCESS on succes, EXIT_FAILURE on forward reference, -1 on error. */ int resolve_unique(struct lys_node *parent, const char *uniq_str_path, uint8_t *trg_type) { int rc; const struct lys_node *leaf = NULL; struct ly_ctx *ctx = parent->module->ctx; rc = resolve_descendant_schema_nodeid(uniq_str_path, *lys_child(parent, LYS_LEAF), LYS_LEAF, 1, &leaf); if (rc || !leaf) { if (rc) { LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, parent, uniq_str_path, "unique"); if (rc > 0) { LOGVAL(ctx, LYE_INCHAR, LY_VLOG_PREV, NULL, uniq_str_path[rc - 1], &uniq_str_path[rc - 1]); } else if (rc == -2) { LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Unique argument references list."); } rc = -1; } else { LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, parent, uniq_str_path, "unique"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Target leaf not found."); rc = EXIT_FAILURE; } goto error; } if (leaf->nodetype != LYS_LEAF) { LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, parent, uniq_str_path, "unique"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Target is not a leaf."); return -1; } /* check status */ if (parent->nodetype != LYS_EXT && lyp_check_status(parent->flags, parent->module, parent->name, leaf->flags, leaf->module, leaf->name, leaf)) { return -1; } /* check that all unique's targets are of the same config type */ if (*trg_type) { if (((*trg_type == 1) && (leaf->flags & LYS_CONFIG_R)) || ((*trg_type == 2) && (leaf->flags & LYS_CONFIG_W))) { LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, parent, uniq_str_path, "unique"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Leaf \"%s\" referenced in unique statement is config %s, but previous referenced leaf is config %s.", uniq_str_path, *trg_type == 1 ? "false" : "true", *trg_type == 1 ? "true" : "false"); return -1; } } else { /* first unique */ if (leaf->flags & LYS_CONFIG_W) { *trg_type = 1; } else { *trg_type = 2; } } /* set leaf's unique flag */ ((struct lys_node_leaf *)leaf)->flags |= LYS_UNIQUE; return EXIT_SUCCESS; error: return rc; } void unres_data_del(struct unres_data *unres, uint32_t i) { /* there are items after the one deleted */ if (i+1 < unres->count) { /* we only move the data, memory is left allocated, why bother */ memmove(&unres->node[i], &unres->node[i+1], (unres->count-(i+1)) * sizeof *unres->node); /* deleting the last item */ } else if (i == 0) { free(unres->node); unres->node = NULL; } /* if there are no items after and it is not the last one, just move the counter */ --unres->count; } /** * @brief Resolve (find) a data node from a specific module. Does not log. * * @param[in] mod Module to search in. * @param[in] name Name of the data node. * @param[in] nam_len Length of the name. * @param[in] start Data node to start the search from. * @param[in,out] parents Resolved nodes. If there are some parents, * they are replaced (!!) with the resolvents. * * @return EXIT_SUCCESS on success, EXIT_FAILURE on forward reference, -1 on error. */ static int resolve_data(const struct lys_module *mod, const char *name, int nam_len, struct lyd_node *start, struct unres_data *parents) { struct lyd_node *node; int flag; uint32_t i; if (!parents->count) { parents->count = 1; parents->node = malloc(sizeof *parents->node); LY_CHECK_ERR_RETURN(!parents->node, LOGMEM(mod->ctx), -1); parents->node[0] = NULL; } for (i = 0; i < parents->count;) { if (parents->node[i] && (parents->node[i]->schema->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA))) { /* skip */ ++i; continue; } flag = 0; LY_TREE_FOR(parents->node[i] ? parents->node[i]->child : start, node) { if (lyd_node_module(node) == mod && !strncmp(node->schema->name, name, nam_len) && node->schema->name[nam_len] == '\0') { /* matching target */ if (!flag) { /* put node instead of the current parent */ parents->node[i] = node; flag = 1; } else { /* multiple matching, so create a new node */ ++parents->count; parents->node = ly_realloc(parents->node, parents->count * sizeof *parents->node); LY_CHECK_ERR_RETURN(!parents->node, LOGMEM(mod->ctx), EXIT_FAILURE); parents->node[parents->count-1] = node; ++i; } } } if (!flag) { /* remove item from the parents list */ unres_data_del(parents, i); } else { ++i; } } return parents->count ? EXIT_SUCCESS : EXIT_FAILURE; } static int resolve_schema_leafref_valid_dep_flag(const struct lys_node *op_node, const struct lys_module *local_mod, const struct lys_node *first_node, int abs_path) { int dep1, dep2; const struct lys_node *node; if (!op_node) { /* leafref pointing to a different module */ if (local_mod != lys_node_module(first_node)) { return 1; } } else if (lys_parent(op_node)) { /* inner operation (notif/action) */ if (abs_path) { return 1; } else { /* compare depth of both nodes */ for (dep1 = 0, node = op_node; lys_parent(node); node = lys_parent(node)); for (dep2 = 0, node = first_node; lys_parent(node); node = lys_parent(node)); if ((dep2 > dep1) || ((dep2 == dep1) && (op_node != first_node))) { return 1; } } } else { /* top-level operation (notif/rpc) */ if (op_node != first_node) { return 1; } } return 0; } /** * @brief Resolve a path (leafref) predicate in JSON schema context. Logs directly. * * @param[in] path Path to use. * @param[in] context_node Predicate context node (where the predicate is placed). * @param[in] parent Path context node (where the path begins/is placed). * @param[in] node_set Set where to add nodes whose parent chain must be implemented. * * @return 0 on forward reference, otherwise the number * of characters successfully parsed, * positive on success, negative on failure. */ static int resolve_schema_leafref_predicate(const char *path, const struct lys_node *context_node, struct lys_node *parent, struct ly_set *node_set) { const struct lys_module *trg_mod; const struct lys_node *src_node, *dst_node, *tmp_parent; struct lys_node_augment *last_aug; const char *path_key_expr, *source, *sour_pref, *dest, *dest_pref; int pke_len, sour_len, sour_pref_len, dest_len, dest_pref_len, pke_parsed, parsed = 0; int has_predicate, dest_parent_times, i, rc; struct ly_ctx *ctx = context_node->module->ctx; do { if ((i = parse_path_predicate(path, &sour_pref, &sour_pref_len, &source, &sour_len, &path_key_expr, &pke_len, &has_predicate)) < 1) { LOGVAL(ctx, LYE_INCHAR, LY_VLOG_LYS, parent, path[-i], path - i); return -parsed + i; } parsed += i; path += i; /* source (must be leaf) */ if (sour_pref) { trg_mod = lyp_get_module(lys_node_module(parent), NULL, 0, sour_pref, sour_pref_len, 0); } else { trg_mod = lys_node_module(parent); } rc = lys_getnext_data(trg_mod, context_node, source, sour_len, LYS_LEAF | LYS_LEAFLIST, LYS_GETNEXT_NOSTATECHECK, &src_node); if (rc) { LOGVAL(ctx, LYE_NORESOLV, LY_VLOG_LYS, parent, "leafref predicate", path-parsed); return 0; } /* destination */ dest_parent_times = 0; pke_parsed = 0; if ((i = parse_path_key_expr(path_key_expr, &dest_pref, &dest_pref_len, &dest, &dest_len, &dest_parent_times)) < 1) { LOGVAL(ctx, LYE_INCHAR, LY_VLOG_LYS, parent, path_key_expr[-i], path_key_expr-i); return -parsed; } pke_parsed += i; for (i = 0, dst_node = parent; i < dest_parent_times; ++i) { if (!dst_node) { /* we went too much into parents, there is no parent anymore */ LOGVAL(ctx, LYE_NORESOLV, LY_VLOG_LYS, parent, "leafref predicate", path_key_expr); return 0; } if (dst_node->parent && (dst_node->parent->nodetype == LYS_AUGMENT) && !((struct lys_node_augment *)dst_node->parent)->target) { /* we are in an unresolved augment, cannot evaluate */ LOGVAL(ctx, LYE_SPEC, LY_VLOG_LYS, dst_node->parent, "Cannot resolve leafref predicate \"%s\" because it is in an unresolved augment.", path_key_expr); return 0; } /* path is supposed to be evaluated in data tree, so we have to skip * all schema nodes that cannot be instantiated in data tree */ for (dst_node = lys_parent(dst_node); dst_node && !(dst_node->nodetype & (LYS_CONTAINER | LYS_LIST | LYS_ACTION | LYS_NOTIF | LYS_RPC)); dst_node = lys_parent(dst_node)); } while (1) { last_aug = NULL; if (dest_pref) { trg_mod = lyp_get_module(lys_node_module(parent), NULL, 0, dest_pref, dest_pref_len, 0); } else { trg_mod = lys_node_module(parent); } if (!trg_mod->implemented && dst_node) { get_next_augment: last_aug = lys_getnext_target_aug(last_aug, trg_mod, dst_node); } tmp_parent = (last_aug ? (struct lys_node *)last_aug : dst_node); rc = lys_getnext_data(trg_mod, tmp_parent, dest, dest_len, LYS_CONTAINER | LYS_LIST | LYS_LEAF, LYS_GETNEXT_NOSTATECHECK, &dst_node); if (rc) { if (last_aug) { /* restore the correct augment target */ dst_node = last_aug->target; goto get_next_augment; } LOGVAL(ctx, LYE_NORESOLV, LY_VLOG_LYS, parent, "leafref predicate", path_key_expr); return 0; } if (pke_len == pke_parsed) { break; } if ((i = parse_path_key_expr(path_key_expr + pke_parsed, &dest_pref, &dest_pref_len, &dest, &dest_len, &dest_parent_times)) < 1) { LOGVAL(ctx, LYE_INCHAR, LY_VLOG_LYS, parent, (path_key_expr + pke_parsed)[-i], (path_key_expr + pke_parsed) - i); return -parsed; } pke_parsed += i; } /* check source - dest match */ if (dst_node->nodetype != src_node->nodetype) { LOGVAL(ctx, LYE_NORESOLV, LY_VLOG_LYS, parent, "leafref predicate", path - parsed); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Destination node is not a %s, but a %s.", strnodetype(src_node->nodetype), strnodetype(dst_node->nodetype)); return -parsed; } /* add both nodes into node set */ ly_set_add(node_set, (void *)dst_node, 0); ly_set_add(node_set, (void *)src_node, 0); } while (has_predicate); return parsed; } static int check_leafref_features(struct lys_type *type) { struct lys_node *iter; struct ly_set *src_parents, *trg_parents, *features; struct lys_node_augment *aug; struct ly_ctx *ctx = ((struct lys_tpdf *)type->parent)->module->ctx; unsigned int i, j, size, x; int ret = EXIT_SUCCESS; assert(type->parent); src_parents = ly_set_new(); trg_parents = ly_set_new(); features = ly_set_new(); /* get parents chain of source (leafref) */ for (iter = (struct lys_node *)type->parent; iter; iter = lys_parent(iter)) { if (iter->nodetype & (LYS_INPUT | LYS_OUTPUT)) { continue; } if (iter->parent && (iter->parent->nodetype == LYS_AUGMENT)) { aug = (struct lys_node_augment *)iter->parent; if ((aug->module->implemented && (aug->flags & LYS_NOTAPPLIED)) || !aug->target) { /* unresolved augment, wait until it's resolved */ LOGVAL(ctx, LYE_SPEC, LY_VLOG_LYS, aug, "Cannot check leafref \"%s\" if-feature consistency because of an unresolved augment.", type->info.lref.path); ret = EXIT_FAILURE; goto cleanup; } /* also add this augment */ ly_set_add(src_parents, aug, LY_SET_OPT_USEASLIST); } ly_set_add(src_parents, iter, LY_SET_OPT_USEASLIST); } /* get parents chain of target */ for (iter = (struct lys_node *)type->info.lref.target; iter; iter = lys_parent(iter)) { if (iter->nodetype & (LYS_INPUT | LYS_OUTPUT)) { continue; } if (iter->parent && (iter->parent->nodetype == LYS_AUGMENT)) { aug = (struct lys_node_augment *)iter->parent; if ((aug->module->implemented && (aug->flags & LYS_NOTAPPLIED)) || !aug->target) { /* unresolved augment, wait until it's resolved */ LOGVAL(ctx, LYE_SPEC, LY_VLOG_LYS, aug, "Cannot check leafref \"%s\" if-feature consistency because of an unresolved augment.", type->info.lref.path); ret = EXIT_FAILURE; goto cleanup; } } ly_set_add(trg_parents, iter, LY_SET_OPT_USEASLIST); } /* compare the features used in if-feature statements in the rest of both * chains of parents. The set of features used for target must be a subset * of features used for the leafref. This is not a perfect, we should compare * the truth tables but it could require too much resources, so we simplify that */ for (i = 0; i < src_parents->number; i++) { iter = src_parents->set.s[i]; /* shortcut */ if (!iter->iffeature_size) { continue; } for (j = 0; j < iter->iffeature_size; j++) { resolve_iffeature_getsizes(&iter->iffeature[j], NULL, &size); for (; size; size--) { if (!iter->iffeature[j].features[size - 1]) { /* not yet resolved feature, postpone this check */ ret = EXIT_FAILURE; goto cleanup; } ly_set_add(features, iter->iffeature[j].features[size - 1], 0); } } } x = features->number; for (i = 0; i < trg_parents->number; i++) { iter = trg_parents->set.s[i]; /* shortcut */ if (!iter->iffeature_size) { continue; } for (j = 0; j < iter->iffeature_size; j++) { resolve_iffeature_getsizes(&iter->iffeature[j], NULL, &size); for (; size; size--) { if (!iter->iffeature[j].features[size - 1]) { /* not yet resolved feature, postpone this check */ ret = EXIT_FAILURE; goto cleanup; } if ((unsigned)ly_set_add(features, iter->iffeature[j].features[size - 1], 0) >= x) { /* the feature is not present in features set of target's parents chain */ LOGVAL(ctx, LYE_NORESOLV, LY_VLOG_LYS, type->parent, "leafref", type->info.lref.path); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Leafref is not conditional based on \"%s\" feature as its target.", iter->iffeature[j].features[size - 1]->name); ret = -1; goto cleanup; } } } } cleanup: ly_set_free(features); ly_set_free(src_parents); ly_set_free(trg_parents); return ret; } /** * @brief Resolve a path (leafref) in JSON schema context. Logs directly. * * @param[in] path Path to use. * @param[in] parent_node Parent of the leafref. * @param[out] ret Pointer to the resolved schema node. Can be NULL. * * @return EXIT_SUCCESS on success, EXIT_FAILURE on forward reference, -1 on error. */ static int resolve_schema_leafref(struct lys_type *type, struct lys_node *parent, struct unres_schema *unres) { const struct lys_node *node, *op_node = NULL, *tmp_parent; struct ly_set *node_set; struct lys_node_augment *last_aug; const struct lys_module *tmp_mod, *cur_module; const char *id, *prefix, *name; int pref_len, nam_len, parent_times, has_predicate; int i, first_iter; struct ly_ctx *ctx = parent->module->ctx; first_iter = 1; parent_times = 0; id = type->info.lref.path; node_set = ly_set_new(); if (!node_set) { LOGMEM(ctx); return -1; } /* find operation schema we are in */ for (op_node = lys_parent(parent); op_node && !(op_node->nodetype & (LYS_ACTION | LYS_NOTIF | LYS_RPC)); op_node = lys_parent(op_node)); cur_module = lys_node_module(parent); do { if ((i = parse_path_arg(cur_module, id, &prefix, &pref_len, &name, &nam_len, &parent_times, &has_predicate)) < 1) { LOGVAL(ctx, LYE_INCHAR, LY_VLOG_LYS, parent, id[-i], &id[-i]); ly_set_free(node_set); return -1; } id += i; /* get the current module */ tmp_mod = prefix ? lyp_get_module(cur_module, NULL, 0, prefix, pref_len, 0) : cur_module; if (!tmp_mod) { LOGVAL(ctx, LYE_NORESOLV, LY_VLOG_LYS, parent, "leafref", type->info.lref.path); ly_set_free(node_set); return EXIT_FAILURE; } last_aug = NULL; if (first_iter) { if (parent_times == -1) { /* use module data */ node = NULL; } else if (parent_times > 0) { /* we are looking for the right parent */ for (i = 0, node = parent; i < parent_times; i++) { if (node->parent && (node->parent->nodetype == LYS_AUGMENT) && !((struct lys_node_augment *)node->parent)->target) { /* we are in an unresolved augment, cannot evaluate */ LOGVAL(ctx, LYE_SPEC, LY_VLOG_LYS, node->parent, "Cannot resolve leafref \"%s\" because it is in an unresolved augment.", type->info.lref.path); ly_set_free(node_set); return EXIT_FAILURE; } /* path is supposed to be evaluated in data tree, so we have to skip * all schema nodes that cannot be instantiated in data tree */ for (node = lys_parent(node); node && !(node->nodetype & (LYS_CONTAINER | LYS_LIST | LYS_ACTION | LYS_NOTIF | LYS_RPC)); node = lys_parent(node)); if (!node) { if (i == parent_times - 1) { /* top-level */ break; } /* higher than top-level */ LOGVAL(ctx, LYE_NORESOLV, LY_VLOG_LYS, parent, "leafref", type->info.lref.path); ly_set_free(node_set); return EXIT_FAILURE; } } } else { LOGINT(ctx); ly_set_free(node_set); return -1; } } /* find the next node (either in unconnected augment or as a schema sibling, node is NULL for top-level node - * - useless to search for that in augments) */ if (!tmp_mod->implemented && node) { get_next_augment: last_aug = lys_getnext_target_aug(last_aug, tmp_mod, node); } tmp_parent = (last_aug ? (struct lys_node *)last_aug : node); node = NULL; while ((node = lys_getnext(node, tmp_parent, tmp_mod, LYS_GETNEXT_NOSTATECHECK))) { if (lys_node_module(node) != lys_main_module(tmp_mod)) { continue; } if (strncmp(node->name, name, nam_len) || node->name[nam_len]) { continue; } /* match */ break; } if (!node) { if (last_aug) { /* restore the correct augment target */ node = last_aug->target; goto get_next_augment; } LOGVAL(ctx, LYE_NORESOLV, LY_VLOG_LYS, parent, "leafref", type->info.lref.path); ly_set_free(node_set); return EXIT_FAILURE; } if (first_iter) { /* set external dependency flag, we can decide based on the first found node */ if (resolve_schema_leafref_valid_dep_flag(op_node, cur_module, node, (parent_times == -1 ? 1 : 0))) { parent->flags |= LYS_LEAFREF_DEP; } first_iter = 0; } if (has_predicate) { /* we have predicate, so the current result must be list */ if (node->nodetype != LYS_LIST) { LOGVAL(ctx, LYE_NORESOLV, LY_VLOG_LYS, parent, "leafref", type->info.lref.path); ly_set_free(node_set); return -1; } i = resolve_schema_leafref_predicate(id, node, parent, node_set); if (!i) { ly_set_free(node_set); return EXIT_FAILURE; } else if (i < 0) { ly_set_free(node_set); return -1; } id += i; has_predicate = 0; } } while (id[0]); /* the target must be leaf or leaf-list (in YANG 1.1 only) */ if ((node->nodetype != LYS_LEAF) && (node->nodetype != LYS_LEAFLIST)) { LOGVAL(ctx, LYE_NORESOLV, LY_VLOG_LYS, parent, "leafref", type->info.lref.path); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Leafref target \"%s\" is not a leaf nor a leaf-list.", type->info.lref.path); ly_set_free(node_set); return -1; } /* check status */ if (lyp_check_status(parent->flags, parent->module, parent->name, node->flags, node->module, node->name, node)) { ly_set_free(node_set); return -1; } /* assign */ type->info.lref.target = (struct lys_node_leaf *)node; /* add the target node into a set so its parent chain modules can be implemented */ ly_set_add(node_set, (void *)node, 0); /* as the last thing traverse this leafref and make targets on the path implemented */ if (lys_node_module(parent)->implemented) { /* make all the modules in the path implemented */ for (i = 0; (unsigned)i < node_set->number; ++i) { for (node = node_set->set.s[i]; node; node = lys_parent(node)) { if (!lys_node_module(node)->implemented) { lys_node_module(node)->implemented = 1; if (unres_schema_add_node(lys_node_module(node), unres, NULL, UNRES_MOD_IMPLEMENT, NULL) == -1) { ly_set_free(node_set); return -1; } } } } /* store the backlink from leafref target */ if (lys_leaf_add_leafref_target(type->info.lref.target, (struct lys_node *)type->parent)) { ly_set_free(node_set); return -1; } } ly_set_free(node_set); /* check if leafref and its target are under common if-features */ return check_leafref_features(type); } /** * @brief Compare 2 data node values. * * Comparison performed on canonical forms, the first value * is first transformed into canonical form. * * @param[in] node Leaf/leaf-list with these values. * @param[in] noncan_val Non-canonical value. * @param[in] noncan_val_len Length of \p noncal_val. * @param[in] can_val Canonical value. * @return 1 if equal, 0 if not, -1 on error (logged). */ static int valequal(struct lys_node *node, const char *noncan_val, int noncan_val_len, const char *can_val) { int ret; struct lyd_node_leaf_list leaf; struct lys_node_leaf *sleaf = (struct lys_node_leaf*)node; /* dummy leaf */ memset(&leaf, 0, sizeof leaf); leaf.value_str = lydict_insert(node->module->ctx, noncan_val, noncan_val_len); repeat: leaf.value_type = sleaf->type.base; leaf.schema = node; if (leaf.value_type == LY_TYPE_LEAFREF) { if (!sleaf->type.info.lref.target) { /* it should either be unresolved leafref (leaf.value_type are ORed flags) or it will be resolved */ LOGINT(node->module->ctx); ret = -1; goto finish; } sleaf = sleaf->type.info.lref.target; goto repeat; } else { if (!lyp_parse_value(&sleaf->type, &leaf.value_str, NULL, &leaf, NULL, NULL, 0, 0, 0)) { ret = -1; goto finish; } } if (!strcmp(leaf.value_str, can_val)) { ret = 1; } else { ret = 0; } finish: lydict_remove(node->module->ctx, leaf.value_str); return ret; } /** * @brief Resolve instance-identifier predicate in JSON data format. * Does not log. * * @param[in] prev_mod Previous module to use in case there is no prefix. * @param[in] pred Predicate to use. * @param[in,out] node Node matching the restriction without * the predicate. If it does not satisfy the predicate, * it is set to NULL. * * @return Number of characters successfully parsed, * positive on success, negative on failure. */ static int resolve_instid_predicate(const struct lys_module *prev_mod, const char *pred, struct lyd_node **node, int cur_idx) { /* ... /node[key=value] ... */ struct lyd_node_leaf_list *key; struct lys_node_leaf **list_keys = NULL; struct lys_node_list *slist = NULL; const char *model, *name, *value; int mod_len, nam_len, val_len, i, has_predicate, parsed; struct ly_ctx *ctx = prev_mod->ctx; assert(pred && node && *node); parsed = 0; do { if ((i = parse_predicate(pred + parsed, &model, &mod_len, &name, &nam_len, &value, &val_len, &has_predicate)) < 1) { return -parsed + i; } parsed += i; if (!(*node)) { /* just parse it all */ continue; } /* target */ if (name[0] == '.') { /* leaf-list value */ if ((*node)->schema->nodetype != LYS_LEAFLIST) { LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Instance identifier expects leaf-list, but have %s \"%s\".", strnodetype((*node)->schema->nodetype), (*node)->schema->name); parsed = -1; goto cleanup; } /* check the value */ if (!valequal((*node)->schema, value, val_len, ((struct lyd_node_leaf_list *)*node)->value_str)) { *node = NULL; goto cleanup; } } else if (isdigit(name[0])) { assert(!value); /* keyless list position */ if ((*node)->schema->nodetype != LYS_LIST) { LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Instance identifier expects list, but have %s \"%s\".", strnodetype((*node)->schema->nodetype), (*node)->schema->name); parsed = -1; goto cleanup; } if (((struct lys_node_list *)(*node)->schema)->keys) { LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Instance identifier expects list without keys, but have list \"%s\".", (*node)->schema->name); parsed = -1; goto cleanup; } /* check the index */ if (atoi(name) != cur_idx) { *node = NULL; goto cleanup; } } else { /* list key value */ if ((*node)->schema->nodetype != LYS_LIST) { LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Instance identifier expects list, but have %s \"%s\".", strnodetype((*node)->schema->nodetype), (*node)->schema->name); parsed = -1; goto cleanup; } slist = (struct lys_node_list *)(*node)->schema; /* prepare key array */ if (!list_keys) { list_keys = malloc(slist->keys_size * sizeof *list_keys); LY_CHECK_ERR_RETURN(!list_keys, LOGMEM(ctx), -1); for (i = 0; i < slist->keys_size; ++i) { list_keys[i] = slist->keys[i]; } } /* find the schema key leaf */ for (i = 0; i < slist->keys_size; ++i) { if (list_keys[i] && !strncmp(list_keys[i]->name, name, nam_len) && !list_keys[i]->name[nam_len]) { break; } } if (i == slist->keys_size) { /* this list has no such key */ LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Instance identifier expects list with the key \"%.*s\"," " but list \"%s\" does not define it.", nam_len, name, slist->name); parsed = -1; goto cleanup; } /* check module */ if (model) { if (strncmp(list_keys[i]->module->name, model, mod_len) || list_keys[i]->module->name[mod_len]) { LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Instance identifier expects key \"%s\" from module \"%.*s\", not \"%s\".", list_keys[i]->name, model, mod_len, list_keys[i]->module->name); parsed = -1; goto cleanup; } } else { if (list_keys[i]->module != prev_mod) { LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Instance identifier expects key \"%s\" from module \"%s\", not \"%s\".", list_keys[i]->name, prev_mod->name, list_keys[i]->module->name); parsed = -1; goto cleanup; } } /* find the actual data key */ for (key = (struct lyd_node_leaf_list *)(*node)->child; key; key = (struct lyd_node_leaf_list *)key->next) { if (key->schema == (struct lys_node *)list_keys[i]) { break; } } if (!key) { /* list instance is missing a key? definitely should not happen */ LOGINT(ctx); parsed = -1; goto cleanup; } /* check the value */ if (!valequal(key->schema, value, val_len, key->value_str)) { *node = NULL; /* we still want to parse the whole predicate */ continue; } /* everything is fine, mark this key as resolved */ list_keys[i] = NULL; } } while (has_predicate); /* check that all list keys were specified */ if (*node && list_keys) { for (i = 0; i < slist->keys_size; ++i) { if (list_keys[i]) { LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Instance identifier is missing list key \"%s\".", list_keys[i]->name); parsed = -1; goto cleanup; } } } cleanup: free(list_keys); return parsed; } static int check_xpath(struct lys_node *node, int check_place) { struct lys_node *parent; struct lyxp_set set; enum int_log_opts prev_ilo; if (check_place) { parent = node; while (parent) { if (parent->nodetype == LYS_GROUPING) { /* unresolved grouping, skip for now (will be checked later) */ return EXIT_SUCCESS; } if (parent->nodetype == LYS_AUGMENT) { if (!((struct lys_node_augment *)parent)->target) { /* unresolved augment, skip for now (will be checked later) */ return EXIT_FAILURE; } else { parent = ((struct lys_node_augment *)parent)->target; continue; } } parent = parent->parent; } } memset(&set, 0, sizeof set); /* produce just warnings */ ly_ilo_change(NULL, ILO_ERR2WRN, &prev_ilo, NULL); lyxp_node_atomize(node, &set, 1); ly_ilo_restore(NULL, prev_ilo, NULL, 0); if (set.val.snodes) { free(set.val.snodes); } return EXIT_SUCCESS; } static int check_leafref_config(struct lys_node_leaf *leaf, struct lys_type *type) { unsigned int i; if (type->base == LY_TYPE_LEAFREF) { if ((leaf->flags & LYS_CONFIG_W) && type->info.lref.target && type->info.lref.req != -1 && (type->info.lref.target->flags & LYS_CONFIG_R)) { LOGVAL(leaf->module->ctx, LYE_SPEC, LY_VLOG_LYS, leaf, "The leafref %s is config but refers to a non-config %s.", strnodetype(leaf->nodetype), strnodetype(type->info.lref.target->nodetype)); return -1; } /* we can skip the test in case the leafref is not yet resolved. In that case the test is done in the time * of leafref resolving (lys_leaf_add_leafref_target()) */ } else if (type->base == LY_TYPE_UNION) { for (i = 0; i < type->info.uni.count; i++) { if (check_leafref_config(leaf, &type->info.uni.types[i])) { return -1; } } } return 0; } /** * @brief Passes config flag down to children, skips nodes without config flags. * Logs. * * @param[in] node Siblings and their children to have flags changed. * @param[in] clear Flag to clear all config flags if parent is LYS_NOTIF, LYS_INPUT, LYS_OUTPUT, LYS_RPC. * @param[in] flags Flags to assign to all the nodes. * @param[in,out] unres List of unresolved items. * * @return 0 on success, -1 on error. */ int inherit_config_flag(struct lys_node *node, int flags, int clear) { struct lys_node_leaf *leaf; struct ly_ctx *ctx; if (!node) { return 0; } assert(!(flags ^ (flags & LYS_CONFIG_MASK))); ctx = node->module->ctx; LY_TREE_FOR(node, node) { if (clear) { node->flags &= ~LYS_CONFIG_MASK; node->flags &= ~LYS_CONFIG_SET; } else { if (node->flags & LYS_CONFIG_SET) { /* skip nodes with an explicit config value */ if ((flags & LYS_CONFIG_R) && (node->flags & LYS_CONFIG_W)) { LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, node, "true", "config"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "State nodes cannot have configuration nodes as children."); return -1; } continue; } if (!(node->nodetype & (LYS_USES | LYS_GROUPING))) { node->flags = (node->flags & ~LYS_CONFIG_MASK) | flags; /* check that configuration lists have keys */ if ((node->nodetype == LYS_LIST) && (node->flags & LYS_CONFIG_W) && !((struct lys_node_list *)node)->keys_size) { LOGVAL(ctx, LYE_MISSCHILDSTMT, LY_VLOG_LYS, node, "key", "list"); return -1; } } } if (!(node->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA))) { if (inherit_config_flag(node->child, flags, clear)) { return -1; } } else if (node->nodetype & (LYS_LEAF | LYS_LEAFLIST)) { leaf = (struct lys_node_leaf *)node; if (check_leafref_config(leaf, &leaf->type)) { return -1; } } } return 0; } /** * @brief Resolve augment target. Logs directly. * * @param[in] aug Augment to use. * @param[in] uses Parent where to start the search in. If set, uses augment, if not, standalone augment. * @param[in,out] unres List of unresolved items. * * @return EXIT_SUCCESS on success, EXIT_FAILURE on forward reference, -1 on error. */ static int resolve_augment(struct lys_node_augment *aug, struct lys_node *uses, struct unres_schema *unres) { int rc; struct lys_node *sub; struct lys_module *mod; struct ly_set *set; struct ly_ctx *ctx; assert(aug); mod = lys_main_module(aug->module); ctx = mod->ctx; /* set it as not applied for now */ aug->flags |= LYS_NOTAPPLIED; /* it can already be resolved in case we returned EXIT_FAILURE from if block below */ if (!aug->target) { /* resolve target node */ rc = resolve_schema_nodeid(aug->target_name, uses, (uses ? NULL : lys_node_module((struct lys_node *)aug)), &set, 0, 0); if (rc == -1) { LOGVAL(ctx, LYE_PATH, LY_VLOG_LYS, aug); return -1; } if (!set) { LOGVAL(ctx, LYE_INRESOLV, LY_VLOG_LYS, aug, "augment", aug->target_name); return EXIT_FAILURE; } aug->target = set->set.s[0]; ly_set_free(set); } /* make this module implemented if the target module is (if the target is in an unimplemented module, * it is fine because when we will be making that module implemented, its augment will be applied * and that augment target module made implemented, recursively) */ if (mod->implemented && !lys_node_module(aug->target)->implemented) { lys_node_module(aug->target)->implemented = 1; if (unres_schema_add_node(lys_node_module(aug->target), unres, NULL, UNRES_MOD_IMPLEMENT, NULL) == -1) { return -1; } } /* check for mandatory nodes - if the target node is in another module * the added nodes cannot be mandatory */ if (!aug->parent && (lys_node_module((struct lys_node *)aug) != lys_node_module(aug->target)) && (rc = lyp_check_mandatory_augment(aug, aug->target))) { return rc; } /* check augment target type and then augment nodes type */ if (aug->target->nodetype & (LYS_CONTAINER | LYS_LIST)) { LY_TREE_FOR(aug->child, sub) { if (!(sub->nodetype & (LYS_ANYDATA | LYS_CONTAINER | LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_USES | LYS_CHOICE | LYS_ACTION | LYS_NOTIF))) { LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, aug, strnodetype(sub->nodetype), "augment"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Cannot augment \"%s\" with a \"%s\".", strnodetype(aug->target->nodetype), strnodetype(sub->nodetype)); return -1; } } } else if (aug->target->nodetype & (LYS_CASE | LYS_INPUT | LYS_OUTPUT | LYS_NOTIF)) { LY_TREE_FOR(aug->child, sub) { if (!(sub->nodetype & (LYS_ANYDATA | LYS_CONTAINER | LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_USES | LYS_CHOICE))) { LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, aug, strnodetype(sub->nodetype), "augment"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Cannot augment \"%s\" with a \"%s\".", strnodetype(aug->target->nodetype), strnodetype(sub->nodetype)); return -1; } } } else if (aug->target->nodetype == LYS_CHOICE) { LY_TREE_FOR(aug->child, sub) { if (!(sub->nodetype & (LYS_CASE | LYS_ANYDATA | LYS_CONTAINER | LYS_LEAF | LYS_LIST | LYS_LEAFLIST))) { LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, aug, strnodetype(sub->nodetype), "augment"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Cannot augment \"%s\" with a \"%s\".", strnodetype(aug->target->nodetype), strnodetype(sub->nodetype)); return -1; } } } else { LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, aug, aug->target_name, "target-node"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Invalid augment target node type \"%s\".", strnodetype(aug->target->nodetype)); return -1; } /* check identifier uniqueness as in lys_node_addchild() */ LY_TREE_FOR(aug->child, sub) { if (lys_check_id(sub, aug->target, NULL)) { return -1; } } if (!aug->child) { /* empty augment, nothing to connect, but it is techincally applied */ LOGWRN(ctx, "Augment \"%s\" without children.", aug->target_name); aug->flags &= ~LYS_NOTAPPLIED; } else if ((aug->parent || mod->implemented) && apply_aug(aug, unres)) { /* we try to connect the augment only in case the module is implemented or * the augment applies on the used grouping, anyway we failed here */ return -1; } return EXIT_SUCCESS; } static int resolve_extension(struct unres_ext *info, struct lys_ext_instance **ext, struct unres_schema *unres) { enum LY_VLOG_ELEM vlog_type; void *vlog_node; unsigned int i, j; struct lys_ext *e; char *ext_name, *ext_prefix, *tmp; struct lyxml_elem *next_yin, *yin; const struct lys_module *mod; struct lys_ext_instance *tmp_ext; struct ly_ctx *ctx = NULL; LYEXT_TYPE etype; switch (info->parent_type) { case LYEXT_PAR_NODE: vlog_node = info->parent; vlog_type = LY_VLOG_LYS; break; case LYEXT_PAR_MODULE: case LYEXT_PAR_IMPORT: case LYEXT_PAR_INCLUDE: vlog_node = NULL; vlog_type = LY_VLOG_LYS; break; default: vlog_node = NULL; vlog_type = LY_VLOG_NONE; break; } if (info->datatype == LYS_IN_YIN) { /* YIN */ /* get the module where the extension is supposed to be defined */ mod = lyp_get_import_module_ns(info->mod, info->data.yin->ns->value); if (!mod) { LOGVAL(ctx, LYE_INSTMT, vlog_type, vlog_node, info->data.yin->name); return EXIT_FAILURE; } ctx = mod->ctx; /* find the extension definition */ e = NULL; for (i = 0; i < mod->extensions_size; i++) { if (ly_strequal(mod->extensions[i].name, info->data.yin->name, 1)) { e = &mod->extensions[i]; break; } } /* try submodules */ for (j = 0; !e && j < mod->inc_size; j++) { for (i = 0; i < mod->inc[j].submodule->extensions_size; i++) { if (ly_strequal(mod->inc[j].submodule->extensions[i].name, info->data.yin->name, 1)) { e = &mod->inc[j].submodule->extensions[i]; break; } } } if (!e) { LOGVAL(ctx, LYE_INSTMT, vlog_type, vlog_node, info->data.yin->name); return EXIT_FAILURE; } /* we have the extension definition, so now it cannot be forward referenced and error is always fatal */ if (e->plugin && e->plugin->check_position) { /* common part - we have plugin with position checking function, use it first */ if ((*e->plugin->check_position)(info->parent, info->parent_type, info->substmt)) { /* extension is not allowed here */ LOGVAL(ctx, LYE_INSTMT, vlog_type, vlog_node, e->name); return -1; } } /* extension type-specific part - allocation */ if (e->plugin) { etype = e->plugin->type; } else { /* default type */ etype = LYEXT_FLAG; } switch (etype) { case LYEXT_FLAG: (*ext) = calloc(1, sizeof(struct lys_ext_instance)); break; case LYEXT_COMPLEX: (*ext) = calloc(1, ((struct lyext_plugin_complex*)e->plugin)->instance_size); break; case LYEXT_ERR: /* we never should be here */ LOGINT(ctx); return -1; } LY_CHECK_ERR_RETURN(!*ext, LOGMEM(ctx), -1); /* common part for all extension types */ (*ext)->def = e; (*ext)->parent = info->parent; (*ext)->parent_type = info->parent_type; (*ext)->insubstmt = info->substmt; (*ext)->insubstmt_index = info->substmt_index; (*ext)->ext_type = e->plugin ? e->plugin->type : LYEXT_FLAG; (*ext)->flags |= e->plugin ? e->plugin->flags : 0; if (e->argument) { if (!(e->flags & LYS_YINELEM)) { (*ext)->arg_value = lyxml_get_attr(info->data.yin, e->argument, NULL); if (!(*ext)->arg_value) { LOGVAL(ctx, LYE_MISSARG, LY_VLOG_NONE, NULL, e->argument, info->data.yin->name); return -1; } (*ext)->arg_value = lydict_insert(mod->ctx, (*ext)->arg_value, 0); } else { LY_TREE_FOR_SAFE(info->data.yin->child, next_yin, yin) { if (ly_strequal(yin->name, e->argument, 1)) { (*ext)->arg_value = lydict_insert(mod->ctx, yin->content, 0); lyxml_free(mod->ctx, yin); break; } } } } if ((*ext)->flags & LYEXT_OPT_VALID && (info->parent_type == LYEXT_PAR_NODE || info->parent_type == LYEXT_PAR_TPDF)) { ((struct lys_node *)info->parent)->flags |= LYS_VALID_EXT; } (*ext)->nodetype = LYS_EXT; (*ext)->module = info->mod; /* extension type-specific part - parsing content */ switch (etype) { case LYEXT_FLAG: LY_TREE_FOR_SAFE(info->data.yin->child, next_yin, yin) { if (!yin->ns) { /* garbage */ lyxml_free(mod->ctx, yin); continue; } else if (!strcmp(yin->ns->value, LY_NSYIN)) { /* standard YANG statements are not expected here */ LOGVAL(ctx, LYE_INCHILDSTMT, vlog_type, vlog_node, yin->name, info->data.yin->name); return -1; } else if (yin->ns == info->data.yin->ns && (e->flags & LYS_YINELEM) && ly_strequal(yin->name, e->argument, 1)) { /* we have the extension's argument */ if ((*ext)->arg_value) { LOGVAL(ctx, LYE_TOOMANY, vlog_type, vlog_node, yin->name, info->data.yin->name); return -1; } (*ext)->arg_value = yin->content; yin->content = NULL; lyxml_free(mod->ctx, yin); } else { /* extension instance */ if (lyp_yin_parse_subnode_ext(info->mod, *ext, LYEXT_PAR_EXTINST, yin, LYEXT_SUBSTMT_SELF, 0, unres)) { return -1; } continue; } } break; case LYEXT_COMPLEX: ((struct lys_ext_instance_complex*)(*ext))->substmt = ((struct lyext_plugin_complex*)e->plugin)->substmt; if (lyp_yin_parse_complex_ext(info->mod, (struct lys_ext_instance_complex*)(*ext), info->data.yin, unres)) { /* TODO memory cleanup */ return -1; } break; default: break; } /* TODO - lyext_check_result_clb, other than LYEXT_FLAG plugins */ } else { /* YANG */ ext_prefix = (char *)(*ext)->def; tmp = strchr(ext_prefix, ':'); if (!tmp) { LOGVAL(ctx, LYE_INSTMT, vlog_type, vlog_node, ext_prefix); goto error; } ext_name = tmp + 1; /* get the module where the extension is supposed to be defined */ mod = lyp_get_module(info->mod, ext_prefix, tmp - ext_prefix, NULL, 0, 0); if (!mod) { LOGVAL(ctx, LYE_INSTMT, vlog_type, vlog_node, ext_prefix); return EXIT_FAILURE; } ctx = mod->ctx; /* find the extension definition */ e = NULL; for (i = 0; i < mod->extensions_size; i++) { if (ly_strequal(mod->extensions[i].name, ext_name, 0)) { e = &mod->extensions[i]; break; } } /* try submodules */ for (j = 0; !e && j < mod->inc_size; j++) { for (i = 0; i < mod->inc[j].submodule->extensions_size; i++) { if (ly_strequal(mod->inc[j].submodule->extensions[i].name, ext_name, 0)) { e = &mod->inc[j].submodule->extensions[i]; break; } } } if (!e) { LOGVAL(ctx, LYE_INSTMT, vlog_type, vlog_node, ext_prefix); return EXIT_FAILURE; } (*ext)->flags &= ~LYEXT_OPT_YANG; (*ext)->def = NULL; /* we have the extension definition, so now it cannot be forward referenced and error is always fatal */ if (e->plugin && e->plugin->check_position) { /* common part - we have plugin with position checking function, use it first */ if ((*e->plugin->check_position)(info->parent, info->parent_type, info->substmt)) { /* extension is not allowed here */ LOGVAL(ctx, LYE_INSTMT, vlog_type, vlog_node, e->name); goto error; } } if (e->argument && !(*ext)->arg_value) { LOGVAL(ctx, LYE_MISSARG, LY_VLOG_NONE, NULL, e->argument, ext_name); goto error; } /* extension common part */ (*ext)->def = e; (*ext)->parent = info->parent; (*ext)->ext_type = e->plugin ? e->plugin->type : LYEXT_FLAG; (*ext)->flags |= e->plugin ? e->plugin->flags : 0; if ((*ext)->flags & LYEXT_OPT_VALID && (info->parent_type == LYEXT_PAR_NODE || info->parent_type == LYEXT_PAR_TPDF)) { ((struct lys_node *)info->parent)->flags |= LYS_VALID_EXT; } (*ext)->module = info->mod; (*ext)->nodetype = LYS_EXT; /* extension type-specific part */ if (e->plugin) { etype = e->plugin->type; } else { /* default type */ etype = LYEXT_FLAG; } switch (etype) { case LYEXT_FLAG: /* nothing change */ break; case LYEXT_COMPLEX: tmp_ext = realloc(*ext, ((struct lyext_plugin_complex*)e->plugin)->instance_size); LY_CHECK_ERR_GOTO(!tmp_ext, LOGMEM(ctx), error); memset((char *)tmp_ext + offsetof(struct lys_ext_instance_complex, content), 0, ((struct lyext_plugin_complex*)e->plugin)->instance_size - offsetof(struct lys_ext_instance_complex, content)); (*ext) = tmp_ext; ((struct lys_ext_instance_complex*)(*ext))->substmt = ((struct lyext_plugin_complex*)e->plugin)->substmt; if (info->data.yang) { *tmp = ':'; if (yang_parse_ext_substatement(info->mod, unres, info->data.yang->ext_substmt, ext_prefix, (struct lys_ext_instance_complex*)(*ext))) { goto error; } if (yang_fill_extcomplex_module(info->mod->ctx, (struct lys_ext_instance_complex*)(*ext), ext_prefix, info->data.yang->ext_modules, info->mod->implemented)) { goto error; } } if (lyp_mand_check_ext((struct lys_ext_instance_complex*)(*ext), ext_prefix)) { goto error; } break; case LYEXT_ERR: /* we never should be here */ LOGINT(ctx); goto error; } if (yang_check_ext_instance(info->mod, &(*ext)->ext, (*ext)->ext_size, *ext, unres)) { goto error; } free(ext_prefix); } return EXIT_SUCCESS; error: free(ext_prefix); return -1; } /** * @brief Resolve (find) choice default case. Does not log. * * @param[in] choic Choice to use. * @param[in] dflt Name of the default case. * * @return Pointer to the default node or NULL. */ static struct lys_node * resolve_choice_dflt(struct lys_node_choice *choic, const char *dflt) { struct lys_node *child, *ret; LY_TREE_FOR(choic->child, child) { if (child->nodetype == LYS_USES) { ret = resolve_choice_dflt((struct lys_node_choice *)child, dflt); if (ret) { return ret; } } if (ly_strequal(child->name, dflt, 1) && (child->nodetype & (LYS_ANYDATA | LYS_CASE | LYS_CONTAINER | LYS_LEAF | LYS_LEAFLIST | LYS_LIST | LYS_CHOICE))) { return child; } } return NULL; } /** * @brief Resolve uses, apply augments, refines. Logs directly. * * @param[in] uses Uses to use. * @param[in,out] unres List of unresolved items. * * @return EXIT_SUCCESS on success, -1 on error. */ static int resolve_uses(struct lys_node_uses *uses, struct unres_schema *unres) { struct ly_ctx *ctx = uses->module->ctx; /* shortcut */ struct lys_node *node = NULL, *next, *iter, **refine_nodes = NULL; struct lys_node *node_aux, *parent, *tmp; struct lys_node_leaflist *llist; struct lys_node_leaf *leaf; struct lys_refine *rfn; struct lys_restr *must, **old_must; struct lys_iffeature *iff, **old_iff; int i, j, k, rc; uint8_t size, *old_size; unsigned int usize, usize1, usize2; assert(uses->grp); /* check that the grouping is resolved (no unresolved uses inside) */ assert(!uses->grp->unres_count); /* copy the data nodes from grouping into the uses context */ LY_TREE_FOR(uses->grp->child, node_aux) { if (node_aux->nodetype & LYS_GROUPING) { /* do not instantiate groupings from groupings */ continue; } node = lys_node_dup(uses->module, (struct lys_node *)uses, node_aux, unres, 0); if (!node) { LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, uses, uses->grp->name, "uses"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Copying data from grouping failed."); goto fail; } /* test the name of siblings */ LY_TREE_FOR((uses->parent) ? *lys_child(uses->parent, LYS_USES) : lys_main_module(uses->module)->data, tmp) { if (!(tmp->nodetype & (LYS_USES | LYS_GROUPING | LYS_CASE)) && ly_strequal(tmp->name, node_aux->name, 1)) { goto fail; } } } /* we managed to copy the grouping, the rest must be possible to resolve */ if (uses->refine_size) { refine_nodes = malloc(uses->refine_size * sizeof *refine_nodes); LY_CHECK_ERR_GOTO(!refine_nodes, LOGMEM(ctx), fail); } /* apply refines */ for (i = 0; i < uses->refine_size; i++) { rfn = &uses->refine[i]; rc = resolve_descendant_schema_nodeid(rfn->target_name, uses->child, LYS_NO_RPC_NOTIF_NODE | LYS_ACTION | LYS_NOTIF, 0, (const struct lys_node **)&node); if (rc || !node) { LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, uses, rfn->target_name, "refine"); goto fail; } if (rfn->target_type && !(node->nodetype & rfn->target_type)) { LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, uses, rfn->target_name, "refine"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Refine substatements not applicable to the target-node."); goto fail; } refine_nodes[i] = node; /* description on any nodetype */ if (rfn->dsc) { lydict_remove(ctx, node->dsc); node->dsc = lydict_insert(ctx, rfn->dsc, 0); } /* reference on any nodetype */ if (rfn->ref) { lydict_remove(ctx, node->ref); node->ref = lydict_insert(ctx, rfn->ref, 0); } /* config on any nodetype, * in case of notification or rpc/action, the config is not applicable (there is no config status) */ if ((rfn->flags & LYS_CONFIG_MASK) && (node->flags & LYS_CONFIG_MASK)) { node->flags &= ~LYS_CONFIG_MASK; node->flags |= (rfn->flags & LYS_CONFIG_MASK); } /* default value ... */ if (rfn->dflt_size) { if (node->nodetype == LYS_LEAF) { /* leaf */ leaf = (struct lys_node_leaf *)node; /* replace default value */ lydict_remove(ctx, leaf->dflt); leaf->dflt = lydict_insert(ctx, rfn->dflt[0], 0); /* check the default value */ if (unres_schema_add_node(leaf->module, unres, &leaf->type, UNRES_TYPE_DFLT, (struct lys_node *)(&leaf->dflt)) == -1) { goto fail; } } else if (node->nodetype == LYS_LEAFLIST) { /* leaf-list */ llist = (struct lys_node_leaflist *)node; /* remove complete set of defaults in target */ for (j = 0; j < llist->dflt_size; j++) { lydict_remove(ctx, llist->dflt[j]); } free(llist->dflt); /* copy the default set from refine */ llist->dflt = malloc(rfn->dflt_size * sizeof *llist->dflt); LY_CHECK_ERR_GOTO(!llist->dflt, LOGMEM(ctx), fail); llist->dflt_size = rfn->dflt_size; for (j = 0; j < llist->dflt_size; j++) { llist->dflt[j] = lydict_insert(ctx, rfn->dflt[j], 0); } /* check default value */ for (j = 0; j < llist->dflt_size; j++) { if (unres_schema_add_node(llist->module, unres, &llist->type, UNRES_TYPE_DFLT, (struct lys_node *)(&llist->dflt[j])) == -1) { goto fail; } } } } /* mandatory on leaf, anyxml or choice */ if (rfn->flags & LYS_MAND_MASK) { /* remove current value */ node->flags &= ~LYS_MAND_MASK; /* set new value */ node->flags |= (rfn->flags & LYS_MAND_MASK); if (rfn->flags & LYS_MAND_TRUE) { /* check if node has default value */ if ((node->nodetype & LYS_LEAF) && ((struct lys_node_leaf *)node)->dflt) { LOGVAL(ctx, LYE_SPEC, LY_VLOG_LYS, uses, "The \"mandatory\" statement is forbidden on leaf with \"default\"."); goto fail; } if ((node->nodetype & LYS_CHOICE) && ((struct lys_node_choice *)node)->dflt) { LOGVAL(ctx, LYE_SPEC, LY_VLOG_LYS, uses, "The \"mandatory\" statement is forbidden on choices with \"default\"."); goto fail; } } } /* presence on container */ if ((node->nodetype & LYS_CONTAINER) && rfn->mod.presence) { lydict_remove(ctx, ((struct lys_node_container *)node)->presence); ((struct lys_node_container *)node)->presence = lydict_insert(ctx, rfn->mod.presence, 0); } /* min/max-elements on list or leaf-list */ if (node->nodetype == LYS_LIST) { if (rfn->flags & LYS_RFN_MINSET) { ((struct lys_node_list *)node)->min = rfn->mod.list.min; } if (rfn->flags & LYS_RFN_MAXSET) { ((struct lys_node_list *)node)->max = rfn->mod.list.max; } } else if (node->nodetype == LYS_LEAFLIST) { if (rfn->flags & LYS_RFN_MINSET) { ((struct lys_node_leaflist *)node)->min = rfn->mod.list.min; } if (rfn->flags & LYS_RFN_MAXSET) { ((struct lys_node_leaflist *)node)->max = rfn->mod.list.max; } } /* must in leaf, leaf-list, list, container or anyxml */ if (rfn->must_size) { switch (node->nodetype) { case LYS_LEAF: old_size = &((struct lys_node_leaf *)node)->must_size; old_must = &((struct lys_node_leaf *)node)->must; break; case LYS_LEAFLIST: old_size = &((struct lys_node_leaflist *)node)->must_size; old_must = &((struct lys_node_leaflist *)node)->must; break; case LYS_LIST: old_size = &((struct lys_node_list *)node)->must_size; old_must = &((struct lys_node_list *)node)->must; break; case LYS_CONTAINER: old_size = &((struct lys_node_container *)node)->must_size; old_must = &((struct lys_node_container *)node)->must; break; case LYS_ANYXML: case LYS_ANYDATA: old_size = &((struct lys_node_anydata *)node)->must_size; old_must = &((struct lys_node_anydata *)node)->must; break; default: LOGINT(ctx); goto fail; } size = *old_size + rfn->must_size; must = realloc(*old_must, size * sizeof *rfn->must); LY_CHECK_ERR_GOTO(!must, LOGMEM(ctx), fail); for (k = 0, j = *old_size; k < rfn->must_size; k++, j++) { must[j].ext_size = rfn->must[k].ext_size; lys_ext_dup(ctx, rfn->module, rfn->must[k].ext, rfn->must[k].ext_size, &rfn->must[k], LYEXT_PAR_RESTR, &must[j].ext, 0, unres); must[j].expr = lydict_insert(ctx, rfn->must[k].expr, 0); must[j].dsc = lydict_insert(ctx, rfn->must[k].dsc, 0); must[j].ref = lydict_insert(ctx, rfn->must[k].ref, 0); must[j].eapptag = lydict_insert(ctx, rfn->must[k].eapptag, 0); must[j].emsg = lydict_insert(ctx, rfn->must[k].emsg, 0); must[j].flags = rfn->must[k].flags; } *old_must = must; *old_size = size; /* check XPath dependencies again */ if (unres_schema_add_node(node->module, unres, node, UNRES_XPATH, NULL) == -1) { goto fail; } } /* if-feature in leaf, leaf-list, list, container or anyxml */ if (rfn->iffeature_size) { old_size = &node->iffeature_size; old_iff = &node->iffeature; size = *old_size + rfn->iffeature_size; iff = realloc(*old_iff, size * sizeof *rfn->iffeature); LY_CHECK_ERR_GOTO(!iff, LOGMEM(ctx), fail); *old_iff = iff; for (k = 0, j = *old_size; k < rfn->iffeature_size; k++, j++) { resolve_iffeature_getsizes(&rfn->iffeature[k], &usize1, &usize2); if (usize1) { /* there is something to duplicate */ /* duplicate compiled expression */ usize = (usize1 / 4) + (usize1 % 4) ? 1 : 0; iff[j].expr = malloc(usize * sizeof *iff[j].expr); LY_CHECK_ERR_GOTO(!iff[j].expr, LOGMEM(ctx), fail); memcpy(iff[j].expr, rfn->iffeature[k].expr, usize * sizeof *iff[j].expr); /* duplicate list of feature pointers */ iff[j].features = malloc(usize2 * sizeof *iff[k].features); LY_CHECK_ERR_GOTO(!iff[j].expr, LOGMEM(ctx), fail); memcpy(iff[j].features, rfn->iffeature[k].features, usize2 * sizeof *iff[j].features); /* duplicate extensions */ iff[j].ext_size = rfn->iffeature[k].ext_size; lys_ext_dup(ctx, rfn->module, rfn->iffeature[k].ext, rfn->iffeature[k].ext_size, &rfn->iffeature[k], LYEXT_PAR_IFFEATURE, &iff[j].ext, 0, unres); } (*old_size)++; } assert(*old_size == size); } } /* apply augments */ for (i = 0; i < uses->augment_size; i++) { rc = resolve_augment(&uses->augment[i], (struct lys_node *)uses, unres); if (rc) { goto fail; } } /* check refines */ for (i = 0; i < uses->refine_size; i++) { node = refine_nodes[i]; rfn = &uses->refine[i]; /* config on any nodetype */ if ((rfn->flags & LYS_CONFIG_MASK) && (node->flags & LYS_CONFIG_MASK)) { for (parent = lys_parent(node); parent && parent->nodetype == LYS_USES; parent = lys_parent(parent)); if (parent && parent->nodetype != LYS_GROUPING && (parent->flags & LYS_CONFIG_MASK) && ((parent->flags & LYS_CONFIG_MASK) != (rfn->flags & LYS_CONFIG_MASK)) && (rfn->flags & LYS_CONFIG_W)) { /* setting config true under config false is prohibited */ LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, uses, "config", "refine"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "changing config from 'false' to 'true' is prohibited while " "the target's parent is still config 'false'."); goto fail; } /* inherit config change to the target children */ LY_TREE_DFS_BEGIN(node->child, next, iter) { if (rfn->flags & LYS_CONFIG_W) { if (iter->flags & LYS_CONFIG_SET) { /* config is set explicitely, go to next sibling */ next = NULL; goto nextsibling; } } else { /* LYS_CONFIG_R */ if ((iter->flags & LYS_CONFIG_SET) && (iter->flags & LYS_CONFIG_W)) { /* error - we would have config data under status data */ LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, uses, "config", "refine"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "changing config from 'true' to 'false' is prohibited while the target " "has still a children with explicit config 'true'."); goto fail; } } /* change config */ iter->flags &= ~LYS_CONFIG_MASK; iter->flags |= (rfn->flags & LYS_CONFIG_MASK); /* select next iter - modified LY_TREE_DFS_END */ if (iter->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA)) { next = NULL; } else { next = iter->child; } nextsibling: if (!next) { /* try siblings */ next = iter->next; } while (!next) { /* parent is already processed, go to its sibling */ iter = lys_parent(iter); /* no siblings, go back through parents */ if (iter == node) { /* we are done, no next element to process */ break; } next = iter->next; } } } /* default value */ if (rfn->dflt_size) { if (node->nodetype == LYS_CHOICE) { /* choice */ ((struct lys_node_choice *)node)->dflt = resolve_choice_dflt((struct lys_node_choice *)node, rfn->dflt[0]); if (!((struct lys_node_choice *)node)->dflt) { LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, uses, rfn->dflt[0], "default"); goto fail; } if (lyp_check_mandatory_choice(node)) { goto fail; } } } /* min/max-elements on list or leaf-list */ if (node->nodetype == LYS_LIST && ((struct lys_node_list *)node)->max) { if (((struct lys_node_list *)node)->min > ((struct lys_node_list *)node)->max) { LOGVAL(ctx, LYE_SPEC, LY_VLOG_LYS, uses, "Invalid value \"%d\" of \"%s\".", rfn->mod.list.min, "min-elements"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "\"min-elements\" is bigger than \"max-elements\"."); goto fail; } } else if (node->nodetype == LYS_LEAFLIST && ((struct lys_node_leaflist *)node)->max) { if (((struct lys_node_leaflist *)node)->min > ((struct lys_node_leaflist *)node)->max) { LOGVAL(ctx, LYE_SPEC, LY_VLOG_LYS, uses, "Invalid value \"%d\" of \"%s\".", rfn->mod.list.min, "min-elements"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "\"min-elements\" is bigger than \"max-elements\"."); goto fail; } } /* additional checks */ /* default value with mandatory/min-elements */ if (node->nodetype == LYS_LEAFLIST) { llist = (struct lys_node_leaflist *)node; if (llist->dflt_size && llist->min) { LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, uses, rfn->dflt_size ? "default" : "min-elements", "refine"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "The \"min-elements\" statement with non-zero value is forbidden on leaf-lists with the \"default\" statement."); goto fail; } } else if (node->nodetype == LYS_LEAF) { leaf = (struct lys_node_leaf *)node; if (leaf->dflt && (leaf->flags & LYS_MAND_TRUE)) { LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, uses, rfn->dflt_size ? "default" : "mandatory", "refine"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "The \"mandatory\" statement is forbidden on leafs with the \"default\" statement."); goto fail; } } /* check for mandatory node in default case, first find the closest parent choice to the changed node */ if ((rfn->flags & LYS_MAND_TRUE) || rfn->mod.list.min) { for (parent = node->parent; parent && !(parent->nodetype & (LYS_CHOICE | LYS_GROUPING | LYS_ACTION | LYS_USES)); parent = parent->parent) { if (parent->nodetype == LYS_CONTAINER && ((struct lys_node_container *)parent)->presence) { /* stop also on presence containers */ break; } } /* and if it is a choice with the default case, check it for presence of a mandatory node in it */ if (parent && parent->nodetype == LYS_CHOICE && ((struct lys_node_choice *)parent)->dflt) { if (lyp_check_mandatory_choice(parent)) { goto fail; } } } } free(refine_nodes); return EXIT_SUCCESS; fail: LY_TREE_FOR_SAFE(uses->child, next, iter) { lys_node_free(iter, NULL, 0); } free(refine_nodes); return -1; } void resolve_identity_backlink_update(struct lys_ident *der, struct lys_ident *base) { int i; assert(der && base); if (!base->der) { /* create a set for backlinks if it does not exist */ base->der = ly_set_new(); } /* store backlink */ ly_set_add(base->der, der, LY_SET_OPT_USEASLIST); /* do it recursively */ for (i = 0; i < base->base_size; i++) { resolve_identity_backlink_update(der, base->base[i]); } } /** * @brief Resolve base identity recursively. Does not log. * * @param[in] module Main module. * @param[in] ident Identity to use. * @param[in] basename Base name of the identity. * @param[out] ret Pointer to the resolved identity. Can be NULL. * * @return EXIT_SUCCESS on success, EXIT_FAILURE on forward reference, -1 on crucial error. */ static int resolve_base_ident_sub(const struct lys_module *module, struct lys_ident *ident, const char *basename, struct unres_schema *unres, struct lys_ident **ret) { uint32_t i, j; struct lys_ident *base = NULL; struct ly_ctx *ctx = module->ctx; assert(ret); /* search module */ for (i = 0; i < module->ident_size; i++) { if (!strcmp(basename, module->ident[i].name)) { if (!ident) { /* just search for type, so do not modify anything, just return * the base identity pointer */ *ret = &module->ident[i]; return EXIT_SUCCESS; } base = &module->ident[i]; goto matchfound; } } /* search submodules */ for (j = 0; j < module->inc_size && module->inc[j].submodule; j++) { for (i = 0; i < module->inc[j].submodule->ident_size; i++) { if (!strcmp(basename, module->inc[j].submodule->ident[i].name)) { if (!ident) { *ret = &module->inc[j].submodule->ident[i]; return EXIT_SUCCESS; } base = &module->inc[j].submodule->ident[i]; goto matchfound; } } } matchfound: /* we found it somewhere */ if (base) { /* is it already completely resolved? */ for (i = 0; i < unres->count; i++) { if ((unres->item[i] == base) && (unres->type[i] == UNRES_IDENT)) { /* identity found, but not yet resolved, so do not return it in *res and try it again later */ /* simple check for circular reference, * the complete check is done as a side effect of using only completely * resolved identities (previous check of unres content) */ if (ly_strequal((const char *)unres->str_snode[i], ident->name, 1)) { LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, basename, "base"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Circular reference of \"%s\" identity.", basename); return -1; } return EXIT_FAILURE; } } /* checks done, store the result */ *ret = base; return EXIT_SUCCESS; } /* base not found (maybe a forward reference) */ return EXIT_FAILURE; } /** * @brief Resolve base identity. Logs directly. * * @param[in] module Main module. * @param[in] ident Identity to use. * @param[in] basename Base name of the identity. * @param[in] parent Either "type" or "identity". * @param[in,out] type Type structure where we want to resolve identity. Can be NULL. * * @return EXIT_SUCCESS on success, EXIT_FAILURE on forward reference, -1 on error. */ static int resolve_base_ident(const struct lys_module *module, struct lys_ident *ident, const char *basename, const char *parent, struct lys_type *type, struct unres_schema *unres) { const char *name; int mod_name_len = 0, rc; struct lys_ident *target, **ret; uint16_t flags; struct lys_module *mod; struct ly_ctx *ctx = module->ctx; assert((ident && !type) || (!ident && type)); if (!type) { /* have ident to resolve */ ret = &target; flags = ident->flags; mod = ident->module; } else { /* have type to fill */ ++type->info.ident.count; type->info.ident.ref = ly_realloc(type->info.ident.ref, type->info.ident.count * sizeof *type->info.ident.ref); LY_CHECK_ERR_RETURN(!type->info.ident.ref, LOGMEM(ctx), -1); ret = &type->info.ident.ref[type->info.ident.count - 1]; flags = type->parent->flags; mod = type->parent->module; } *ret = NULL; /* search for the base identity */ name = strchr(basename, ':'); if (name) { /* set name to correct position after colon */ mod_name_len = name - basename; name++; if (!strncmp(basename, module->name, mod_name_len) && !module->name[mod_name_len]) { /* prefix refers to the current module, ignore it */ mod_name_len = 0; } } else { name = basename; } /* get module where to search */ module = lyp_get_module(module, NULL, 0, mod_name_len ? basename : NULL, mod_name_len, 0); if (!module) { /* identity refers unknown data model */ LOGVAL(ctx, LYE_INMOD, LY_VLOG_NONE, NULL, basename); return -1; } /* search in the identified module ... */ rc = resolve_base_ident_sub(module, ident, name, unres, ret); if (!rc) { assert(*ret); /* check status */ if (lyp_check_status(flags, mod, ident ? ident->name : "of type", (*ret)->flags, (*ret)->module, (*ret)->name, NULL)) { rc = -1; } else if (ident) { ident->base[ident->base_size++] = *ret; if (lys_main_module(mod)->implemented) { /* in case of the implemented identity, maintain backlinks to it * from the base identities to make it available when resolving * data with the identity values (not implemented identity is not * allowed as an identityref value). */ resolve_identity_backlink_update(ident, *ret); } } } else if (rc == EXIT_FAILURE) { LOGVAL(ctx, LYE_INRESOLV, LY_VLOG_NONE, NULL, parent, basename); if (type) { --type->info.ident.count; } } return rc; } /* * 1 - true (der is derived from base) * 0 - false (der is not derived from base) */ static int search_base_identity(struct lys_ident *der, struct lys_ident *base) { int i; if (der == base) { return 1; } else { for(i = 0; i < der->base_size; i++) { if (search_base_identity(der->base[i], base) == 1) { return 1; } } } return 0; } /** * @brief Resolve JSON data format identityref. Logs directly. * * @param[in] type Identityref type. * @param[in] ident_name Identityref name. * @param[in] node Node where the identityref is being resolved * @param[in] dflt flag if we are resolving default value in the schema * * @return Pointer to the identity resolvent, NULL on error. */ struct lys_ident * resolve_identref(struct lys_type *type, const char *ident_name, struct lyd_node *node, struct lys_module *mod, int dflt) { const char *mod_name, *name; char *str; int mod_name_len, nam_len, rc; int need_implemented = 0; unsigned int i, j; struct lys_ident *der, *cur; struct lys_module *imod = NULL, *m, *tmod; struct ly_ctx *ctx; assert(type && ident_name && mod); ctx = mod->ctx; if (!type || (!type->info.ident.count && !type->der) || !ident_name) { return NULL; } rc = parse_node_identifier(ident_name, &mod_name, &mod_name_len, &name, &nam_len, NULL, 0); if (rc < 1) { LOGVAL(ctx, LYE_INCHAR, node ? LY_VLOG_LYD : LY_VLOG_NONE, node, ident_name[-rc], &ident_name[-rc]); return NULL; } else if (rc < (signed)strlen(ident_name)) { LOGVAL(ctx, LYE_INCHAR, node ? LY_VLOG_LYD : LY_VLOG_NONE, node, ident_name[rc], &ident_name[rc]); return NULL; } m = lys_main_module(mod); /* shortcut */ if (!mod_name || (!strncmp(mod_name, m->name, mod_name_len) && !m->name[mod_name_len])) { /* identity is defined in the same module as node */ imod = m; } else if (dflt) { /* solving identityref in default definition in schema - * find the identity's module in the imported modules list to have a correct revision */ for (i = 0; i < mod->imp_size; i++) { if (!strncmp(mod_name, mod->imp[i].module->name, mod_name_len) && !mod->imp[i].module->name[mod_name_len]) { imod = mod->imp[i].module; break; } } /* We may need to pull it from the module that the typedef came from */ if (!imod && type && type->der) { tmod = type->der->module; for (i = 0; i < tmod->imp_size; i++) { if (!strncmp(mod_name, tmod->imp[i].module->name, mod_name_len) && !tmod->imp[i].module->name[mod_name_len]) { imod = tmod->imp[i].module; break; } } } } else { /* solving identityref in data - get the module from the context */ for (i = 0; i < (unsigned)mod->ctx->models.used; ++i) { imod = mod->ctx->models.list[i]; if (!strncmp(mod_name, imod->name, mod_name_len) && !imod->name[mod_name_len]) { break; } imod = NULL; } if (!imod && mod->ctx->models.parsing_sub_modules_count) { /* we are currently parsing some module and checking XPath or a default value, * so take this module into account */ for (i = 0; i < mod->ctx->models.parsing_sub_modules_count; i++) { imod = mod->ctx->models.parsing_sub_modules[i]; if (imod->type) { /* skip submodules */ continue; } if (!strncmp(mod_name, imod->name, mod_name_len) && !imod->name[mod_name_len]) { break; } imod = NULL; } } } if (!dflt && (!imod || !imod->implemented) && ctx->data_clb) { /* the needed module was not found, but it may have been expected so call the data callback */ if (imod) { ctx->data_clb(ctx, imod->name, imod->ns, LY_MODCLB_NOT_IMPLEMENTED, ctx->data_clb_data); } else if (mod_name) { str = strndup(mod_name, mod_name_len); imod = (struct lys_module *)ctx->data_clb(ctx, str, NULL, 0, ctx->data_clb_data); free(str); } } if (!imod) { goto fail; } if (m != imod || lys_main_module(type->parent->module) != mod) { /* the type is not referencing the same schema, * THEN, we may need to make the module with the identity implemented, but only if it really * contains the identity */ if (!imod->implemented) { cur = NULL; /* get the identity in the module */ for (i = 0; i < imod->ident_size; i++) { if (!strcmp(name, imod->ident[i].name)) { cur = &imod->ident[i]; break; } } if (!cur) { /* go through includes */ for (j = 0; j < imod->inc_size; j++) { for (i = 0; i < imod->inc[j].submodule->ident_size; i++) { if (!strcmp(name, imod->inc[j].submodule->ident[i].name)) { cur = &imod->inc[j].submodule->ident[i]; break; } } } if (!cur) { goto fail; } } /* check that identity is derived from one of the type's base */ while (type->der) { for (i = 0; i < type->info.ident.count; i++) { if (search_base_identity(cur, type->info.ident.ref[i])) { /* cur's base matches the type's base */ need_implemented = 1; goto match; } } type = &type->der->type; } /* matching base not found */ LOGVAL(ctx, LYE_SPEC, node ? LY_VLOG_LYD : LY_VLOG_NONE, node, "Identity used as identityref value is not implemented."); goto fail; } } /* go through all the derived types of all the bases */ while (type->der) { for (i = 0; i < type->info.ident.count; ++i) { cur = type->info.ident.ref[i]; if (cur->der) { /* there are some derived identities */ for (j = 0; j < cur->der->number; j++) { der = (struct lys_ident *)cur->der->set.g[j]; /* shortcut */ if (!strcmp(der->name, name) && lys_main_module(der->module) == imod) { /* we have match */ cur = der; goto match; } } } } type = &type->der->type; } fail: LOGVAL(ctx, LYE_INRESOLV, node ? LY_VLOG_LYD : LY_VLOG_NONE, node, "identityref", ident_name); return NULL; match: for (i = 0; i < cur->iffeature_size; i++) { if (!resolve_iffeature(&cur->iffeature[i])) { if (node) { LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, node, cur->name, node->schema->name); } LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Identity \"%s\" is disabled by its if-feature condition.", cur->name); return NULL; } } if (need_implemented) { if (dflt) { /* later try to make the module implemented */ LOGVRB("Making \"%s\" module implemented because of identityref default value \"%s\" used in the implemented \"%s\" module", imod->name, cur->name, mod->name); /* to be more effective we should use UNRES_MOD_IMPLEMENT but that would require changing prototype of * several functions with little gain */ if (lys_set_implemented(imod)) { LOGERR(ctx, ly_errno, "Setting the module \"%s\" implemented because of used default identity \"%s\" failed.", imod->name, cur->name); goto fail; } } else { /* just say that it was found, but in a non-implemented module */ LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Identity found, but in a non-implemented module \"%s\".", lys_main_module(cur->module)->name); goto fail; } } return cur; } /** * @brief Resolve unresolved uses. Logs directly. * * @param[in] uses Uses to use. * @param[in] unres Specific unres item. * * @return EXIT_SUCCESS on success, EXIT_FAILURE on forward reference, -1 on error. */ static int resolve_unres_schema_uses(struct lys_node_uses *uses, struct unres_schema *unres) { int rc; struct lys_node *par_grp; struct ly_ctx *ctx = uses->module->ctx; /* HACK: when a grouping has uses inside, all such uses have to be resolved before the grouping itself is used * in some uses. When we see such a uses, the grouping's unres counter is used to store number of so far * unresolved uses. The grouping cannot be used unless this counter is decreased back to 0. To remember * that the uses already increased grouping's counter, the LYS_USESGRP flag is used. */ for (par_grp = lys_parent((struct lys_node *)uses); par_grp && (par_grp->nodetype != LYS_GROUPING); par_grp = lys_parent(par_grp)); if (par_grp && ly_strequal(par_grp->name, uses->name, 1)) { LOGVAL(ctx, LYE_INRESOLV, LY_VLOG_LYS, uses, "uses", uses->name); return -1; } if (!uses->grp) { rc = resolve_uses_schema_nodeid(uses->name, (const struct lys_node *)uses, (const struct lys_node_grp **)&uses->grp); if (rc == -1) { LOGVAL(ctx, LYE_INRESOLV, LY_VLOG_LYS, uses, "uses", uses->name); return -1; } else if (rc > 0) { LOGVAL(ctx, LYE_INCHAR, LY_VLOG_LYS, uses, uses->name[rc - 1], &uses->name[rc - 1]); return -1; } else if (!uses->grp) { if (par_grp && !(uses->flags & LYS_USESGRP)) { if (++((struct lys_node_grp *)par_grp)->unres_count == 0) { LOGERR(ctx, LY_EINT, "Too many unresolved items (uses) inside a grouping."); return -1; } uses->flags |= LYS_USESGRP; } LOGVAL(ctx, LYE_INRESOLV, LY_VLOG_LYS, uses, "uses", uses->name); return EXIT_FAILURE; } } if (uses->grp->unres_count) { if (par_grp && !(uses->flags & LYS_USESGRP)) { if (++((struct lys_node_grp *)par_grp)->unres_count == 0) { LOGERR(ctx, LY_EINT, "Too many unresolved items (uses) inside a grouping."); return -1; } uses->flags |= LYS_USESGRP; } else { /* instantiate grouping only when it is completely resolved */ uses->grp = NULL; } LOGVAL(ctx, LYE_INRESOLV, LY_VLOG_LYS, uses, "uses", uses->name); return EXIT_FAILURE; } rc = resolve_uses(uses, unres); if (!rc) { /* decrease unres count only if not first try */ if (par_grp && (uses->flags & LYS_USESGRP)) { assert(((struct lys_node_grp *)par_grp)->unres_count); ((struct lys_node_grp *)par_grp)->unres_count--; uses->flags &= ~LYS_USESGRP; } /* check status */ if (lyp_check_status(uses->flags, uses->module, "of uses", uses->grp->flags, uses->grp->module, uses->grp->name, (struct lys_node *)uses)) { return -1; } return EXIT_SUCCESS; } return rc; } /** * @brief Resolve list keys. Logs directly. * * @param[in] list List to use. * @param[in] keys_str Keys node value. * * @return EXIT_SUCCESS on success, EXIT_FAILURE on forward reference, -1 on error. */ static int resolve_list_keys(struct lys_node_list *list, const char *keys_str) { int i, len, rc; const char *value; char *s = NULL; struct ly_ctx *ctx = list->module->ctx; for (i = 0; i < list->keys_size; ++i) { assert(keys_str); if (!list->child) { /* no child, possible forward reference */ LOGVAL(ctx, LYE_INRESOLV, LY_VLOG_LYS, list, "list keys", keys_str); return EXIT_FAILURE; } /* get the key name */ if ((value = strpbrk(keys_str, " \t\n"))) { len = value - keys_str; while (isspace(value[0])) { value++; } } else { len = strlen(keys_str); } rc = lys_getnext_data(lys_node_module((struct lys_node *)list), (struct lys_node *)list, keys_str, len, LYS_LEAF, LYS_GETNEXT_NOSTATECHECK, (const struct lys_node **)&list->keys[i]); if (rc) { LOGVAL(ctx, LYE_INRESOLV, LY_VLOG_LYS, list, "list key", keys_str); return EXIT_FAILURE; } if (check_key(list, i, keys_str, len)) { /* check_key logs */ return -1; } /* check status */ if (lyp_check_status(list->flags, list->module, list->name, list->keys[i]->flags, list->keys[i]->module, list->keys[i]->name, (struct lys_node *)list->keys[i])) { return -1; } /* default value - is ignored, keep it but print a warning */ if (list->keys[i]->dflt) { /* log is not hidden only in case this resolving fails and in such a case * we cannot get here */ assert(log_opt == ILO_STORE); log_opt = ILO_LOG; LOGWRN(ctx, "Default value \"%s\" in the list key \"%s\" is ignored. (%s)", list->keys[i]->dflt, list->keys[i]->name, s = lys_path((struct lys_node*)list, LYS_PATH_FIRST_PREFIX)); log_opt = ILO_STORE; free(s); } /* prepare for next iteration */ while (value && isspace(value[0])) { value++; } keys_str = value; } return EXIT_SUCCESS; } /** * @brief Resolve (check) all must conditions of \p node. * Logs directly. * * @param[in] node Data node with optional must statements. * @param[in] inout_parent If set, must in input or output parent of node->schema will be resolved. * * @return EXIT_SUCCESS on pass, EXIT_FAILURE on fail, -1 on error. */ static int resolve_must(struct lyd_node *node, int inout_parent, int ignore_fail) { uint8_t i, must_size; struct lys_node *schema; struct lys_restr *must; struct lyxp_set set; struct ly_ctx *ctx = node->schema->module->ctx; assert(node); memset(&set, 0, sizeof set); if (inout_parent) { for (schema = lys_parent(node->schema); schema && (schema->nodetype & (LYS_CHOICE | LYS_CASE | LYS_USES)); schema = lys_parent(schema)); if (!schema || !(schema->nodetype & (LYS_INPUT | LYS_OUTPUT))) { LOGINT(ctx); return -1; } must_size = ((struct lys_node_inout *)schema)->must_size; must = ((struct lys_node_inout *)schema)->must; /* context node is the RPC/action */ node = node->parent; if (!(node->schema->nodetype & (LYS_RPC | LYS_ACTION))) { LOGINT(ctx); return -1; } } else { switch (node->schema->nodetype) { case LYS_CONTAINER: must_size = ((struct lys_node_container *)node->schema)->must_size; must = ((struct lys_node_container *)node->schema)->must; break; case LYS_LEAF: must_size = ((struct lys_node_leaf *)node->schema)->must_size; must = ((struct lys_node_leaf *)node->schema)->must; break; case LYS_LEAFLIST: must_size = ((struct lys_node_leaflist *)node->schema)->must_size; must = ((struct lys_node_leaflist *)node->schema)->must; break; case LYS_LIST: must_size = ((struct lys_node_list *)node->schema)->must_size; must = ((struct lys_node_list *)node->schema)->must; break; case LYS_ANYXML: case LYS_ANYDATA: must_size = ((struct lys_node_anydata *)node->schema)->must_size; must = ((struct lys_node_anydata *)node->schema)->must; break; case LYS_NOTIF: must_size = ((struct lys_node_notif *)node->schema)->must_size; must = ((struct lys_node_notif *)node->schema)->must; break; default: must_size = 0; break; } } for (i = 0; i < must_size; ++i) { if (lyxp_eval(must[i].expr, node, LYXP_NODE_ELEM, lyd_node_module(node), &set, LYXP_MUST)) { return -1; } lyxp_set_cast(&set, LYXP_SET_BOOLEAN, node, lyd_node_module(node), LYXP_MUST); if (!set.val.bool) { if ((ignore_fail == 1) || ((must[i].flags & (LYS_XPCONF_DEP | LYS_XPSTATE_DEP)) && (ignore_fail == 2))) { LOGVRB("Must condition \"%s\" not satisfied, but it is not required.", must[i].expr); } else { LOGVAL(ctx, LYE_NOMUST, LY_VLOG_LYD, node, must[i].expr); if (must[i].emsg) { ly_vlog_str(ctx, LY_VLOG_PREV, must[i].emsg); } if (must[i].eapptag) { ly_err_last_set_apptag(ctx, must[i].eapptag); } return 1; } } } return EXIT_SUCCESS; } /** * @brief Resolve (find) when condition schema context node. Does not log. * * @param[in] schema Schema node with the when condition. * @param[out] ctx_snode When schema context node. * @param[out] ctx_snode_type Schema context node type. */ void resolve_when_ctx_snode(const struct lys_node *schema, struct lys_node **ctx_snode, enum lyxp_node_type *ctx_snode_type) { const struct lys_node *sparent; /* find a not schema-only node */ *ctx_snode_type = LYXP_NODE_ELEM; while (schema->nodetype & (LYS_USES | LYS_CHOICE | LYS_CASE | LYS_AUGMENT | LYS_INPUT | LYS_OUTPUT)) { if (schema->nodetype == LYS_AUGMENT) { sparent = ((struct lys_node_augment *)schema)->target; } else { sparent = schema->parent; } if (!sparent) { /* context node is the document root (fake root in our case) */ if (schema->flags & LYS_CONFIG_W) { *ctx_snode_type = LYXP_NODE_ROOT_CONFIG; } else { *ctx_snode_type = LYXP_NODE_ROOT; } /* we need the first top-level sibling, but no uses or groupings */ schema = lys_getnext(NULL, NULL, lys_node_module(schema), LYS_GETNEXT_NOSTATECHECK); break; } schema = sparent; } *ctx_snode = (struct lys_node *)schema; } /** * @brief Resolve (find) when condition context node. Does not log. * * @param[in] node Data node, whose conditional definition is being decided. * @param[in] schema Schema node with the when condition. * @param[out] ctx_node Context node. * @param[out] ctx_node_type Context node type. * * @return EXIT_SUCCESS on success, -1 on error. */ static int resolve_when_ctx_node(struct lyd_node *node, struct lys_node *schema, struct lyd_node **ctx_node, enum lyxp_node_type *ctx_node_type) { struct lyd_node *parent; struct lys_node *sparent; enum lyxp_node_type node_type; uint16_t i, data_depth, schema_depth; resolve_when_ctx_snode(schema, &schema, &node_type); if (node_type == LYXP_NODE_ELEM) { /* standard element context node */ for (parent = node, data_depth = 0; parent; parent = parent->parent, ++data_depth); for (sparent = schema, schema_depth = 0; sparent; sparent = (sparent->nodetype == LYS_AUGMENT ? ((struct lys_node_augment *)sparent)->target : sparent->parent)) { if (sparent->nodetype & (LYS_CONTAINER | LYS_LEAF | LYS_LEAFLIST | LYS_LIST | LYS_ANYDATA | LYS_NOTIF | LYS_RPC)) { ++schema_depth; } } if (data_depth < schema_depth) { return -1; } /* find the corresponding data node */ for (i = 0; i < data_depth - schema_depth; ++i) { node = node->parent; } if (node->schema != schema) { return -1; } } else { /* root context node */ while (node->parent) { node = node->parent; } while (node->prev->next) { node = node->prev; } } *ctx_node = node; *ctx_node_type = node_type; return EXIT_SUCCESS; } /** * @brief Temporarily unlink nodes as per YANG 1.1 RFC section 7.21.5 for when XPath evaluation. * The context node is adjusted if needed. * * @param[in] snode Schema node, whose children instances need to be unlinked. * @param[in,out] node Data siblings where to look for the children of \p snode. If it is unlinked, * it is moved to point to another sibling still in the original tree. * @param[in,out] ctx_node When context node, adjusted if needed. * @param[in] ctx_node_type Context node type, just for information to detect invalid situations. * @param[out] unlinked_nodes Unlinked siblings. Can be safely appended to \p node afterwards. * Ordering may change, but there will be no semantic change. * * @return EXIT_SUCCESS on success, -1 on error. */ static int resolve_when_unlink_nodes(struct lys_node *snode, struct lyd_node **node, struct lyd_node **ctx_node, enum lyxp_node_type ctx_node_type, struct lyd_node **unlinked_nodes) { struct lyd_node *next, *elem; const struct lys_node *slast; struct ly_ctx *ctx = snode->module->ctx; switch (snode->nodetype) { case LYS_AUGMENT: case LYS_USES: case LYS_CHOICE: case LYS_CASE: slast = NULL; while ((slast = lys_getnext(slast, snode, NULL, LYS_GETNEXT_PARENTUSES))) { if (slast->nodetype & (LYS_ACTION | LYS_NOTIF)) { continue; } if (resolve_when_unlink_nodes((struct lys_node *)slast, node, ctx_node, ctx_node_type, unlinked_nodes)) { return -1; } } break; case LYS_CONTAINER: case LYS_LIST: case LYS_LEAF: case LYS_LEAFLIST: case LYS_ANYXML: case LYS_ANYDATA: LY_TREE_FOR_SAFE(lyd_first_sibling(*node), next, elem) { if (elem->schema == snode) { if (elem == *ctx_node) { /* We are going to unlink our context node! This normally cannot happen, * but we use normal top-level data nodes for faking a document root node, * so if this is the context node, we just use the next top-level node. * Additionally, it can even happen that there are no top-level data nodes left, * all were unlinked, so in this case we pass NULL as the context node/data tree, * lyxp_eval() can handle this special situation. */ if (ctx_node_type == LYXP_NODE_ELEM) { LOGINT(ctx); return -1; } if (elem->prev == elem) { /* unlinking last top-level element, use an empty data tree */ *ctx_node = NULL; } else { /* in this case just use the previous/last top-level data node */ *ctx_node = elem->prev; } } else if (elem == *node) { /* We are going to unlink the currently processed node. This does not matter that * much, but we would lose access to the original data tree, so just move our * pointer somewhere still inside it. */ if ((*node)->prev != *node) { *node = (*node)->prev; } else { /* the processed node with sibings were all unlinked, oh well */ *node = NULL; } } /* temporarily unlink the node */ lyd_unlink_internal(elem, 0); if (*unlinked_nodes) { if (lyd_insert_after((*unlinked_nodes)->prev, elem)) { LOGINT(ctx); return -1; } } else { *unlinked_nodes = elem; } if (snode->nodetype & (LYS_CONTAINER | LYS_LEAF | LYS_ANYDATA)) { /* there can be only one instance */ break; } } } break; default: LOGINT(ctx); return -1; } return EXIT_SUCCESS; } /** * @brief Relink the unlinked nodes back. * * @param[in] node Data node to link the nodes back to. It can actually be the adjusted context node, * we simply need a sibling from the original data tree. * @param[in] unlinked_nodes Unlinked nodes to relink to \p node. * @param[in] ctx_node_type Context node type to distinguish between \p node being the parent * or the sibling of \p unlinked_nodes. * * @return EXIT_SUCCESS on success, -1 on error. */ static int resolve_when_relink_nodes(struct lyd_node *node, struct lyd_node *unlinked_nodes, enum lyxp_node_type ctx_node_type) { struct lyd_node *elem; LY_TREE_FOR_SAFE(unlinked_nodes, unlinked_nodes, elem) { lyd_unlink_internal(elem, 0); if (ctx_node_type == LYXP_NODE_ELEM) { if (lyd_insert_common(node, NULL, elem, 0)) { return -1; } } else { if (lyd_insert_nextto(node, elem, 0, 0)) { return -1; } } } return EXIT_SUCCESS; } int resolve_applies_must(const struct lyd_node *node) { int ret = 0; uint8_t must_size; struct lys_node *schema, *iter; assert(node); schema = node->schema; /* their own must */ switch (schema->nodetype) { case LYS_CONTAINER: must_size = ((struct lys_node_container *)schema)->must_size; break; case LYS_LEAF: must_size = ((struct lys_node_leaf *)schema)->must_size; break; case LYS_LEAFLIST: must_size = ((struct lys_node_leaflist *)schema)->must_size; break; case LYS_LIST: must_size = ((struct lys_node_list *)schema)->must_size; break; case LYS_ANYXML: case LYS_ANYDATA: must_size = ((struct lys_node_anydata *)schema)->must_size; break; case LYS_NOTIF: must_size = ((struct lys_node_notif *)schema)->must_size; break; default: must_size = 0; break; } if (must_size) { ++ret; } /* schema may be a direct data child of input/output with must (but it must be first, it needs to be evaluated only once) */ if (!node->prev->next) { for (iter = lys_parent(schema); iter && (iter->nodetype & (LYS_CHOICE | LYS_CASE | LYS_USES)); iter = lys_parent(iter)); if (iter && (iter->nodetype & (LYS_INPUT | LYS_OUTPUT))) { ret += 0x2; } } return ret; } static struct lys_when * snode_get_when(const struct lys_node *schema) { switch (schema->nodetype) { case LYS_CONTAINER: return ((struct lys_node_container *)schema)->when; case LYS_CHOICE: return ((struct lys_node_choice *)schema)->when; case LYS_LEAF: return ((struct lys_node_leaf *)schema)->when; case LYS_LEAFLIST: return ((struct lys_node_leaflist *)schema)->when; case LYS_LIST: return ((struct lys_node_list *)schema)->when; case LYS_ANYDATA: case LYS_ANYXML: return ((struct lys_node_anydata *)schema)->when; case LYS_CASE: return ((struct lys_node_case *)schema)->when; case LYS_USES: return ((struct lys_node_uses *)schema)->when; case LYS_AUGMENT: return ((struct lys_node_augment *)schema)->when; default: return NULL; } } int resolve_applies_when(const struct lys_node *schema, int mode, const struct lys_node *stop) { const struct lys_node *parent; assert(schema); if (!(schema->nodetype & (LYS_NOTIF | LYS_RPC)) && snode_get_when(schema)) { return 1; } parent = schema; goto check_augment; while (parent) { /* stop conditions */ if (!mode) { /* stop on node that can be instantiated in data tree */ if (!(parent->nodetype & (LYS_USES | LYS_CHOICE | LYS_CASE))) { break; } } else { /* stop on the specified node */ if (parent == stop) { break; } } if (snode_get_when(parent)) { return 1; } check_augment: if (parent->parent && (parent->parent->nodetype == LYS_AUGMENT) && snode_get_when(parent->parent)) { return 1; } parent = lys_parent(parent); } return 0; } /** * @brief Resolve (check) all when conditions relevant for \p node. * Logs directly. * * @param[in] node Data node, whose conditional reference, if such, is being decided. * @param[in] ignore_fail 1 if when does not have to be satisfied, 2 if it does not have to be satisfied * only when requiring external dependencies. * * @return * -1 - error, ly_errno is set * 0 - all "when" statements true * 0, ly_vecode = LYVE_NOWHEN - some "when" statement false, returned in failed_when * 1, ly_vecode = LYVE_INWHEN - nodes needed to resolve are conditional and not yet resolved (under another "when") */ int resolve_when(struct lyd_node *node, int ignore_fail, struct lys_when **failed_when) { struct lyd_node *ctx_node = NULL, *unlinked_nodes, *tmp_node; struct lys_node *sparent; struct lyxp_set set; enum lyxp_node_type ctx_node_type; struct ly_ctx *ctx = node->schema->module->ctx; int rc = 0; assert(node); memset(&set, 0, sizeof set); if (!(node->schema->nodetype & (LYS_NOTIF | LYS_RPC | LYS_ACTION)) && snode_get_when(node->schema)) { /* make the node dummy for the evaluation */ node->validity |= LYD_VAL_INUSE; rc = lyxp_eval(snode_get_when(node->schema)->cond, node, LYXP_NODE_ELEM, lyd_node_module(node), &set, LYXP_WHEN); node->validity &= ~LYD_VAL_INUSE; if (rc) { if (rc == 1) { LOGVAL(ctx, LYE_INWHEN, LY_VLOG_LYD, node, snode_get_when(node->schema)->cond); } goto cleanup; } /* set boolean result of the condition */ lyxp_set_cast(&set, LYXP_SET_BOOLEAN, node, lyd_node_module(node), LYXP_WHEN); if (!set.val.bool) { node->when_status |= LYD_WHEN_FALSE; if ((ignore_fail == 1) || ((snode_get_when(node->schema)->flags & (LYS_XPCONF_DEP | LYS_XPSTATE_DEP)) && (ignore_fail == 2))) { LOGVRB("When condition \"%s\" is not satisfied, but it is not required.", snode_get_when(node->schema)->cond); } else { LOGVAL(ctx, LYE_NOWHEN, LY_VLOG_LYD, node, snode_get_when(node->schema)->cond); if (failed_when) { *failed_when = snode_get_when(node->schema); } goto cleanup; } } /* free xpath set content */ lyxp_set_cast(&set, LYXP_SET_EMPTY, node, lyd_node_module(node), 0); } sparent = node->schema; goto check_augment; /* check when in every schema node that affects node */ while (sparent && (sparent->nodetype & (LYS_USES | LYS_CHOICE | LYS_CASE))) { if (snode_get_when(sparent)) { if (!ctx_node) { rc = resolve_when_ctx_node(node, sparent, &ctx_node, &ctx_node_type); if (rc) { LOGINT(ctx); goto cleanup; } } unlinked_nodes = NULL; /* we do not want our node pointer to change */ tmp_node = node; rc = resolve_when_unlink_nodes(sparent, &tmp_node, &ctx_node, ctx_node_type, &unlinked_nodes); if (rc) { goto cleanup; } rc = lyxp_eval(snode_get_when(sparent)->cond, ctx_node, ctx_node_type, lys_node_module(sparent), &set, LYXP_WHEN); if (unlinked_nodes && ctx_node) { if (resolve_when_relink_nodes(ctx_node, unlinked_nodes, ctx_node_type)) { rc = -1; goto cleanup; } } if (rc) { if (rc == 1) { LOGVAL(ctx, LYE_INWHEN, LY_VLOG_LYD, node, snode_get_when(sparent)->cond); } goto cleanup; } lyxp_set_cast(&set, LYXP_SET_BOOLEAN, ctx_node, lys_node_module(sparent), LYXP_WHEN); if (!set.val.bool) { if ((ignore_fail == 1) || ((snode_get_when(sparent)->flags & (LYS_XPCONF_DEP | LYS_XPSTATE_DEP)) && (ignore_fail == 2))) { LOGVRB("When condition \"%s\" is not satisfied, but it is not required.", snode_get_when(sparent)->cond); } else { node->when_status |= LYD_WHEN_FALSE; LOGVAL(ctx, LYE_NOWHEN, LY_VLOG_LYD, node, snode_get_when(sparent)->cond); if (failed_when) { *failed_when = snode_get_when(sparent); } goto cleanup; } } /* free xpath set content */ lyxp_set_cast(&set, LYXP_SET_EMPTY, ctx_node, lys_node_module(sparent), 0); } check_augment: if ((sparent->parent && (sparent->parent->nodetype == LYS_AUGMENT) && snode_get_when(sparent->parent))) { if (!ctx_node) { rc = resolve_when_ctx_node(node, sparent->parent, &ctx_node, &ctx_node_type); if (rc) { LOGINT(ctx); goto cleanup; } } unlinked_nodes = NULL; tmp_node = node; rc = resolve_when_unlink_nodes(sparent->parent, &tmp_node, &ctx_node, ctx_node_type, &unlinked_nodes); if (rc) { goto cleanup; } rc = lyxp_eval(snode_get_when(sparent->parent)->cond, ctx_node, ctx_node_type, lys_node_module(sparent->parent), &set, LYXP_WHEN); /* reconnect nodes, if ctx_node is NULL then all the nodes were unlinked, but linked together, * so the tree did not actually change and there is nothing for us to do */ if (unlinked_nodes && ctx_node) { if (resolve_when_relink_nodes(ctx_node, unlinked_nodes, ctx_node_type)) { rc = -1; goto cleanup; } } if (rc) { if (rc == 1) { LOGVAL(ctx, LYE_INWHEN, LY_VLOG_LYD, node, snode_get_when(sparent->parent)->cond); } goto cleanup; } lyxp_set_cast(&set, LYXP_SET_BOOLEAN, ctx_node, lys_node_module(sparent->parent), LYXP_WHEN); if (!set.val.bool) { node->when_status |= LYD_WHEN_FALSE; if ((ignore_fail == 1) || ((snode_get_when(sparent->parent)->flags & (LYS_XPCONF_DEP | LYS_XPSTATE_DEP)) && (ignore_fail == 2))) { LOGVRB("When condition \"%s\" is not satisfied, but it is not required.", snode_get_when(sparent->parent)->cond); } else { LOGVAL(ctx, LYE_NOWHEN, LY_VLOG_LYD, node, snode_get_when(sparent->parent)->cond); if (failed_when) { *failed_when = snode_get_when(sparent->parent); } goto cleanup; } } /* free xpath set content */ lyxp_set_cast(&set, LYXP_SET_EMPTY, ctx_node, lys_node_module(sparent->parent), 0); } sparent = lys_parent(sparent); } node->when_status |= LYD_WHEN_TRUE; cleanup: /* free xpath set content */ lyxp_set_cast(&set, LYXP_SET_EMPTY, ctx_node ? ctx_node : node, NULL, 0); return rc; } static int check_type_union_leafref(struct lys_type *type) { uint8_t i; if ((type->base == LY_TYPE_UNION) && type->info.uni.count) { /* go through unions and look for leafref */ for (i = 0; i < type->info.uni.count; ++i) { switch (type->info.uni.types[i].base) { case LY_TYPE_LEAFREF: return 1; case LY_TYPE_UNION: if (check_type_union_leafref(&type->info.uni.types[i])) { return 1; } break; default: break; } } return 0; } /* just inherit the flag value */ return type->der->has_union_leafref; } /** * @brief Resolve a single unres schema item. Logs indirectly. * * @param[in] mod Main module. * @param[in] item Item to resolve. Type determined by \p type. * @param[in] type Type of the unresolved item. * @param[in] str_snode String, a schema node, or NULL. * @param[in] unres Unres schema structure to use. * @param[in] final_fail Whether we are just printing errors of the failed unres items. * * @return EXIT_SUCCESS on success, EXIT_FAILURE on forward reference, -1 on error. */ static int resolve_unres_schema_item(struct lys_module *mod, void *item, enum UNRES_ITEM type, void *str_snode, struct unres_schema *unres) { /* has_str - whether the str_snode is a string in a dictionary that needs to be freed */ int rc = -1, has_str = 0, parent_type = 0, i, k; unsigned int j; struct ly_ctx * ctx = mod->ctx; struct lys_node *root, *next, *node, *par_grp; const char *expr; uint8_t *u; struct ly_set *refs, *procs; struct lys_feature *ref, *feat; struct lys_ident *ident; struct lys_type *stype; struct lys_node_choice *choic; struct lyxml_elem *yin; struct yang_type *yang; struct unres_list_uniq *unique_info; struct unres_iffeat_data *iff_data; struct unres_ext *ext_data; struct lys_ext_instance *ext, **extlist; struct lyext_plugin *eplugin; switch (type) { case UNRES_IDENT: expr = str_snode; has_str = 1; ident = item; rc = resolve_base_ident(mod, ident, expr, "identity", NULL, unres); break; case UNRES_TYPE_IDENTREF: expr = str_snode; has_str = 1; stype = item; rc = resolve_base_ident(mod, NULL, expr, "type", stype, unres); break; case UNRES_TYPE_LEAFREF: node = str_snode; stype = item; rc = resolve_schema_leafref(stype, node, unres); break; case UNRES_TYPE_DER_EXT: parent_type++; /* falls through */ case UNRES_TYPE_DER_TPDF: parent_type++; /* falls through */ case UNRES_TYPE_DER: /* parent */ node = str_snode; stype = item; /* HACK type->der is temporarily unparsed type statement */ yin = (struct lyxml_elem *)stype->der; stype->der = NULL; if (yin->flags & LY_YANG_STRUCTURE_FLAG) { yang = (struct yang_type *)yin; rc = yang_check_type(mod, node, yang, stype, parent_type, unres); if (rc) { /* may try again later */ stype->der = (struct lys_tpdf *)yang; } else { /* we need to always be able to free this, it's safe only in this case */ lydict_remove(ctx, yang->name); free(yang); } } else { rc = fill_yin_type(mod, node, yin, stype, parent_type, unres); if (!rc || rc == -1) { /* we need to always be able to free this, it's safe only in this case */ lyxml_free(ctx, yin); } else { /* may try again later, put all back how it was */ stype->der = (struct lys_tpdf *)yin; } } if (rc == EXIT_SUCCESS) { /* it does not make sense to have leaf-list of empty type */ if (!parent_type && node->nodetype == LYS_LEAFLIST && stype->base == LY_TYPE_EMPTY) { LOGWRN(ctx, "The leaf-list \"%s\" is of \"empty\" type, which does not make sense.", node->name); } if ((type == UNRES_TYPE_DER_TPDF) && (stype->base == LY_TYPE_UNION)) { /* fill typedef union leafref flag */ ((struct lys_tpdf *)stype->parent)->has_union_leafref = check_type_union_leafref(stype); } else if ((type == UNRES_TYPE_DER) && stype->der->has_union_leafref) { /* copy the type in case it has union leafref flag */ if (lys_copy_union_leafrefs(mod, node, stype, NULL, unres)) { LOGERR(ctx, LY_EINT, "Failed to duplicate type."); return -1; } } } else if (rc == EXIT_FAILURE && !(stype->value_flags & LY_VALUE_UNRESGRP)) { /* forward reference - in case the type is in grouping, we have to make the grouping unusable * by uses statement until the type is resolved. We do that the same way as uses statements inside * grouping. The grouping cannot be used unless the unres counter is 0. * To remember that the grouping already increased the counter, the LYTYPE_GRP is used as value * of the type's base member. */ for (par_grp = node; par_grp && (par_grp->nodetype != LYS_GROUPING); par_grp = lys_parent(par_grp)); if (par_grp) { if (++((struct lys_node_grp *)par_grp)->unres_count == 0) { LOGERR(ctx, LY_EINT, "Too many unresolved items (type) inside a grouping."); return -1; } stype->value_flags |= LY_VALUE_UNRESGRP; } } break; case UNRES_IFFEAT: iff_data = str_snode; rc = resolve_feature(iff_data->fname, strlen(iff_data->fname), iff_data->node, item); if (!rc) { /* success */ if (iff_data->infeature) { /* store backlink into the target feature to allow reverse changes in case of changing feature status */ feat = *((struct lys_feature **)item); if (!feat->depfeatures) { feat->depfeatures = ly_set_new(); } ly_set_add(feat->depfeatures, iff_data->node, LY_SET_OPT_USEASLIST); } /* cleanup temporary data */ lydict_remove(ctx, iff_data->fname); free(iff_data); } break; case UNRES_FEATURE: feat = (struct lys_feature *)item; if (feat->iffeature_size) { refs = ly_set_new(); procs = ly_set_new(); ly_set_add(procs, feat, 0); while (procs->number) { ref = procs->set.g[procs->number - 1]; ly_set_rm_index(procs, procs->number - 1); for (i = 0; i < ref->iffeature_size; i++) { resolve_iffeature_getsizes(&ref->iffeature[i], NULL, &j); for (; j > 0 ; j--) { if (ref->iffeature[i].features[j - 1]) { if (ref->iffeature[i].features[j - 1] == feat) { LOGVAL(ctx, LYE_CIRC_FEATURES, LY_VLOG_NONE, NULL, feat->name); goto featurecheckdone; } if (ref->iffeature[i].features[j - 1]->iffeature_size) { k = refs->number; if (ly_set_add(refs, ref->iffeature[i].features[j - 1], 0) == k) { /* not yet seen feature, add it for processing */ ly_set_add(procs, ref->iffeature[i].features[j - 1], 0); } } } else { /* forward reference */ rc = EXIT_FAILURE; goto featurecheckdone; } } } } rc = EXIT_SUCCESS; featurecheckdone: ly_set_free(refs); ly_set_free(procs); } break; case UNRES_USES: rc = resolve_unres_schema_uses(item, unres); break; case UNRES_TYPEDEF_DFLT: parent_type++; /* falls through */ case UNRES_TYPE_DFLT: stype = item; rc = check_default(stype, (const char **)str_snode, mod, parent_type); if ((rc == EXIT_FAILURE) && !parent_type && (stype->base == LY_TYPE_LEAFREF)) { for (par_grp = (struct lys_node *)stype->parent; par_grp && (par_grp->nodetype != LYS_GROUPING); par_grp = lys_parent(par_grp)); if (par_grp) { /* checking default value in a grouping finished with forward reference means we cannot check the value */ rc = EXIT_SUCCESS; } } break; case UNRES_CHOICE_DFLT: expr = str_snode; has_str = 1; choic = item; if (!choic->dflt) { choic->dflt = resolve_choice_dflt(choic, expr); } if (choic->dflt) { rc = lyp_check_mandatory_choice((struct lys_node *)choic); } else { rc = EXIT_FAILURE; } break; case UNRES_LIST_KEYS: rc = resolve_list_keys(item, ((struct lys_node_list *)item)->keys_str); break; case UNRES_LIST_UNIQ: unique_info = (struct unres_list_uniq *)item; rc = resolve_unique(unique_info->list, unique_info->expr, unique_info->trg_type); break; case UNRES_AUGMENT: rc = resolve_augment(item, NULL, unres); break; case UNRES_XPATH: node = (struct lys_node *)item; rc = check_xpath(node, 1); break; case UNRES_MOD_IMPLEMENT: rc = lys_make_implemented_r(mod, unres); break; case UNRES_EXT: ext_data = (struct unres_ext *)str_snode; extlist = &(*(struct lys_ext_instance ***)item)[ext_data->ext_index]; rc = resolve_extension(ext_data, extlist, unres); if (!rc) { /* success */ /* is there a callback to be done to finalize the extension? */ eplugin = extlist[0]->def->plugin; if (eplugin) { if (eplugin->check_result || (eplugin->flags & LYEXT_OPT_INHERIT)) { u = malloc(sizeof *u); LY_CHECK_ERR_RETURN(!u, LOGMEM(ctx), -1); (*u) = ext_data->ext_index; if (unres_schema_add_node(mod, unres, item, UNRES_EXT_FINALIZE, (struct lys_node *)u) == -1) { /* something really bad happend since the extension finalization is not actually * being resolved while adding into unres, so something more serious with the unres * list itself must happened */ return -1; } } } } if (!rc || rc == -1) { /* cleanup on success or fatal error */ if (ext_data->datatype == LYS_IN_YIN) { /* YIN */ lyxml_free(ctx, ext_data->data.yin); } else { /* YANG */ yang_free_ext_data(ext_data->data.yang); } free(ext_data); } break; case UNRES_EXT_FINALIZE: u = (uint8_t *)str_snode; ext = (*(struct lys_ext_instance ***)item)[*u]; free(u); eplugin = ext->def->plugin; /* inherit */ if ((eplugin->flags & LYEXT_OPT_INHERIT) && (ext->parent_type == LYEXT_PAR_NODE)) { root = (struct lys_node *)ext->parent; if (!(root->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA))) { LY_TREE_DFS_BEGIN(root->child, next, node) { /* first, check if the node already contain instance of the same extension, * in such a case we won't inherit. In case the node was actually defined as * augment data, we are supposed to check the same way also the augment node itself */ if (lys_ext_instance_presence(ext->def, node->ext, node->ext_size) != -1) { goto inherit_dfs_sibling; } else if (node->parent != root && node->parent->nodetype == LYS_AUGMENT && lys_ext_instance_presence(ext->def, node->parent->ext, node->parent->ext_size) != -1) { goto inherit_dfs_sibling; } if (eplugin->check_inherit) { /* we have a callback to check the inheritance, use it */ switch ((rc = (*eplugin->check_inherit)(ext, node))) { case 0: /* yes - continue with the inheriting code */ break; case 1: /* no - continue with the node's sibling */ goto inherit_dfs_sibling; case 2: /* no, but continue with the children, just skip the inheriting code for this node */ goto inherit_dfs_child; default: LOGERR(ctx, LY_EINT, "Plugin's (%s:%s) check_inherit callback returns invalid value (%d),", ext->def->module->name, ext->def->name, rc); } } /* inherit the extension */ extlist = realloc(node->ext, (node->ext_size + 1) * sizeof *node->ext); LY_CHECK_ERR_RETURN(!extlist, LOGMEM(ctx), -1); extlist[node->ext_size] = malloc(sizeof **extlist); LY_CHECK_ERR_RETURN(!extlist[node->ext_size], LOGMEM(ctx); node->ext = extlist, -1); memcpy(extlist[node->ext_size], ext, sizeof *ext); extlist[node->ext_size]->flags |= LYEXT_OPT_INHERIT; node->ext = extlist; node->ext_size++; inherit_dfs_child: /* modification of - select element for the next run - children first */ if (node->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA)) { next = NULL; } else { next = node->child; } if (!next) { inherit_dfs_sibling: /* no children, try siblings */ next = node->next; } while (!next) { /* go to the parent */ node = lys_parent(node); /* we are done if we are back in the root (the starter's parent */ if (node == root) { break; } /* parent is already processed, go to its sibling */ next = node->next; } } } } /* final check */ if (eplugin->check_result) { if ((*eplugin->check_result)(ext)) { LOGERR(ctx, LY_EPLUGIN, "Resolving extension failed."); return -1; } } rc = 0; break; default: LOGINT(ctx); break; } if (has_str && !rc) { /* the string is no more needed in case of success. * In case of forward reference, we will try to resolve the string later */ lydict_remove(ctx, str_snode); } return rc; } /* logs directly */ static void print_unres_schema_item_fail(void *item, enum UNRES_ITEM type, void *str_node) { struct lyxml_elem *xml; struct lyxml_attr *attr; struct unres_iffeat_data *iff_data; const char *name = NULL; struct unres_ext *extinfo; switch (type) { case UNRES_IDENT: LOGVRB("Resolving %s \"%s\" failed, it will be attempted later.", "identity", (char *)str_node); break; case UNRES_TYPE_IDENTREF: LOGVRB("Resolving %s \"%s\" failed, it will be attempted later.", "identityref", (char *)str_node); break; case UNRES_TYPE_LEAFREF: LOGVRB("Resolving %s \"%s\" failed, it will be attempted later.", "leafref", ((struct lys_type *)item)->info.lref.path); break; case UNRES_TYPE_DER_EXT: case UNRES_TYPE_DER_TPDF: case UNRES_TYPE_DER: xml = (struct lyxml_elem *)((struct lys_type *)item)->der; if (xml->flags & LY_YANG_STRUCTURE_FLAG) { name = ((struct yang_type *)xml)->name; } else { LY_TREE_FOR(xml->attr, attr) { if ((attr->type == LYXML_ATTR_STD) && !strcmp(attr->name, "name")) { name = attr->value; break; } } assert(attr); } LOGVRB("Resolving %s \"%s\" failed, it will be attempted later.", "derived type", name); break; case UNRES_IFFEAT: iff_data = str_node; LOGVRB("Resolving %s \"%s\" failed, it will be attempted later.", "if-feature", iff_data->fname); break; case UNRES_FEATURE: LOGVRB("There are unresolved if-features for \"%s\" feature circular dependency check, it will be attempted later", ((struct lys_feature *)item)->name); break; case UNRES_USES: LOGVRB("Resolving %s \"%s\" failed, it will be attempted later.", "uses", ((struct lys_node_uses *)item)->name); break; case UNRES_TYPEDEF_DFLT: case UNRES_TYPE_DFLT: if (*(char **)str_node) { LOGVRB("Resolving %s \"%s\" failed, it will be attempted later.", "type default", *(char **)str_node); } /* else no default value in the type itself, but we are checking some restrictions against * possible default value of some base type. The failure is caused by not resolved base type, * so it was already reported */ break; case UNRES_CHOICE_DFLT: LOGVRB("Resolving %s \"%s\" failed, it will be attempted later.", "choice default", (char *)str_node); break; case UNRES_LIST_KEYS: LOGVRB("Resolving %s \"%s\" failed, it will be attempted later.", "list keys", (char *)str_node); break; case UNRES_LIST_UNIQ: LOGVRB("Resolving %s \"%s\" failed, it will be attempted later.", "list unique", (char *)str_node); break; case UNRES_AUGMENT: LOGVRB("Resolving %s \"%s\" failed, it will be attempted later.", "augment target", ((struct lys_node_augment *)item)->target_name); break; case UNRES_XPATH: LOGVRB("Resolving %s \"%s\" failed, it will be attempted later.", "XPath expressions of", ((struct lys_node *)item)->name); break; case UNRES_EXT: extinfo = (struct unres_ext *)str_node; name = extinfo->datatype == LYS_IN_YIN ? extinfo->data.yin->name : NULL; /* TODO YANG extension */ LOGVRB("Resolving extension \"%s\" failed, it will be attempted later.", name); break; default: LOGINT(NULL); break; } } static int resolve_unres_schema_types(struct unres_schema *unres, enum UNRES_ITEM types, struct ly_ctx *ctx, int forward_ref, int print_all_errors, uint32_t *resolved) { uint32_t i, unres_count, res_count; int ret = 0, rc; struct ly_err_item *prev_eitem; enum int_log_opts prev_ilo; LY_ERR prev_ly_errno; /* if there can be no forward references, every failure is final, so we can print it directly */ if (forward_ref) { prev_ly_errno = ly_errno; ly_ilo_change(ctx, ILO_STORE, &prev_ilo, &prev_eitem); } do { unres_count = 0; res_count = 0; for (i = 0; i < unres->count; ++i) { /* UNRES_TYPE_LEAFREF must be resolved (for storing leafref target pointers); * if-features are resolved here to make sure that we will have all if-features for * later check of feature circular dependency */ if (unres->type[i] & types) { ++unres_count; rc = resolve_unres_schema_item(unres->module[i], unres->item[i], unres->type[i], unres->str_snode[i], unres); if (unres->type[i] == UNRES_EXT_FINALIZE) { /* to avoid double free */ unres->type[i] = UNRES_RESOLVED; } if (!rc || (unres->type[i] == UNRES_XPATH)) { /* invalid XPath can never cause an error, only a warning */ if (unres->type[i] == UNRES_LIST_UNIQ) { /* free the allocated structure */ free(unres->item[i]); } unres->type[i] = UNRES_RESOLVED; ++(*resolved); ++res_count; } else if ((rc == EXIT_FAILURE) && forward_ref) { /* forward reference, erase errors */ ly_err_free_next(ctx, prev_eitem); } else if (print_all_errors) { /* just so that we quit the loop */ ++res_count; ret = -1; } else { if (forward_ref) { ly_ilo_restore(ctx, prev_ilo, prev_eitem, 1); } return -1; } } } } while (res_count && (res_count < unres_count)); if (res_count < unres_count) { assert(forward_ref); /* just print the errors (but we must free the ones we have and get them again :-/ ) */ ly_ilo_restore(ctx, prev_ilo, prev_eitem, 0); for (i = 0; i < unres->count; ++i) { if (unres->type[i] & types) { resolve_unres_schema_item(unres->module[i], unres->item[i], unres->type[i], unres->str_snode[i], unres); } } return -1; } if (forward_ref) { /* restore log */ ly_ilo_restore(ctx, prev_ilo, prev_eitem, 0); ly_errno = prev_ly_errno; } return ret; } /** * @brief Resolve every unres schema item in the structure. Logs directly. * * @param[in] mod Main module. * @param[in] unres Unres schema structure to use. * * @return EXIT_SUCCESS on success, -1 on error. */ int resolve_unres_schema(struct lys_module *mod, struct unres_schema *unres) { uint32_t resolved = 0; assert(unres); LOGVRB("Resolving \"%s\" unresolved schema nodes and their constraints...", mod->name); /* UNRES_TYPE_LEAFREF must be resolved (for storing leafref target pointers); * if-features are resolved here to make sure that we will have all if-features for * later check of feature circular dependency */ if (resolve_unres_schema_types(unres, UNRES_USES | UNRES_IFFEAT | UNRES_TYPE_DER | UNRES_TYPE_DER_TPDF | UNRES_TYPE_DER_TPDF | UNRES_TYPE_LEAFREF | UNRES_MOD_IMPLEMENT | UNRES_AUGMENT | UNRES_CHOICE_DFLT | UNRES_IDENT, mod->ctx, 1, 0, &resolved)) { return -1; } /* another batch of resolved items */ if (resolve_unres_schema_types(unres, UNRES_TYPE_IDENTREF | UNRES_FEATURE | UNRES_TYPEDEF_DFLT | UNRES_TYPE_DFLT | UNRES_LIST_KEYS | UNRES_LIST_UNIQ | UNRES_EXT, mod->ctx, 1, 0, &resolved)) { return -1; } /* print xpath warnings and finalize extensions, keep it last to provide the complete schema tree information to the plugin's checkers */ if (resolve_unres_schema_types(unres, UNRES_XPATH | UNRES_EXT_FINALIZE, mod->ctx, 0, 1, &resolved)) { return -1; } LOGVRB("All \"%s\" schema nodes and constraints resolved.", mod->name); unres->count = 0; return EXIT_SUCCESS; } /** * @brief Try to resolve an unres schema item with a string argument. Logs indirectly. * * @param[in] mod Main module. * @param[in] unres Unres schema structure to use. * @param[in] item Item to resolve. Type determined by \p type. * @param[in] type Type of the unresolved item. * @param[in] str String argument. * * @return EXIT_SUCCESS on success, EXIT_FAILURE on storing the item in unres, -1 on error. */ int unres_schema_add_str(struct lys_module *mod, struct unres_schema *unres, void *item, enum UNRES_ITEM type, const char *str) { int rc; const char *dictstr; dictstr = lydict_insert(mod->ctx, str, 0); rc = unres_schema_add_node(mod, unres, item, type, (struct lys_node *)dictstr); if (rc < 0) { lydict_remove(mod->ctx, dictstr); } return rc; } /** * @brief Try to resolve an unres schema item with a schema node argument. Logs indirectly. * * @param[in] mod Main module. * @param[in] unres Unres schema structure to use. * @param[in] item Item to resolve. Type determined by \p type. * @param[in] type Type of the unresolved item. UNRES_TYPE_DER is handled specially! * @param[in] snode Schema node argument. * * @return EXIT_SUCCESS on success, EXIT_FAILURE on storing the item in unres, -1 on error. */ int unres_schema_add_node(struct lys_module *mod, struct unres_schema *unres, void *item, enum UNRES_ITEM type, struct lys_node *snode) { int rc; uint32_t u; enum int_log_opts prev_ilo; struct ly_err_item *prev_eitem; LY_ERR prev_ly_errno; struct lyxml_elem *yin; struct ly_ctx *ctx = mod->ctx; assert(unres && (item || (type == UNRES_MOD_IMPLEMENT)) && ((type != UNRES_LEAFREF) && (type != UNRES_INSTID) && (type != UNRES_WHEN) && (type != UNRES_MUST))); /* check for duplicities in unres */ for (u = 0; u < unres->count; u++) { if (unres->type[u] == type && unres->item[u] == item && unres->str_snode[u] == snode && unres->module[u] == mod) { /* duplication can happen when the node contains multiple statements of the same type to check, * this can happen for example when refinement is being applied, so we just postpone the processing * and do not duplicate the information */ return EXIT_FAILURE; } } if ((type == UNRES_EXT_FINALIZE) || (type == UNRES_XPATH) || (type == UNRES_MOD_IMPLEMENT)) { /* extension finalization is not even tried when adding the item into the inres list, * xpath is not tried because it would hide some potential warnings, * implementing module must be deferred because some other nodes can be added that will need to be traversed * and their targets made implemented */ rc = EXIT_FAILURE; } else { prev_ly_errno = ly_errno; ly_ilo_change(ctx, ILO_STORE, &prev_ilo, &prev_eitem); rc = resolve_unres_schema_item(mod, item, type, snode, unres); if (rc != EXIT_FAILURE) { ly_ilo_restore(ctx, prev_ilo, prev_eitem, rc == -1 ? 1 : 0); if (rc != -1) { ly_errno = prev_ly_errno; } if (type == UNRES_LIST_UNIQ) { /* free the allocated structure */ free(item); } else if (rc == -1 && type == UNRES_IFFEAT) { /* free the allocated resources */ free(*((char **)item)); } return rc; } else { /* erase info about validation errors */ ly_ilo_restore(ctx, prev_ilo, prev_eitem, 0); ly_errno = prev_ly_errno; } print_unres_schema_item_fail(item, type, snode); /* HACK unlinking is performed here so that we do not do any (NS) copying in vain */ if (type == UNRES_TYPE_DER || type == UNRES_TYPE_DER_TPDF) { yin = (struct lyxml_elem *)((struct lys_type *)item)->der; if (!(yin->flags & LY_YANG_STRUCTURE_FLAG)) { lyxml_unlink_elem(mod->ctx, yin, 1); ((struct lys_type *)item)->der = (struct lys_tpdf *)yin; } } } unres->count++; unres->item = ly_realloc(unres->item, unres->count*sizeof *unres->item); LY_CHECK_ERR_RETURN(!unres->item, LOGMEM(ctx), -1); unres->item[unres->count-1] = item; unres->type = ly_realloc(unres->type, unres->count*sizeof *unres->type); LY_CHECK_ERR_RETURN(!unres->type, LOGMEM(ctx), -1); unres->type[unres->count-1] = type; unres->str_snode = ly_realloc(unres->str_snode, unres->count*sizeof *unres->str_snode); LY_CHECK_ERR_RETURN(!unres->str_snode, LOGMEM(ctx), -1); unres->str_snode[unres->count-1] = snode; unres->module = ly_realloc(unres->module, unres->count*sizeof *unres->module); LY_CHECK_ERR_RETURN(!unres->module, LOGMEM(ctx), -1); unres->module[unres->count-1] = mod; return rc; } /** * @brief Duplicate an unres schema item. Logs indirectly. * * @param[in] mod Main module. * @param[in] unres Unres schema structure to use. * @param[in] item Old item to be resolved. * @param[in] type Type of the old unresolved item. * @param[in] new_item New item to use in the duplicate. * * @return EXIT_SUCCESS on success, EXIT_FAILURE if item is not in unres, -1 on error. */ int unres_schema_dup(struct lys_module *mod, struct unres_schema *unres, void *item, enum UNRES_ITEM type, void *new_item) { int i; struct unres_list_uniq aux_uniq; struct unres_iffeat_data *iff_data; assert(item && new_item && ((type != UNRES_LEAFREF) && (type != UNRES_INSTID) && (type != UNRES_WHEN))); /* hack for UNRES_LIST_UNIQ, which stores multiple items behind its item */ if (type == UNRES_LIST_UNIQ) { aux_uniq.list = item; aux_uniq.expr = ((struct unres_list_uniq *)new_item)->expr; item = &aux_uniq; } i = unres_schema_find(unres, -1, item, type); if (i == -1) { if (type == UNRES_LIST_UNIQ) { free(new_item); } return EXIT_FAILURE; } if ((type == UNRES_TYPE_LEAFREF) || (type == UNRES_USES) || (type == UNRES_TYPE_DFLT) || (type == UNRES_FEATURE) || (type == UNRES_LIST_UNIQ)) { if (unres_schema_add_node(mod, unres, new_item, type, unres->str_snode[i]) == -1) { LOGINT(mod->ctx); return -1; } } else if (type == UNRES_IFFEAT) { /* duplicate unres_iffeature_data */ iff_data = malloc(sizeof *iff_data); LY_CHECK_ERR_RETURN(!iff_data, LOGMEM(mod->ctx), -1); iff_data->fname = lydict_insert(mod->ctx, ((struct unres_iffeat_data *)unres->str_snode[i])->fname, 0); iff_data->node = ((struct unres_iffeat_data *)unres->str_snode[i])->node; if (unres_schema_add_node(mod, unres, new_item, type, (struct lys_node *)iff_data) == -1) { LOGINT(mod->ctx); return -1; } } else { if (unres_schema_add_str(mod, unres, new_item, type, unres->str_snode[i]) == -1) { LOGINT(mod->ctx); return -1; } } return EXIT_SUCCESS; } /* does not log */ int unres_schema_find(struct unres_schema *unres, int start_on_backwards, void *item, enum UNRES_ITEM type) { int i; struct unres_list_uniq *aux_uniq1, *aux_uniq2; if (!unres->count) { return -1; } if (start_on_backwards >= 0) { i = start_on_backwards; } else { i = unres->count - 1; } for (; i > -1; i--) { if (unres->type[i] != type) { continue; } if (type != UNRES_LIST_UNIQ) { if (unres->item[i] == item) { break; } } else { aux_uniq1 = (struct unres_list_uniq *)unres->item[i]; aux_uniq2 = (struct unres_list_uniq *)item; if ((aux_uniq1->list == aux_uniq2->list) && ly_strequal(aux_uniq1->expr, aux_uniq2->expr, 0)) { break; } } } return i; } static void unres_schema_free_item(struct ly_ctx *ctx, struct unres_schema *unres, uint32_t i) { struct lyxml_elem *yin; struct yang_type *yang; struct unres_iffeat_data *iff_data; switch (unres->type[i]) { case UNRES_TYPE_DER_TPDF: case UNRES_TYPE_DER: yin = (struct lyxml_elem *)((struct lys_type *)unres->item[i])->der; if (yin->flags & LY_YANG_STRUCTURE_FLAG) { yang =(struct yang_type *)yin; ((struct lys_type *)unres->item[i])->base = yang->base; lydict_remove(ctx, yang->name); free(yang); if (((struct lys_type *)unres->item[i])->base == LY_TYPE_UNION) { yang_free_type_union(ctx, (struct lys_type *)unres->item[i]); } } else { lyxml_free(ctx, yin); } break; case UNRES_IFFEAT: iff_data = (struct unres_iffeat_data *)unres->str_snode[i]; lydict_remove(ctx, iff_data->fname); free(unres->str_snode[i]); break; case UNRES_IDENT: case UNRES_TYPE_IDENTREF: case UNRES_CHOICE_DFLT: case UNRES_LIST_KEYS: lydict_remove(ctx, (const char *)unres->str_snode[i]); break; case UNRES_LIST_UNIQ: free(unres->item[i]); break; case UNRES_EXT: free(unres->str_snode[i]); break; case UNRES_EXT_FINALIZE: free(unres->str_snode[i]); default: break; } unres->type[i] = UNRES_RESOLVED; } void unres_schema_free(struct lys_module *module, struct unres_schema **unres, int all) { uint32_t i; unsigned int unresolved = 0; if (!unres || !(*unres)) { return; } assert(module || ((*unres)->count == 0)); for (i = 0; i < (*unres)->count; ++i) { if (!all && ((*unres)->module[i] != module)) { if ((*unres)->type[i] != UNRES_RESOLVED) { unresolved++; } continue; } /* free heap memory for the specific item */ unres_schema_free_item(module->ctx, *unres, i); } /* free it all */ if (!module || all || (!unresolved && !module->type)) { free((*unres)->item); free((*unres)->type); free((*unres)->str_snode); free((*unres)->module); free((*unres)); (*unres) = NULL; } } /* check whether instance-identifier points outside its data subtree (for operation it is any node * outside the operation subtree, otherwise it is a node from a foreign model) */ static int check_instid_ext_dep(const struct lys_node *sleaf, const char *json_instid) { const struct lys_node *op_node, *first_node; enum int_log_opts prev_ilo; char *buf, *tmp; if (!json_instid || !json_instid[0]) { /* no/empty value */ return 0; } for (op_node = lys_parent(sleaf); op_node && !(op_node->nodetype & (LYS_NOTIF | LYS_RPC | LYS_ACTION)); op_node = lys_parent(op_node)); if (op_node && lys_parent(op_node)) { /* nested operation - any absolute path is external */ return 1; } /* get the first node from the instid */ tmp = strchr(json_instid + 1, '/'); buf = strndup(json_instid, tmp ? (size_t)(tmp - json_instid) : strlen(json_instid)); if (!buf) { /* so that we do not have to bother with logging, say it is not external */ return 0; } /* find the first schema node, do not log */ ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, NULL); first_node = ly_ctx_get_node(NULL, sleaf, buf, 0); ly_ilo_restore(NULL, prev_ilo, NULL, 0); free(buf); if (!first_node) { /* unknown path, say it is external */ return 1; } /* based on the first schema node in the path we can decide whether it points to an external tree or not */ if (op_node) { if (op_node != first_node) { /* it is a top-level operation, so we're good if it points somewhere inside it */ return 1; } } else { if (lys_node_module(sleaf) != lys_node_module(first_node)) { /* modules differ */ return 1; } } return 0; } /** * @brief Resolve instance-identifier in JSON data format. Logs directly. * * @param[in] data Data node where the path is used * @param[in] path Instance-identifier node value. * @param[in,out] ret Resolved instance or NULL. * * @return 0 on success (even if unresolved and \p ret is NULL), -1 on error. */ static int resolve_instid(struct lyd_node *data, const char *path, int req_inst, struct lyd_node **ret) { int i = 0, j, parsed, cur_idx; const struct lys_module *mod, *prev_mod = NULL; struct ly_ctx *ctx = data->schema->module->ctx; struct lyd_node *root, *node; const char *model = NULL, *name; char *str; int mod_len, name_len, has_predicate; struct unres_data node_match; memset(&node_match, 0, sizeof node_match); *ret = NULL; /* we need root to resolve absolute path */ for (root = data; root->parent; root = root->parent); /* we're still parsing it and the pointer is not correct yet */ if (root->prev) { for (; root->prev->next; root = root->prev); } /* search for the instance node */ while (path[i]) { j = parse_instance_identifier(&path[i], &model, &mod_len, &name, &name_len, &has_predicate); if (j <= 0) { LOGVAL(ctx, LYE_INCHAR, LY_VLOG_LYD, data, path[i-j], &path[i-j]); goto error; } i += j; if (model) { str = strndup(model, mod_len); if (!str) { LOGMEM(ctx); goto error; } mod = ly_ctx_get_module(ctx, str, NULL, 1); if (ctx->data_clb) { if (!mod) { mod = ctx->data_clb(ctx, str, NULL, 0, ctx->data_clb_data); } else if (!mod->implemented) { mod = ctx->data_clb(ctx, mod->name, mod->ns, LY_MODCLB_NOT_IMPLEMENTED, ctx->data_clb_data); } } free(str); if (!mod || !mod->implemented || mod->disabled) { break; } } else if (!prev_mod) { /* first iteration and we are missing module name */ LOGVAL(ctx, LYE_INELEM_LEN, LY_VLOG_LYD, data, name_len, name); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Instance-identifier is missing prefix in the first node."); goto error; } else { mod = prev_mod; } if (resolve_data(mod, name, name_len, root, &node_match)) { /* no instance exists */ break; } if (has_predicate) { /* we have predicate, so the current results must be list or leaf-list */ parsed = j = 0; /* index of the current node (for lists with position predicates) */ cur_idx = 1; while (j < (signed)node_match.count) { node = node_match.node[j]; parsed = resolve_instid_predicate(mod, &path[i], &node, cur_idx); if (parsed < 1) { LOGVAL(ctx, LYE_INPRED, LY_VLOG_LYD, data, &path[i - parsed]); goto error; } if (!node) { /* current node does not satisfy the predicate */ unres_data_del(&node_match, j); } else { ++j; } ++cur_idx; } i += parsed; } else if (node_match.count) { /* check that we are not addressing lists */ for (j = 0; (unsigned)j < node_match.count; ++j) { if (node_match.node[j]->schema->nodetype == LYS_LIST) { unres_data_del(&node_match, j--); } } if (!node_match.count) { LOGVAL(ctx, LYE_SPEC, LY_VLOG_LYD, data, "Instance identifier is missing list keys."); } } prev_mod = mod; } if (!node_match.count) { /* no instance exists */ if (req_inst > -1) { LOGVAL(ctx, LYE_NOREQINS, LY_VLOG_LYD, data, path); return EXIT_FAILURE; } LOGVRB("There is no instance of \"%s\", but it is not required.", path); return EXIT_SUCCESS; } else if (node_match.count > 1) { /* instance identifier must resolve to a single node */ LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYD, data, path, "data tree"); goto error; } else { /* we have required result, remember it and cleanup */ *ret = node_match.node[0]; free(node_match.node); return EXIT_SUCCESS; } error: /* cleanup */ free(node_match.node); return -1; } static int resolve_leafref(struct lyd_node_leaf_list *leaf, const char *path, int req_inst, struct lyd_node **ret) { struct lyxp_set xp_set; uint32_t i; memset(&xp_set, 0, sizeof xp_set); *ret = NULL; /* syntax was already checked, so just evaluate the path using standard XPath */ if (lyxp_eval(path, (struct lyd_node *)leaf, LYXP_NODE_ELEM, lyd_node_module((struct lyd_node *)leaf), &xp_set, 0) != EXIT_SUCCESS) { return -1; } if (xp_set.type == LYXP_SET_NODE_SET) { for (i = 0; i < xp_set.used; ++i) { if ((xp_set.val.nodes[i].type != LYXP_NODE_ELEM) || !(xp_set.val.nodes[i].node->schema->nodetype & (LYS_LEAF | LYS_LEAFLIST))) { continue; } /* not that the value is already in canonical form since the parsers does the conversion, * so we can simply compare just the values */ if (ly_strequal(leaf->value_str, ((struct lyd_node_leaf_list *)xp_set.val.nodes[i].node)->value_str, 1)) { /* we have the match */ *ret = xp_set.val.nodes[i].node; break; } } } lyxp_set_cast(&xp_set, LYXP_SET_EMPTY, (struct lyd_node *)leaf, NULL, 0); if (!*ret) { /* reference not found */ if (req_inst > -1) { LOGVAL(leaf->schema->module->ctx, LYE_NOLEAFREF, LY_VLOG_LYD, leaf, path, leaf->value_str); return EXIT_FAILURE; } else { LOGVRB("There is no leafref \"%s\" with the value \"%s\", but it is not required.", path, leaf->value_str); } } return EXIT_SUCCESS; } /* ignore fail because we are parsing edit-config, get, or get-config - but only if the union includes leafref or instid */ int resolve_union(struct lyd_node_leaf_list *leaf, struct lys_type *type, int store, int ignore_fail, struct lys_type **resolved_type) { struct ly_ctx *ctx = leaf->schema->module->ctx; struct lys_type *t; struct lyd_node *ret; enum int_log_opts prev_ilo; int found, success = 0, ext_dep, req_inst; const char *json_val = NULL; assert(type->base == LY_TYPE_UNION); if ((leaf->value_type == LY_TYPE_UNION) || ((leaf->value_type == LY_TYPE_INST) && (leaf->value_flags & LY_VALUE_UNRES))) { /* either NULL or instid previously converted to JSON */ json_val = lydict_insert(ctx, leaf->value.string, 0); } if (store) { lyd_free_value(leaf->value, leaf->value_type, leaf->value_flags, &((struct lys_node_leaf *)leaf->schema)->type, leaf->value_str, NULL, NULL, NULL); memset(&leaf->value, 0, sizeof leaf->value); } /* turn logging off, we are going to try to validate the value with all the types in order */ ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, 0); t = NULL; found = 0; while ((t = lyp_get_next_union_type(type, t, &found))) { found = 0; switch (t->base) { case LY_TYPE_LEAFREF: if ((ignore_fail == 1) || ((leaf->schema->flags & LYS_LEAFREF_DEP) && (ignore_fail == 2))) { req_inst = -1; } else { req_inst = t->info.lref.req; } if (!resolve_leafref(leaf, t->info.lref.path, req_inst, &ret)) { if (store) { if (ret && !(leaf->schema->flags & LYS_LEAFREF_DEP)) { /* valid resolved */ leaf->value.leafref = ret; leaf->value_type = LY_TYPE_LEAFREF; } else { /* valid unresolved */ ly_ilo_restore(NULL, prev_ilo, NULL, 0); if (!lyp_parse_value(t, &leaf->value_str, NULL, leaf, NULL, NULL, 1, 0, 0)) { return -1; } ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, NULL); } } success = 1; } break; case LY_TYPE_INST: ext_dep = check_instid_ext_dep(leaf->schema, (json_val ? json_val : leaf->value_str)); if ((ignore_fail == 1) || (ext_dep && (ignore_fail == 2))) { req_inst = -1; } else { req_inst = t->info.inst.req; } if (!resolve_instid((struct lyd_node *)leaf, (json_val ? json_val : leaf->value_str), req_inst, &ret)) { if (store) { if (ret && !ext_dep) { /* valid resolved */ leaf->value.instance = ret; leaf->value_type = LY_TYPE_INST; if (json_val) { lydict_remove(leaf->schema->module->ctx, leaf->value_str); leaf->value_str = json_val; json_val = NULL; } } else { /* valid unresolved */ if (json_val) { /* put the JSON val back */ leaf->value.string = json_val; json_val = NULL; } else { leaf->value.instance = NULL; } leaf->value_type = LY_TYPE_INST; leaf->value_flags |= LY_VALUE_UNRES; } } success = 1; } break; default: if (lyp_parse_value(t, &leaf->value_str, NULL, leaf, NULL, NULL, store, 0, 0)) { success = 1; } break; } if (success) { break; } /* erase possible present and invalid value data */ if (store) { lyd_free_value(leaf->value, leaf->value_type, leaf->value_flags, t, leaf->value_str, NULL, NULL, NULL); memset(&leaf->value, 0, sizeof leaf->value); } } /* turn logging back on */ ly_ilo_restore(NULL, prev_ilo, NULL, 0); if (json_val) { if (!success) { /* put the value back for now */ assert(leaf->value_type == LY_TYPE_UNION); leaf->value.string = json_val; } else { /* value was ultimately useless, but we could not have known */ lydict_remove(leaf->schema->module->ctx, json_val); } } if (success) { if (resolved_type) { *resolved_type = t; } } else if (!ignore_fail || !type->info.uni.has_ptr_type) { /* not found and it is required */ LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, leaf, leaf->value_str ? leaf->value_str : "", leaf->schema->name); return EXIT_FAILURE; } return EXIT_SUCCESS; } /** * @brief Resolve a single unres data item. Logs directly. * * @param[in] node Data node to resolve. * @param[in] type Type of the unresolved item. * @param[in] ignore_fail 0 - no, 1 - yes, 2 - yes, but only for external dependencies. * * @return EXIT_SUCCESS on success, EXIT_FAILURE on forward reference, -1 on error. */ int resolve_unres_data_item(struct lyd_node *node, enum UNRES_ITEM type, int ignore_fail, struct lys_when **failed_when) { int rc, req_inst, ext_dep; struct lyd_node_leaf_list *leaf; struct lyd_node *ret; struct lys_node_leaf *sleaf; leaf = (struct lyd_node_leaf_list *)node; sleaf = (struct lys_node_leaf *)leaf->schema; switch (type) { case UNRES_LEAFREF: assert(sleaf->type.base == LY_TYPE_LEAFREF); assert(leaf->validity & LYD_VAL_LEAFREF); if ((ignore_fail == 1) || ((leaf->schema->flags & LYS_LEAFREF_DEP) && (ignore_fail == 2))) { req_inst = -1; } else { req_inst = sleaf->type.info.lref.req; } rc = resolve_leafref(leaf, sleaf->type.info.lref.path, req_inst, &ret); if (!rc) { if (ret && !(leaf->schema->flags & LYS_LEAFREF_DEP)) { /* valid resolved */ if (leaf->value_type == LY_TYPE_BITS) { free(leaf->value.bit); } leaf->value.leafref = ret; leaf->value_type = LY_TYPE_LEAFREF; leaf->value_flags &= ~LY_VALUE_UNRES; } else { /* valid unresolved */ if (!(leaf->value_flags & LY_VALUE_UNRES)) { if (!lyp_parse_value(&sleaf->type, &leaf->value_str, NULL, leaf, NULL, NULL, 1, 0, 0)) { return -1; } } } leaf->validity &= ~LYD_VAL_LEAFREF; } else { return rc; } break; case UNRES_INSTID: assert(sleaf->type.base == LY_TYPE_INST); ext_dep = check_instid_ext_dep(leaf->schema, leaf->value_str); if (ext_dep == -1) { return -1; } if ((ignore_fail == 1) || (ext_dep && (ignore_fail == 2))) { req_inst = -1; } else { req_inst = sleaf->type.info.inst.req; } rc = resolve_instid(node, leaf->value_str, req_inst, &ret); if (!rc) { if (ret && !ext_dep) { /* valid resolved */ leaf->value.instance = ret; leaf->value_type = LY_TYPE_INST; leaf->value_flags &= ~LY_VALUE_UNRES; } else { /* valid unresolved */ leaf->value.instance = NULL; leaf->value_type = LY_TYPE_INST; leaf->value_flags |= LY_VALUE_UNRES; } } else { return rc; } break; case UNRES_UNION: assert(sleaf->type.base == LY_TYPE_UNION); return resolve_union(leaf, &sleaf->type, 1, ignore_fail, NULL); case UNRES_WHEN: if ((rc = resolve_when(node, ignore_fail, failed_when))) { return rc; } break; case UNRES_MUST: if ((rc = resolve_must(node, 0, ignore_fail))) { return rc; } break; case UNRES_MUST_INOUT: if ((rc = resolve_must(node, 1, ignore_fail))) { return rc; } break; case UNRES_UNIQ_LEAVES: if (lyv_data_unique(node)) { return -1; } break; default: LOGINT(NULL); return -1; } return EXIT_SUCCESS; } /** * @brief add data unres item * * @param[in] unres Unres data structure to use. * @param[in] node Data node to use. * * @return 0 on success, -1 on error. */ int unres_data_add(struct unres_data *unres, struct lyd_node *node, enum UNRES_ITEM type) { assert(unres && node); assert((type == UNRES_LEAFREF) || (type == UNRES_INSTID) || (type == UNRES_WHEN) || (type == UNRES_MUST) || (type == UNRES_MUST_INOUT) || (type == UNRES_UNION) || (type == UNRES_UNIQ_LEAVES)); unres->count++; unres->node = ly_realloc(unres->node, unres->count * sizeof *unres->node); LY_CHECK_ERR_RETURN(!unres->node, LOGMEM(NULL), -1); unres->node[unres->count - 1] = node; unres->type = ly_realloc(unres->type, unres->count * sizeof *unres->type); LY_CHECK_ERR_RETURN(!unres->type, LOGMEM(NULL), -1); unres->type[unres->count - 1] = type; return 0; } static void resolve_unres_data_autodel_diff(struct unres_data *unres, uint32_t unres_i) { struct lyd_node *next, *child, *parent; uint32_t i; for (i = 0; i < unres->diff_idx; ++i) { if (unres->diff->type[i] == LYD_DIFF_DELETED) { /* only leaf(-list) default could be removed and there is nothing to be checked in that case */ continue; } if (unres->diff->second[i] == unres->node[unres_i]) { /* 1) default value was supposed to be created, but is disabled by when * -> remove it from diff altogether */ unres_data_diff_rem(unres, i); /* if diff type is CREATED, the value was just a pointer, it can be freed normally (unlike in 4) */ return; } else { parent = unres->diff->second[i]->parent; while (parent && (parent != unres->node[unres_i])) { parent = parent->parent; } if (parent) { /* 2) default value was supposed to be created but is disabled by when in some parent * -> remove this default subtree and add the rest into diff as deleted instead in 4) */ unres_data_diff_rem(unres, i); break; } LY_TREE_DFS_BEGIN(unres->diff->second[i]->parent, next, child) { if (child == unres->node[unres_i]) { /* 3) some default child of a default value was supposed to be created but has false when * -> the subtree will be freed later and automatically disconnected from the diff parent node */ return; } LY_TREE_DFS_END(unres->diff->second[i]->parent, next, child); } } } /* 4) it does not overlap with created default values in any way * -> just add it into diff as deleted */ unres_data_diff_new(unres, unres->node[unres_i], unres->node[unres_i]->parent, 0); lyd_unlink(unres->node[unres_i]); /* should not be freed anymore */ unres->node[unres_i] = NULL; } /** * @brief Resolve every unres data item in the structure. Logs directly. * * If options include #LYD_OPT_TRUSTED, the data are considered trusted (must conditions are not expected, * unresolved leafrefs/instids are accepted, when conditions are normally resolved because at least some implicit * non-presence containers may need to be deleted). * * If options includes #LYD_OPT_WHENAUTODEL, the non-default nodes with false when conditions are auto-deleted. * * @param[in] ctx Context used. * @param[in] unres Unres data structure to use. * @param[in,out] root Root node of the data tree, can be changed due to autodeletion. * @param[in] options Data options as described above. * * @return EXIT_SUCCESS on success, -1 on error. */ int resolve_unres_data(struct ly_ctx *ctx, struct unres_data *unres, struct lyd_node **root, int options) { uint32_t i, j, first, resolved, del_items, stmt_count; uint8_t prev_when_status; int rc, progress, ignore_fail; enum int_log_opts prev_ilo; struct ly_err_item *prev_eitem; LY_ERR prev_ly_errno = ly_errno; struct lyd_node *parent; struct lys_when *when; assert(root); assert(unres); if (!unres->count) { return EXIT_SUCCESS; } if (options & (LYD_OPT_NOTIF_FILTER | LYD_OPT_GET | LYD_OPT_GETCONFIG | LYD_OPT_EDIT)) { ignore_fail = 1; } else if (options & LYD_OPT_NOEXTDEPS) { ignore_fail = 2; } else { ignore_fail = 0; } LOGVRB("Resolving unresolved data nodes and their constraints..."); if (!ignore_fail) { /* remember logging state only if errors are generated and valid */ ly_ilo_change(ctx, ILO_STORE, &prev_ilo, &prev_eitem); } /* * when-stmt first */ first = 1; stmt_count = 0; resolved = 0; del_items = 0; do { if (!ignore_fail) { ly_err_free_next(ctx, prev_eitem); } progress = 0; for (i = 0; i < unres->count; i++) { if (unres->type[i] != UNRES_WHEN) { continue; } if (first) { /* count when-stmt nodes in unres list */ stmt_count++; } /* resolve when condition only when all parent when conditions are already resolved */ for (parent = unres->node[i]->parent; parent && LYD_WHEN_DONE(parent->when_status); parent = parent->parent) { if (!parent->parent && (parent->when_status & LYD_WHEN_FALSE)) { /* the parent node was already unlinked, do not resolve this node, * it will be removed anyway, so just mark it as resolved */ unres->node[i]->when_status |= LYD_WHEN_FALSE; unres->type[i] = UNRES_RESOLVED; resolved++; break; } } if (parent) { continue; } prev_when_status = unres->node[i]->when_status; rc = resolve_unres_data_item(unres->node[i], unres->type[i], ignore_fail, &when); if (!rc) { /* finish with error/delete the node only if when was changed from true to false, an external * dependency was not required, or it was not provided (the flag would not be passed down otherwise, * checked in upper functions) */ if ((unres->node[i]->when_status & LYD_WHEN_FALSE) && (!(when->flags & (LYS_XPCONF_DEP | LYS_XPSTATE_DEP)) || !(options & LYD_OPT_NOEXTDEPS))) { if ((!(prev_when_status & LYD_WHEN_TRUE) || !(options & LYD_OPT_WHENAUTODEL)) && !unres->node[i]->dflt) { /* false when condition */ goto error; } /* follows else */ /* auto-delete */ LOGVRB("Auto-deleting node \"%s\" due to when condition (%s)", ly_errpath(ctx), when->cond); /* only unlink now, the subtree can contain another nodes stored in the unres list */ /* if it has parent non-presence containers that would be empty, we should actually * remove the container */ for (parent = unres->node[i]; parent->parent && parent->parent->schema->nodetype == LYS_CONTAINER; parent = parent->parent) { if (((struct lys_node_container *)parent->parent->schema)->presence) { /* presence container */ break; } if (parent->next || parent->prev != parent) { /* non empty (the child we are in and we are going to remove is not the only child) */ break; } } unres->node[i] = parent; if (*root && *root == unres->node[i]) { *root = (*root)->next; } lyd_unlink(unres->node[i]); unres->type[i] = UNRES_DELETE; del_items++; /* update the rest of unres items */ for (j = 0; j < unres->count; j++) { if (unres->type[j] == UNRES_RESOLVED || unres->type[j] == UNRES_DELETE) { continue; } /* test if the node is in subtree to be deleted */ for (parent = unres->node[j]; parent; parent = parent->parent) { if (parent == unres->node[i]) { /* yes, it is */ unres->type[j] = UNRES_RESOLVED; resolved++; break; } } } } else { unres->type[i] = UNRES_RESOLVED; } if (!ignore_fail) { ly_err_free_next(ctx, prev_eitem); } resolved++; progress = 1; } else if (rc == -1) { goto error; } /* else forward reference */ } first = 0; } while (progress && resolved < stmt_count); /* do we have some unresolved when-stmt? */ if (stmt_count > resolved) { goto error; } for (i = 0; del_items && i < unres->count; i++) { /* we had some when-stmt resulted to false, so now we have to sanitize the unres list */ if (unres->type[i] != UNRES_DELETE) { continue; } if (!unres->node[i]) { unres->type[i] = UNRES_RESOLVED; del_items--; continue; } if (unres->store_diff) { resolve_unres_data_autodel_diff(unres, i); } /* really remove the complete subtree */ lyd_free(unres->node[i]); unres->type[i] = UNRES_RESOLVED; del_items--; } /* * now leafrefs */ if (options & LYD_OPT_TRUSTED) { /* we want to attempt to resolve leafrefs */ assert(!ignore_fail); ignore_fail = 1; ly_ilo_restore(ctx, prev_ilo, prev_eitem, 0); ly_errno = prev_ly_errno; } first = 1; stmt_count = 0; resolved = 0; do { progress = 0; for (i = 0; i < unres->count; i++) { if (unres->type[i] != UNRES_LEAFREF) { continue; } if (first) { /* count leafref nodes in unres list */ stmt_count++; } rc = resolve_unres_data_item(unres->node[i], unres->type[i], ignore_fail, NULL); if (!rc) { unres->type[i] = UNRES_RESOLVED; if (!ignore_fail) { ly_err_free_next(ctx, prev_eitem); } resolved++; progress = 1; } else if (rc == -1) { goto error; } /* else forward reference */ } first = 0; } while (progress && resolved < stmt_count); /* do we have some unresolved leafrefs? */ if (stmt_count > resolved) { goto error; } if (!ignore_fail) { /* log normally now, throw away irrelevant errors */ ly_ilo_restore(ctx, prev_ilo, prev_eitem, 0); ly_errno = prev_ly_errno; } /* * rest */ for (i = 0; i < unres->count; ++i) { if (unres->type[i] == UNRES_RESOLVED) { continue; } assert(!(options & LYD_OPT_TRUSTED) || ((unres->type[i] != UNRES_MUST) && (unres->type[i] != UNRES_MUST_INOUT))); rc = resolve_unres_data_item(unres->node[i], unres->type[i], ignore_fail, NULL); if (rc) { /* since when was already resolved, a forward reference is an error */ return -1; } unres->type[i] = UNRES_RESOLVED; } LOGVRB("All data nodes and constraints resolved."); unres->count = 0; return EXIT_SUCCESS; error: if (!ignore_fail) { /* print all the new errors */ ly_ilo_restore(ctx, prev_ilo, prev_eitem, 1); /* do not restore ly_errno, it was udpated properly */ } return -1; }
./CrossVul/dataset_final_sorted/CWE-119/c/good_1358_0
crossvul-cpp_data_bad_5590_0
/* * An implementation of key value pair (KVP) functionality for Linux. * * * Copyright (C) 2010, Novell, Inc. * Author : K. Y. Srinivasan <ksrinivasan@novell.com> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, GOOD TITLE or * NON INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/net.h> #include <linux/nls.h> #include <linux/connector.h> #include <linux/workqueue.h> #include <linux/hyperv.h> #include "hv_kvp.h" /* * Global state maintained for transaction that is being processed. * Note that only one transaction can be active at any point in time. * * This state is set when we receive a request from the host; we * cleanup this state when the transaction is completed - when we respond * to the host with the key value. */ static struct { bool active; /* transaction status - active or not */ int recv_len; /* number of bytes received. */ int index; /* current index */ struct vmbus_channel *recv_channel; /* chn we got the request */ u64 recv_req_id; /* request ID. */ } kvp_transaction; static void kvp_send_key(struct work_struct *dummy); #define TIMEOUT_FIRED 1 static void kvp_respond_to_host(char *key, char *value, int error); static void kvp_work_func(struct work_struct *dummy); static void kvp_register(void); static DECLARE_DELAYED_WORK(kvp_work, kvp_work_func); static DECLARE_WORK(kvp_sendkey_work, kvp_send_key); static struct cb_id kvp_id = { CN_KVP_IDX, CN_KVP_VAL }; static const char kvp_name[] = "kvp_kernel_module"; static u8 *recv_buffer; /* * Register the kernel component with the user-level daemon. * As part of this registration, pass the LIC version number. */ static void kvp_register(void) { struct cn_msg *msg; msg = kzalloc(sizeof(*msg) + strlen(HV_DRV_VERSION) + 1 , GFP_ATOMIC); if (msg) { msg->id.idx = CN_KVP_IDX; msg->id.val = CN_KVP_VAL; msg->seq = KVP_REGISTER; strcpy(msg->data, HV_DRV_VERSION); msg->len = strlen(HV_DRV_VERSION) + 1; cn_netlink_send(msg, 0, GFP_ATOMIC); kfree(msg); } } static void kvp_work_func(struct work_struct *dummy) { /* * If the timer fires, the user-mode component has not responded; * process the pending transaction. */ kvp_respond_to_host("Unknown key", "Guest timed out", TIMEOUT_FIRED); } /* * Callback when data is received from user mode. */ static void kvp_cn_callback(struct cn_msg *msg, struct netlink_skb_parms *nsp) { struct hv_ku_msg *message; message = (struct hv_ku_msg *)msg->data; if (msg->seq == KVP_REGISTER) { pr_info("KVP: user-mode registering done.\n"); kvp_register(); } if (msg->seq == KVP_USER_SET) { /* * Complete the transaction by forwarding the key value * to the host. But first, cancel the timeout. */ if (cancel_delayed_work_sync(&kvp_work)) kvp_respond_to_host(message->kvp_key, message->kvp_value, !strlen(message->kvp_key)); } } static void kvp_send_key(struct work_struct *dummy) { struct cn_msg *msg; int index = kvp_transaction.index; msg = kzalloc(sizeof(*msg) + sizeof(struct hv_kvp_msg) , GFP_ATOMIC); if (msg) { msg->id.idx = CN_KVP_IDX; msg->id.val = CN_KVP_VAL; msg->seq = KVP_KERNEL_GET; ((struct hv_ku_msg *)msg->data)->kvp_index = index; msg->len = sizeof(struct hv_ku_msg); cn_netlink_send(msg, 0, GFP_ATOMIC); kfree(msg); } return; } /* * Send a response back to the host. */ static void kvp_respond_to_host(char *key, char *value, int error) { struct hv_kvp_msg *kvp_msg; struct hv_kvp_msg_enumerate *kvp_data; char *key_name; struct icmsg_hdr *icmsghdrp; int keylen, valuelen; u32 buf_len; struct vmbus_channel *channel; u64 req_id; /* * If a transaction is not active; log and return. */ if (!kvp_transaction.active) { /* * This is a spurious call! */ pr_warn("KVP: Transaction not active\n"); return; } /* * Copy the global state for completing the transaction. Note that * only one transaction can be active at a time. */ buf_len = kvp_transaction.recv_len; channel = kvp_transaction.recv_channel; req_id = kvp_transaction.recv_req_id; kvp_transaction.active = false; if (channel->onchannel_callback == NULL) /* * We have raced with util driver being unloaded; * silently return. */ return; icmsghdrp = (struct icmsg_hdr *) &recv_buffer[sizeof(struct vmbuspipe_hdr)]; kvp_msg = (struct hv_kvp_msg *) &recv_buffer[sizeof(struct vmbuspipe_hdr) + sizeof(struct icmsg_hdr)]; kvp_data = &kvp_msg->kvp_data; key_name = key; /* * If the error parameter is set, terminate the host's enumeration. */ if (error) { /* * We don't support this index or the we have timedout; * terminate the host-side iteration by returning an error. */ icmsghdrp->status = HV_E_FAIL; goto response_done; } /* * The windows host expects the key/value pair to be encoded * in utf16. */ keylen = utf8s_to_utf16s(key_name, strlen(key_name), (wchar_t *)kvp_data->data.key); kvp_data->data.key_size = 2*(keylen + 1); /* utf16 encoding */ valuelen = utf8s_to_utf16s(value, strlen(value), (wchar_t *)kvp_data->data.value); kvp_data->data.value_size = 2*(valuelen + 1); /* utf16 encoding */ kvp_data->data.value_type = REG_SZ; /* all our values are strings */ icmsghdrp->status = HV_S_OK; response_done: icmsghdrp->icflags = ICMSGHDRFLAG_TRANSACTION | ICMSGHDRFLAG_RESPONSE; vmbus_sendpacket(channel, recv_buffer, buf_len, req_id, VM_PKT_DATA_INBAND, 0); } /* * This callback is invoked when we get a KVP message from the host. * The host ensures that only one KVP transaction can be active at a time. * KVP implementation in Linux needs to forward the key to a user-mde * component to retrive the corresponding value. Consequently, we cannot * respond to the host in the conext of this callback. Since the host * guarantees that at most only one transaction can be active at a time, * we stash away the transaction state in a set of global variables. */ void hv_kvp_onchannelcallback(void *context) { struct vmbus_channel *channel = context; u32 recvlen; u64 requestid; struct hv_kvp_msg *kvp_msg; struct hv_kvp_msg_enumerate *kvp_data; struct icmsg_hdr *icmsghdrp; struct icmsg_negotiate *negop = NULL; vmbus_recvpacket(channel, recv_buffer, PAGE_SIZE, &recvlen, &requestid); if (recvlen > 0) { icmsghdrp = (struct icmsg_hdr *)&recv_buffer[ sizeof(struct vmbuspipe_hdr)]; if (icmsghdrp->icmsgtype == ICMSGTYPE_NEGOTIATE) { vmbus_prep_negotiate_resp(icmsghdrp, negop, recv_buffer); } else { kvp_msg = (struct hv_kvp_msg *)&recv_buffer[ sizeof(struct vmbuspipe_hdr) + sizeof(struct icmsg_hdr)]; kvp_data = &kvp_msg->kvp_data; /* * We only support the "get" operation on * "KVP_POOL_AUTO" pool. */ if ((kvp_msg->kvp_hdr.pool != KVP_POOL_AUTO) || (kvp_msg->kvp_hdr.operation != KVP_OP_ENUMERATE)) { icmsghdrp->status = HV_E_FAIL; goto callback_done; } /* * Stash away this global state for completing the * transaction; note transactions are serialized. */ kvp_transaction.recv_len = recvlen; kvp_transaction.recv_channel = channel; kvp_transaction.recv_req_id = requestid; kvp_transaction.active = true; kvp_transaction.index = kvp_data->index; /* * Get the information from the * user-mode component. * component. This transaction will be * completed when we get the value from * the user-mode component. * Set a timeout to deal with * user-mode not responding. */ schedule_work(&kvp_sendkey_work); schedule_delayed_work(&kvp_work, 5*HZ); return; } callback_done: icmsghdrp->icflags = ICMSGHDRFLAG_TRANSACTION | ICMSGHDRFLAG_RESPONSE; vmbus_sendpacket(channel, recv_buffer, recvlen, requestid, VM_PKT_DATA_INBAND, 0); } } int hv_kvp_init(struct hv_util_service *srv) { int err; err = cn_add_callback(&kvp_id, kvp_name, kvp_cn_callback); if (err) return err; recv_buffer = srv->recv_buffer; return 0; } void hv_kvp_deinit(void) { cn_del_callback(&kvp_id); cancel_delayed_work_sync(&kvp_work); cancel_work_sync(&kvp_sendkey_work); }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_5590_0
crossvul-cpp_data_bad_2068_0
/* IRC extension for TCP NAT alteration. * * (C) 2000-2001 by Harald Welte <laforge@gnumonks.org> * (C) 2004 Rusty Russell <rusty@rustcorp.com.au> IBM Corporation * based on a copy of RR's ip_nat_ftp.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. */ #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/tcp.h> #include <linux/kernel.h> #include <net/netfilter/nf_nat.h> #include <net/netfilter/nf_nat_helper.h> #include <net/netfilter/nf_conntrack_helper.h> #include <net/netfilter/nf_conntrack_expect.h> #include <linux/netfilter/nf_conntrack_irc.h> MODULE_AUTHOR("Harald Welte <laforge@gnumonks.org>"); MODULE_DESCRIPTION("IRC (DCC) NAT helper"); MODULE_LICENSE("GPL"); MODULE_ALIAS("ip_nat_irc"); static unsigned int help(struct sk_buff *skb, enum ip_conntrack_info ctinfo, unsigned int protoff, unsigned int matchoff, unsigned int matchlen, struct nf_conntrack_expect *exp) { char buffer[sizeof("4294967296 65635")]; u_int16_t port; unsigned int ret; /* Reply comes from server. */ exp->saved_proto.tcp.port = exp->tuple.dst.u.tcp.port; exp->dir = IP_CT_DIR_REPLY; exp->expectfn = nf_nat_follow_master; /* Try to get same port: if not, try to change it. */ for (port = ntohs(exp->saved_proto.tcp.port); port != 0; port++) { int ret; exp->tuple.dst.u.tcp.port = htons(port); ret = nf_ct_expect_related(exp); if (ret == 0) break; else if (ret != -EBUSY) { port = 0; break; } } if (port == 0) { nf_ct_helper_log(skb, exp->master, "all ports in use"); return NF_DROP; } ret = nf_nat_mangle_tcp_packet(skb, exp->master, ctinfo, protoff, matchoff, matchlen, buffer, strlen(buffer)); if (ret != NF_ACCEPT) { nf_ct_helper_log(skb, exp->master, "cannot mangle packet"); nf_ct_unexpect_related(exp); } return ret; } static void __exit nf_nat_irc_fini(void) { RCU_INIT_POINTER(nf_nat_irc_hook, NULL); synchronize_rcu(); } static int __init nf_nat_irc_init(void) { BUG_ON(nf_nat_irc_hook != NULL); RCU_INIT_POINTER(nf_nat_irc_hook, help); return 0; } /* Prior to 2.6.11, we had a ports param. No longer, but don't break users. */ static int warn_set(const char *val, struct kernel_param *kp) { printk(KERN_INFO KBUILD_MODNAME ": kernel >= 2.6.10 only uses 'ports' for conntrack modules\n"); return 0; } module_param_call(ports, warn_set, NULL, NULL, 0); module_init(nf_nat_irc_init); module_exit(nf_nat_irc_fini);
./CrossVul/dataset_final_sorted/CWE-119/c/bad_2068_0
crossvul-cpp_data_bad_2364_0
/* hivex - Windows Registry "hive" extraction library. * Copyright (C) 2009-2011 Red Hat Inc. * Derived from code by Petter Nordahl-Hagen under a compatible license: * Copyright (c) 1997-2007 Petter Nordahl-Hagen. * Derived from code by Markus Stephany under a compatible license: * Copyright (c) 2000-2004, Markus Stephany. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * See file LICENSE for the full license. */ #include <config.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <inttypes.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> #include <errno.h> #include <assert.h> #ifdef HAVE_MMAP #include <sys/mman.h> #else /* On systems without mmap (and munmap), use a replacement function. */ #include "mmap.h" #endif #include "full-read.h" #include "full-write.h" #include "c-ctype.h" #include "hivex.h" #include "hivex-internal.h" static uint32_t header_checksum (const hive_h *h) { uint32_t *daddr = (uint32_t *) h->addr; size_t i; uint32_t sum = 0; for (i = 0; i < 0x1fc / 4; ++i) { sum ^= le32toh (*daddr); daddr++; } return sum; } #define HIVEX_OPEN_MSGLVL_MASK (HIVEX_OPEN_VERBOSE|HIVEX_OPEN_DEBUG) hive_h * hivex_open (const char *filename, int flags) { hive_h *h = NULL; assert (sizeof (struct ntreg_header) == 0x1000); assert (offsetof (struct ntreg_header, csum) == 0x1fc); h = calloc (1, sizeof *h); if (h == NULL) goto error; h->msglvl = flags & HIVEX_OPEN_MSGLVL_MASK; const char *debug = getenv ("HIVEX_DEBUG"); if (debug && STREQ (debug, "1")) h->msglvl = 2; DEBUG (2, "created handle %p", h); h->writable = !!(flags & HIVEX_OPEN_WRITE); h->filename = strdup (filename); if (h->filename == NULL) goto error; #ifdef O_CLOEXEC h->fd = open (filename, O_RDONLY | O_CLOEXEC | O_BINARY); #else h->fd = open (filename, O_RDONLY | O_BINARY); #endif if (h->fd == -1) goto error; #ifndef O_CLOEXEC fcntl (h->fd, F_SETFD, FD_CLOEXEC); #endif struct stat statbuf; if (fstat (h->fd, &statbuf) == -1) goto error; h->size = statbuf.st_size; if (!h->writable) { h->addr = mmap (NULL, h->size, PROT_READ, MAP_SHARED, h->fd, 0); if (h->addr == MAP_FAILED) goto error; DEBUG (2, "mapped file at %p", h->addr); } else { h->addr = malloc (h->size); if (h->addr == NULL) goto error; if (full_read (h->fd, h->addr, h->size) < h->size) goto error; /* We don't need the file descriptor along this path, since we * have read all the data. */ if (close (h->fd) == -1) goto error; h->fd = -1; } /* Check header. */ if (h->hdr->magic[0] != 'r' || h->hdr->magic[1] != 'e' || h->hdr->magic[2] != 'g' || h->hdr->magic[3] != 'f') { SET_ERRNO (ENOTSUP, "%s: not a Windows NT Registry hive file", filename); goto error; } /* Check major version. */ uint32_t major_ver = le32toh (h->hdr->major_ver); if (major_ver != 1) { SET_ERRNO (ENOTSUP, "%s: hive file major version %" PRIu32 " (expected 1)", filename, major_ver); goto error; } h->bitmap = calloc (1 + h->size / 32, 1); if (h->bitmap == NULL) goto error; /* Header checksum. */ uint32_t sum = header_checksum (h); if (sum != le32toh (h->hdr->csum)) { SET_ERRNO (EINVAL, "%s: bad checksum in hive header", filename); goto error; } /* Last modified time. */ h->last_modified = le64toh ((int64_t) h->hdr->last_modified); if (h->msglvl >= 2) { char *name = _hivex_windows_utf16_to_utf8 (h->hdr->name, 64); fprintf (stderr, "hivex_open: header fields:\n" " file version %" PRIu32 ".%" PRIu32 "\n" " sequence nos %" PRIu32 " %" PRIu32 "\n" " (sequences nos should match if hive was synched at shutdown)\n" " last modified %" PRIu64 "\n" " (Windows filetime, x 100 ns since 1601-01-01)\n" " original file name %s\n" " (only 32 chars are stored, name is probably truncated)\n" " root offset 0x%x + 0x1000\n" " end of last page 0x%x + 0x1000 (total file size 0x%zx)\n" " checksum 0x%x (calculated 0x%x)\n", major_ver, le32toh (h->hdr->minor_ver), le32toh (h->hdr->sequence1), le32toh (h->hdr->sequence2), h->last_modified, name ? name : "(conversion failed)", le32toh (h->hdr->offset), le32toh (h->hdr->blocks), h->size, le32toh (h->hdr->csum), sum); free (name); } h->rootoffs = le32toh (h->hdr->offset) + 0x1000; h->endpages = le32toh (h->hdr->blocks) + 0x1000; DEBUG (2, "root offset = 0x%zx", h->rootoffs); /* We'll set this flag when we see a block with the root offset (ie. * the root block). */ int seen_root_block = 0, bad_root_block = 0; /* Collect some stats. */ size_t pages = 0; /* Number of hbin pages read. */ size_t smallest_page = SIZE_MAX, largest_page = 0; size_t blocks = 0; /* Total number of blocks found. */ size_t smallest_block = SIZE_MAX, largest_block = 0, blocks_bytes = 0; size_t used_blocks = 0; /* Total number of used blocks found. */ size_t used_size = 0; /* Total size (bytes) of used blocks. */ /* Read the pages and blocks. The aim here is to be robust against * corrupt or malicious registries. So we make sure the loops * always make forward progress. We add the address of each block * we read to a hash table so pointers will only reference the start * of valid blocks. */ size_t off; struct ntreg_hbin_page *page; for (off = 0x1000; off < h->size; off += le32toh (page->page_size)) { if (off >= h->endpages) break; page = (struct ntreg_hbin_page *) ((char *) h->addr + off); if (page->magic[0] != 'h' || page->magic[1] != 'b' || page->magic[2] != 'i' || page->magic[3] != 'n') { SET_ERRNO (ENOTSUP, "%s: trailing garbage at end of file " "(at 0x%zx, after %zu pages)", filename, off, pages); goto error; } size_t page_size = le32toh (page->page_size); DEBUG (2, "page at 0x%zx, size %zu", off, page_size); pages++; if (page_size < smallest_page) smallest_page = page_size; if (page_size > largest_page) largest_page = page_size; if (page_size <= sizeof (struct ntreg_hbin_page) || (page_size & 0x0fff) != 0) { SET_ERRNO (ENOTSUP, "%s: page size %zu at 0x%zx, bad registry", filename, page_size, off); goto error; } /* Read the blocks in this page. */ size_t blkoff; struct ntreg_hbin_block *block; size_t seg_len; for (blkoff = off + 0x20; blkoff < off + page_size; blkoff += seg_len) { blocks++; int is_root = blkoff == h->rootoffs; if (is_root) seen_root_block = 1; block = (struct ntreg_hbin_block *) ((char *) h->addr + blkoff); int used; seg_len = block_len (h, blkoff, &used); if (seg_len <= 4 || (seg_len & 3) != 0) { SET_ERRNO (ENOTSUP, "%s: block size %" PRIu32 " at 0x%zx, bad registry", filename, le32toh (block->seg_len), blkoff); goto error; } if (h->msglvl >= 2) { unsigned char *id = (unsigned char *) block->id; int id0 = id[0], id1 = id[1]; fprintf (stderr, "%s: %s: " "%s block id %d,%d (%c%c) at 0x%zx size %zu%s\n", "hivex", __func__, used ? "used" : "free", id0, id1, c_isprint (id0) ? id0 : '.', c_isprint (id1) ? id1 : '.', blkoff, seg_len, is_root ? " (root)" : ""); } blocks_bytes += seg_len; if (seg_len < smallest_block) smallest_block = seg_len; if (seg_len > largest_block) largest_block = seg_len; if (is_root && !used) bad_root_block = 1; if (used) { used_blocks++; used_size += seg_len; /* Root block must be an nk-block. */ if (is_root && (block->id[0] != 'n' || block->id[1] != 'k')) bad_root_block = 1; /* Note this blkoff is a valid address. */ BITMAP_SET (h->bitmap, blkoff); } } } if (!seen_root_block) { SET_ERRNO (ENOTSUP, "%s: no root block found", filename); goto error; } if (bad_root_block) { SET_ERRNO (ENOTSUP, "%s: bad root block (free or not nk)", filename); goto error; } DEBUG (1, "successfully read Windows Registry hive file:\n" " pages: %zu [sml: %zu, lge: %zu]\n" " blocks: %zu [sml: %zu, avg: %zu, lge: %zu]\n" " blocks used: %zu\n" " bytes used: %zu", pages, smallest_page, largest_page, blocks, smallest_block, blocks_bytes / blocks, largest_block, used_blocks, used_size); return h; error:; int err = errno; if (h) { free (h->bitmap); if (h->addr && h->size && h->addr != MAP_FAILED) { if (!h->writable) munmap (h->addr, h->size); else free (h->addr); } if (h->fd >= 0) close (h->fd); free (h->filename); free (h); } errno = err; return NULL; } int hivex_close (hive_h *h) { int r; DEBUG (1, "hivex_close"); free (h->bitmap); if (!h->writable) munmap (h->addr, h->size); else free (h->addr); if (h->fd >= 0) r = close (h->fd); else r = 0; free (h->filename); free (h); return r; } int hivex_commit (hive_h *h, const char *filename, int flags) { int fd; if (flags != 0) { SET_ERRNO (EINVAL, "flags != 0"); return -1; } CHECK_WRITABLE (-1); filename = filename ? : h->filename; #ifdef O_CLOEXEC fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY|O_CLOEXEC|O_BINARY, 0666); #else fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY|O_BINARY, 0666); #endif if (fd == -1) return -1; #ifndef O_CLOEXEC fcntl (fd, F_SETFD, FD_CLOEXEC); #endif /* Update the header fields. */ uint32_t sequence = le32toh (h->hdr->sequence1); sequence++; h->hdr->sequence1 = htole32 (sequence); h->hdr->sequence2 = htole32 (sequence); /* XXX Ought to update h->hdr->last_modified. */ h->hdr->blocks = htole32 (h->endpages - 0x1000); /* Recompute header checksum. */ uint32_t sum = header_checksum (h); h->hdr->csum = htole32 (sum); DEBUG (2, "hivex_commit: new header checksum: 0x%x", sum); if (full_write (fd, h->addr, h->size) != h->size) { int err = errno; close (fd); errno = err; return -1; } if (close (fd) == -1) return -1; return 0; }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_2364_0
crossvul-cpp_data_good_1_1
/* Copyright (c) 2015, Cisco Systems All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <math.h> #include <string.h> #include <memory.h> #include <assert.h> #include "global.h" #include "getvlc.h" #include "common_block.h" #include "inter_prediction.h" extern int zigzag16[16]; extern int zigzag64[64]; extern int zigzag256[256]; int YPOS, XPOS; #undef TEMPLATE #define TEMPLATE(func) (decoder_info->bitdepth == 8 ? func ## _lbd : func ## _hbd) void read_sequence_header(decoder_info_t *decoder_info, stream_t *stream) { decoder_info->width = get_flc(16, stream); decoder_info->height = get_flc(16, stream); decoder_info->log2_sb_size = get_flc(3, stream); decoder_info->log2_sb_size = clip(decoder_info->log2_sb_size, log2i(MIN_BLOCK_SIZE), log2i(MAX_SB_SIZE)); decoder_info->pb_split = get_flc(1, stream); decoder_info->tb_split_enable = get_flc(1, stream); decoder_info->max_num_ref = get_flc(2, stream) + 1; decoder_info->interp_ref = get_flc(2, stream); decoder_info->max_delta_qp = get_flc(1, stream); decoder_info->deblocking = get_flc(1, stream); decoder_info->clpf = get_flc(1, stream); decoder_info->use_block_contexts = get_flc(1, stream); decoder_info->bipred = get_flc(2, stream); decoder_info->qmtx = get_flc(1, stream); if (decoder_info->qmtx) { decoder_info->qmtx_offset = get_flc(6, stream) - 32; } decoder_info->subsample = get_flc(2, stream); decoder_info->subsample = // 0: 400 1: 420 2: 422 3: 444 (decoder_info->subsample & 1) * 20 + (decoder_info->subsample & 2) * 22 + ((decoder_info->subsample & 3) == 3) * 2 + 400; decoder_info->num_reorder_pics = get_flc(4, stream); if (decoder_info->subsample != 400) { decoder_info->cfl_intra = get_flc(1, stream); decoder_info->cfl_inter = get_flc(1, stream); } decoder_info->bitdepth = get_flc(1, stream) ? 10 : 8; if (decoder_info->bitdepth == 10) decoder_info->bitdepth += 2 * get_flc(1, stream); decoder_info->input_bitdepth = get_flc(1, stream) ? 10 : 8; if (decoder_info->input_bitdepth == 10) decoder_info->input_bitdepth += 2 * get_flc(1, stream); } void read_frame_header(decoder_info_t *dec_info, stream_t *stream) { frame_info_t *frame_info = &dec_info->frame_info; frame_info->frame_type = get_flc(1, stream); frame_info->qp = get_flc(8, stream); frame_info->num_intra_modes = get_flc(4, stream); if (frame_info->frame_type != I_FRAME) { frame_info->num_ref = get_flc(2, stream) + 1; int r; for (r = 0; r < frame_info->num_ref; r++) { frame_info->ref_array[r] = get_flc(6, stream) - 1; } if (frame_info->num_ref == 2 && frame_info->ref_array[0] == -1) { frame_info->ref_array[frame_info->num_ref++] = get_flc(5, stream) - 1; } } else { frame_info->num_ref = 0; } frame_info->display_frame_num = get_flc(16, stream); #if CDEF dec_info->cdef_damping[1] = dec_info->cdef_damping[0] = get_flc(2, stream) + 3; dec_info->cdef_bits = get_flc(2, stream); for (int i = 0; i < (1 << dec_info->cdef_bits); i++) { dec_info->cdef_presets[i].pri_strength[0] = get_flc(4, stream); dec_info->cdef_presets[i].skip_condition[0] = get_flc(1, stream); dec_info->cdef_presets[i].sec_strength[0] = get_flc(2, stream); if (dec_info->subsample != 400) { dec_info->cdef_presets[i].pri_strength[1] = get_flc(4, stream); dec_info->cdef_presets[i].skip_condition[1] = get_flc(1, stream); dec_info->cdef_presets[i].sec_strength[1] = get_flc(2, stream); } } #endif } void read_mv(stream_t *stream,mv_t *mv,mv_t *mvp) { mv_t mvd; int mvabs, mvsign = 0; /* MVX */ if ((mvabs = get_vlc(7, stream))) mvsign = get_flc(1, stream); mvd.x = mvabs * (mvsign ? -1 : 1); mv->x = mvp->x + mvd.x; /* MVY */ if ((mvabs = get_vlc(7, stream))) mvsign = get_flc(1, stream); mvd.y = mvabs * (mvsign ? -1 : 1); mv->y = mvp->y + mvd.y; } void read_coeff(stream_t *stream,int16_t *coeff,int size,int type){ int16_t scoeff[MAX_QUANT_SIZE*MAX_QUANT_SIZE]; int i,j,levelFlag,sign,level,pos,run,tmp,code; int qsize = min(size,MAX_QUANT_SIZE); int N = qsize*qsize; int level_mode; int chroma_flag = type&1; int intra_flag = (type>>1)&1; int vlc_adaptive = intra_flag && !chroma_flag; /* Initialize arrays */ memset(scoeff,0,N*sizeof(int16_t)); memset(coeff,0,size*size*sizeof(int16_t)); pos = 0; /* Use one bit to signal chroma/last_pos=1/level=1 */ if (chroma_flag==1){ int tmp = get_flc(1, stream); if (tmp){ sign = get_flc(1, stream); scoeff[pos] = sign ? -1 : 1; pos = N; } } /* Initiate forward scan */ level_mode = 1; level = 1; while (pos < N){ if (level_mode){ /* Level-mode */ while (pos < N && level > 0){ level = get_vlc(vlc_adaptive,stream); if (level){ sign = get_flc(1, stream); } else{ sign = 1; } scoeff[pos] = sign ? -level : level; if (chroma_flag==0) vlc_adaptive = level > 3; pos++; } } if (pos >= N){ break; } /* Run-mode */ int eob; int eob_pos = chroma_flag ? 0 : 2; if (chroma_flag && size <= 8) code = get_vlc(10, stream); else code = get_vlc(6, stream); eob = code == eob_pos; if (eob) { break; } if (code > eob_pos) code -= 1; levelFlag = (code % 5) == 4; if (levelFlag) run = code / 5; else run = 4*(code/5) + code % 5; pos += run; /* Decode level and sign */ if (levelFlag){ tmp = get_vlc(0,stream); sign = tmp&1; level = (tmp>>1)+2; } else{ level = 1; sign = get_flc(1, stream); } scoeff[pos] = sign ? -level : level; level_mode = level > 1; //Set level_mode pos++; } //while pos < N /* Perform inverse zigzag scan */ int *zigzagptr = zigzag64; if (qsize==4) zigzagptr = zigzag16; else if (qsize==8) zigzagptr = zigzag64; else if (qsize==16) zigzagptr = zigzag256; for (i=0;i<qsize;i++){ for (j=0;j<qsize;j++){ coeff[i*qsize + j] = scoeff[zigzagptr[i*qsize + j]]; } } } int read_delta_qp(stream_t *stream){ int abs_delta_qp,sign_delta_qp,delta_qp; sign_delta_qp = 0; abs_delta_qp = get_vlc(0,stream); if (abs_delta_qp > 0) sign_delta_qp = get_flc(1, stream); delta_qp = sign_delta_qp ? -abs_delta_qp : abs_delta_qp; return delta_qp; } int read_block(decoder_info_t *decoder_info,stream_t *stream,block_info_dec_t *block_info, frame_type_t frame_type) { int width = decoder_info->width; int height = decoder_info->height; int bit_start; int code,tb_split; int pb_part=0; cbp_t cbp; int stat_frame_type = decoder_info->bit_count.stat_frame_type; //TODO: Use only one variable for frame type int size = block_info->block_pos.size; int ypos = block_info->block_pos.ypos; int xpos = block_info->block_pos.xpos; YPOS = ypos; XPOS = xpos; int sizeY = size; int sizeC = size>>block_info->sub; mv_t mv,zerovec; mv_t mvp; mv_t mv_arr[4]; //TODO: Use mv_arr0 instead mv_t mv_arr0[4]; mv_t mv_arr1[4]; block_mode_t mode; intra_mode_t intra_mode = MODE_DC; int16_t *coeff_y = block_info->coeffq_y; int16_t *coeff_u = block_info->coeffq_u; int16_t *coeff_v = block_info->coeffq_v; zerovec.y = zerovec.x = 0; bit_start = stream->bitcnt; mode = decoder_info->mode; int coeff_block_type = (mode == MODE_INTRA)<<1; /* Initialize bit counter for statistical purposes */ bit_start = stream->bitcnt; if (mode == MODE_SKIP){ /* Derive skip vector candidates and number of skip vector candidates from neighbour blocks */ mv_t mv_skip[MAX_NUM_SKIP]; int num_skip_vec,skip_idx; inter_pred_t skip_candidates[MAX_NUM_SKIP]; num_skip_vec = TEMPLATE(get_mv_skip)(ypos, xpos, width, height, size, size, 1 << decoder_info->log2_sb_size, decoder_info->deblock_data, skip_candidates); if (decoder_info->bit_count.stat_frame_type == B_FRAME && decoder_info->interp_ref == 2) { num_skip_vec = TEMPLATE(get_mv_skip_temp)(decoder_info->width, decoder_info->frame_info.phase, decoder_info->num_reorder_pics + 1, &block_info->block_pos, decoder_info->deblock_data, skip_candidates); } for (int idx = 0; idx < num_skip_vec; idx++) { mv_skip[idx] = skip_candidates[idx].mv0; } /* Decode skip index */ if (num_skip_vec == 4) skip_idx = get_flc(2, stream); else if (num_skip_vec == 3){ skip_idx = get_vlc(12, stream); } else if (num_skip_vec == 2){ skip_idx = get_flc(1, stream); } else skip_idx = 0; decoder_info->bit_count.skip_idx[stat_frame_type] += (stream->bitcnt - bit_start); block_info->num_skip_vec = num_skip_vec; block_info->block_param.skip_idx = skip_idx; if (skip_idx == num_skip_vec) mv = mv_skip[0]; else mv = mv_skip[skip_idx]; mv_arr[0] = mv; mv_arr[1] = mv; mv_arr[2] = mv; mv_arr[3] = mv; block_info->block_param.ref_idx0 = skip_candidates[skip_idx].ref_idx0; block_info->block_param.ref_idx1 = skip_candidates[skip_idx].ref_idx1; for (int i = 0; i < 4; i++) { mv_arr0[i] = skip_candidates[skip_idx].mv0; mv_arr1[i] = skip_candidates[skip_idx].mv1; } block_info->block_param.dir = skip_candidates[skip_idx].bipred_flag; } else if (mode == MODE_MERGE){ /* Derive skip vector candidates and number of skip vector candidates from neighbour blocks */ mv_t mv_skip[MAX_NUM_SKIP]; int num_skip_vec,skip_idx; inter_pred_t merge_candidates[MAX_NUM_SKIP]; num_skip_vec = TEMPLATE(get_mv_merge)(ypos, xpos, width, height, size, size, 1 << decoder_info->log2_sb_size, decoder_info->deblock_data, merge_candidates); for (int idx = 0; idx < num_skip_vec; idx++) { mv_skip[idx] = merge_candidates[idx].mv0; } /* Decode skip index */ if (num_skip_vec == 4) skip_idx = get_flc(2, stream); else if (num_skip_vec == 3){ skip_idx = get_vlc(12, stream); } else if (num_skip_vec == 2){ skip_idx = get_flc(1, stream); } else skip_idx = 0; decoder_info->bit_count.skip_idx[stat_frame_type] += (stream->bitcnt - bit_start); block_info->num_skip_vec = num_skip_vec; block_info->block_param.skip_idx = skip_idx; if (skip_idx == num_skip_vec) mv = mv_skip[0]; else mv = mv_skip[skip_idx]; mv_arr[0] = mv; mv_arr[1] = mv; mv_arr[2] = mv; mv_arr[3] = mv; block_info->block_param.ref_idx0 = merge_candidates[skip_idx].ref_idx0; block_info->block_param.ref_idx1 = merge_candidates[skip_idx].ref_idx1; for (int i = 0; i < 4; i++) { mv_arr0[i] = merge_candidates[skip_idx].mv0; mv_arr1[i] = merge_candidates[skip_idx].mv1; } block_info->block_param.dir = merge_candidates[skip_idx].bipred_flag; } else if (mode==MODE_INTER){ int ref_idx; if (decoder_info->pb_split){ /* Decode PU partition */ pb_part = get_vlc(13, stream); } else{ pb_part = 0; } block_info->block_param.pb_part = pb_part; if (decoder_info->frame_info.num_ref > 1){ ref_idx = decoder_info->ref_idx; } else{ ref_idx = 0; } //if (mode==MODE_INTER) decoder_info->bit_count.size_and_ref_idx[stat_frame_type][log2i(size)-3][ref_idx] += 1; mvp = TEMPLATE(get_mv_pred)(ypos,xpos,width,height,size,size,1<<decoder_info->log2_sb_size,ref_idx,decoder_info->deblock_data); /* Deode motion vectors for each prediction block */ mv_t mvp2 = mvp; if (pb_part==0){ read_mv(stream,&mv_arr[0],&mvp2); mv_arr[1] = mv_arr[0]; mv_arr[2] = mv_arr[0]; mv_arr[3] = mv_arr[0]; } else if(pb_part==1){ //HOR read_mv(stream,&mv_arr[0],&mvp2); mvp2 = mv_arr[0]; read_mv(stream,&mv_arr[2],&mvp2); mv_arr[1] = mv_arr[0]; mv_arr[3] = mv_arr[2]; } else if(pb_part==2){ //VER read_mv(stream,&mv_arr[0],&mvp2); mvp2 = mv_arr[0]; read_mv(stream,&mv_arr[1],&mvp2); mv_arr[2] = mv_arr[0]; mv_arr[3] = mv_arr[1]; } else{ read_mv(stream,&mv_arr[0],&mvp2); mvp2 = mv_arr[0]; read_mv(stream,&mv_arr[1],&mvp2); read_mv(stream,&mv_arr[2],&mvp2); read_mv(stream,&mv_arr[3],&mvp2); } decoder_info->bit_count.mv[stat_frame_type] += (stream->bitcnt - bit_start); block_info->block_param.ref_idx0 = ref_idx; block_info->block_param.ref_idx1 = ref_idx; block_info->block_param.dir = 0; } else if (mode==MODE_BIPRED){ int ref_idx = 0; mvp = TEMPLATE(get_mv_pred)(ypos,xpos,width,height,size,size,1 << decoder_info->log2_sb_size, ref_idx,decoder_info->deblock_data); /* Deode motion vectors */ mv_t mvp2 = mvp; #if BIPRED_PART if (decoder_info->pb_split) { /* Decode PU partition */ pb_part = get_vlc(13, stream); } else { pb_part = 0; } #else pb_part = 0; #endif block_info->block_param.pb_part = pb_part; if (pb_part == 0) { read_mv(stream, &mv_arr0[0], &mvp2); mv_arr0[1] = mv_arr0[0]; mv_arr0[2] = mv_arr0[0]; mv_arr0[3] = mv_arr0[0]; } else { mv_arr0[0] = mvp2; mv_arr0[1] = mvp2; mv_arr0[2] = mvp2; mv_arr0[3] = mvp2; } if (decoder_info->bit_count.stat_frame_type == B_FRAME) mvp2 = mv_arr0[0]; if (pb_part == 0) { read_mv(stream, &mv_arr1[0], &mvp2); mv_arr1[1] = mv_arr1[0]; mv_arr1[2] = mv_arr1[0]; mv_arr1[3] = mv_arr1[0]; } else if (pb_part == 1) { //HOR read_mv(stream, &mv_arr1[0], &mvp2); mvp2 = mv_arr1[0]; read_mv(stream, &mv_arr1[2], &mvp2); mv_arr1[1] = mv_arr1[0]; mv_arr1[3] = mv_arr1[2]; } else if (pb_part == 2) { //VER read_mv(stream, &mv_arr1[0], &mvp2); mvp2 = mv_arr1[0]; read_mv(stream, &mv_arr1[1], &mvp2); mv_arr1[2] = mv_arr1[0]; mv_arr1[3] = mv_arr1[1]; } else { read_mv(stream, &mv_arr1[0], &mvp2); mvp2 = mv_arr1[0]; read_mv(stream, &mv_arr1[1], &mvp2); read_mv(stream, &mv_arr1[2], &mvp2); read_mv(stream, &mv_arr1[3], &mvp2); } if (decoder_info->bit_count.stat_frame_type == B_FRAME) { block_info->block_param.ref_idx0 = 0; block_info->block_param.ref_idx1 = 1; if (decoder_info->frame_info.interp_ref > 0) { block_info->block_param.ref_idx0 += 1; block_info->block_param.ref_idx1 += 1; } } else{ if (decoder_info->frame_info.num_ref == 2) { int code = get_vlc(13, stream); block_info->block_param.ref_idx0 = (code >> 1) & 1; block_info->block_param.ref_idx1 = (code >> 0) & 1; } else { int code = get_vlc(10, stream); block_info->block_param.ref_idx0 = (code >> 2) & 3; block_info->block_param.ref_idx1 = (code >> 0) & 3; } } block_info->block_param.dir = 2; int combined_ref = block_info->block_param.ref_idx0 * decoder_info->frame_info.num_ref + block_info->block_param.ref_idx1; decoder_info->bit_count.bi_ref[stat_frame_type][combined_ref] += 1; decoder_info->bit_count.mv[stat_frame_type] += (stream->bitcnt - bit_start); } else if (mode==MODE_INTRA){ /* Decode intra prediction mode */ if (decoder_info->frame_info.num_intra_modes<=4){ intra_mode = get_flc(2, stream); } else { intra_mode = get_vlc(8, stream); } decoder_info->bit_count.intra_mode[stat_frame_type] += (stream->bitcnt - bit_start); decoder_info->bit_count.size_and_intra_mode[stat_frame_type][log2i(size)-3][intra_mode] += 1; block_info->block_param.intra_mode = intra_mode; for (int i=0;i<4;i++){ mv_arr[i] = zerovec; //Note: This is necessary for derivation of mvp and mv_skip } block_info->block_param.ref_idx0 = 0; block_info->block_param.ref_idx1 = 0; block_info->block_param.dir = -1; } if (mode!=MODE_SKIP){ int tmp; int cbp_table[8] = {1,0,5,2,6,3,7,4}; code = 0; if (decoder_info->subsample == 400) { tb_split = cbp.u = cbp.v = 0; cbp.y = get_flc(1,stream); if (decoder_info->tb_split_enable && cbp.y) { // 0: cbp=split=0, 10: cbp=1,split=0, 11: split=1 tb_split = get_flc(1,stream); cbp.y &= !tb_split; } } else { bit_start = stream->bitcnt; code = get_vlc(0,stream); int off = (mode == MODE_MERGE) ? 1 : 2; if (decoder_info->tb_split_enable) { tb_split = code == off; if (code > off) code -= 1; if (tb_split) decoder_info->bit_count.cbp2_stat[0][stat_frame_type][mode-1][log2i(size)-3][8] += 1; } else{ tb_split = 0; } } block_info->block_param.tb_split = tb_split; decoder_info->bit_count.cbp[stat_frame_type] += (stream->bitcnt - bit_start); if (tb_split == 0){ if (decoder_info->subsample != 400) { tmp = 0; if (mode==MODE_MERGE){ if (code==7) code = 1; else if (code>0) code = code+1; } else { if (decoder_info->block_context->cbp == 0 && code < 2) { code = 1 - code; } } while (tmp < 8 && code != cbp_table[tmp]) tmp++; decoder_info->bit_count.cbp2_stat[max(0,decoder_info->block_context->cbp)][stat_frame_type][mode-1][log2i(size)-3][tmp] += 1; cbp.y = ((tmp>>0)&1); cbp.u = ((tmp>>1)&1); cbp.v = ((tmp>>2)&1); } block_info->cbp = cbp; if (cbp.y){ bit_start = stream->bitcnt; read_coeff(stream,coeff_y,sizeY,coeff_block_type|0); decoder_info->bit_count.coeff_y[stat_frame_type] += (stream->bitcnt - bit_start); } else memset(coeff_y,0,sizeY*sizeY*sizeof(int16_t)); if (cbp.u){ bit_start = stream->bitcnt; read_coeff(stream,coeff_u,sizeC,coeff_block_type|1); decoder_info->bit_count.coeff_u[stat_frame_type] += (stream->bitcnt - bit_start); } else memset(coeff_u,0,sizeC*sizeC*sizeof(int16_t)); if (cbp.v){ bit_start = stream->bitcnt; read_coeff(stream,coeff_v,sizeC,coeff_block_type|1); decoder_info->bit_count.coeff_v[stat_frame_type] += (stream->bitcnt - bit_start); } else memset(coeff_v,0,sizeC*sizeC*sizeof(int16_t)); } else{ if (sizeC > 4){ int index; int16_t *coeff; /* Loop over 4 TUs */ for (index=0;index<4;index++){ bit_start = stream->bitcnt; code = get_vlc(0,stream); int tmp = 0; while (code != cbp_table[tmp] && tmp < 8) tmp++; if (decoder_info->block_context->cbp==0 && tmp < 2) tmp = 1-tmp; cbp.y = ((tmp>>0)&1); cbp.u = ((tmp>>1)&1); cbp.v = ((tmp>>2)&1); /* Updating statistics for CBP */ decoder_info->bit_count.cbp[stat_frame_type] += (stream->bitcnt - bit_start); decoder_info->bit_count.cbp_stat[stat_frame_type][cbp.y + (cbp.u<<1) + (cbp.v<<2)] += 1; /* Decode coefficients for this TU */ /* Y */ coeff = coeff_y + index*sizeY/2*sizeY/2; if (cbp.y){ bit_start = stream->bitcnt; read_coeff(stream,coeff,sizeY/2,coeff_block_type|0); decoder_info->bit_count.coeff_y[stat_frame_type] += (stream->bitcnt - bit_start); } else{ memset(coeff,0,sizeY/2*sizeY/2*sizeof(int16_t)); } /* U */ coeff = coeff_u + index*sizeC/2*sizeC/2; if (cbp.u){ bit_start = stream->bitcnt; read_coeff(stream,coeff,sizeC/2,coeff_block_type|1); decoder_info->bit_count.coeff_u[stat_frame_type] += (stream->bitcnt - bit_start); } else{ memset(coeff,0,sizeC/2*sizeC/2*sizeof(int16_t)); } /* V */ coeff = coeff_v + index*sizeC/2*sizeC/2; if (cbp.v){ bit_start = stream->bitcnt; read_coeff(stream,coeff,sizeC/2,coeff_block_type|1); decoder_info->bit_count.coeff_v[stat_frame_type] += (stream->bitcnt - bit_start); } else{ memset(coeff,0,sizeC/2*sizeC/2*sizeof(int16_t)); } } block_info->cbp.y = 1; //TODO: Do properly with respect to deblocking filter block_info->cbp.u = 1; block_info->cbp.v = 1; } else{ int index; int16_t *coeff; /* Loop over 4 TUs */ for (index=0;index<4;index++){ bit_start = stream->bitcnt; cbp.y = get_flc(1, stream); decoder_info->bit_count.cbp[stat_frame_type] += (stream->bitcnt - bit_start); /* Y */ coeff = coeff_y + index*sizeY/2*sizeY/2; if (cbp.y){ bit_start = stream->bitcnt; read_coeff(stream,coeff,sizeY/2,coeff_block_type|0); decoder_info->bit_count.coeff_y[stat_frame_type] += (stream->bitcnt - bit_start); } else{ memset(coeff,0,sizeY/2*sizeY/2*sizeof(int16_t)); } } bit_start = stream->bitcnt; if (decoder_info->subsample != 400) { int tmp; tmp = get_vlc(13, stream); cbp.u = tmp & 1; cbp.v = (tmp >> 1) & 1; } else cbp.u = cbp.v = 0; decoder_info->bit_count.cbp[stat_frame_type] += (stream->bitcnt - bit_start); if (cbp.u){ bit_start = stream->bitcnt; read_coeff(stream,coeff_u,sizeC,coeff_block_type|1); decoder_info->bit_count.coeff_u[stat_frame_type] += (stream->bitcnt - bit_start); } else memset(coeff_u,0,sizeC*sizeC*sizeof(int16_t)); if (cbp.v){ bit_start = stream->bitcnt; read_coeff(stream,coeff_v,sizeC,coeff_block_type|1); decoder_info->bit_count.coeff_v[stat_frame_type] += (stream->bitcnt - bit_start); } else memset(coeff_v,0,sizeC*sizeC*sizeof(int16_t)); block_info->cbp.y = 1; //TODO: Do properly with respect to deblocking filter block_info->cbp.u = 1; block_info->cbp.v = 1; } //if (size==8) } //if (tb_split==0) } //if (mode!=MODE_SKIP) else{ tb_split = 0; block_info->cbp.y = 0; block_info->cbp.u = 0; block_info->cbp.v = 0; } /* Store block data */ if (mode==MODE_BIPRED){ memcpy(block_info->block_param.mv_arr0,mv_arr0,4*sizeof(mv_t)); //Used for mv0 coding memcpy(block_info->block_param.mv_arr1,mv_arr1,4*sizeof(mv_t)); //Used for mv1 coding } else if(mode==MODE_SKIP){ memcpy(block_info->block_param.mv_arr0,mv_arr0,4*sizeof(mv_t)); //Used for mv0 coding memcpy(block_info->block_param.mv_arr1,mv_arr1,4*sizeof(mv_t)); //Used for mv1 coding } else if(mode==MODE_MERGE){ memcpy(block_info->block_param.mv_arr0,mv_arr0,4*sizeof(mv_t)); //Used for mv0 coding memcpy(block_info->block_param.mv_arr1,mv_arr1,4*sizeof(mv_t)); //Used for mv1 coding } else{ memcpy(block_info->block_param.mv_arr0,mv_arr,4*sizeof(mv_t)); //Used for mv0 coding memcpy(block_info->block_param.mv_arr1,mv_arr,4*sizeof(mv_t)); //Used for mv1 coding } block_info->block_param.mode = mode; block_info->block_param.tb_split = tb_split; int bwidth = min(size,width - xpos); int bheight = min(size,height - ypos); /* Update mode and block size statistics */ decoder_info->bit_count.mode[stat_frame_type][mode] += (bwidth/MIN_BLOCK_SIZE * bheight/MIN_BLOCK_SIZE); decoder_info->bit_count.size[stat_frame_type][log2i(size)-3] += (bwidth/MIN_BLOCK_SIZE * bheight/MIN_BLOCK_SIZE); decoder_info->bit_count.size_and_mode[stat_frame_type][log2i(size)-3][mode] += (bwidth/MIN_BLOCK_SIZE * bheight/MIN_BLOCK_SIZE); return 0; }
./CrossVul/dataset_final_sorted/CWE-119/c/good_1_1
crossvul-cpp_data_good_3259_0
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "tool_setup.h" #define ENABLE_CURLX_PRINTF /* use our own printf() functions */ #include "curlx.h" #include "tool_cfgable.h" #include "tool_writeout.h" #include "memdebug.h" /* keep this as LAST include */ typedef enum { VAR_NONE, /* must be the first */ VAR_TOTAL_TIME, VAR_NAMELOOKUP_TIME, VAR_CONNECT_TIME, VAR_APPCONNECT_TIME, VAR_PRETRANSFER_TIME, VAR_STARTTRANSFER_TIME, VAR_SIZE_DOWNLOAD, VAR_SIZE_UPLOAD, VAR_SPEED_DOWNLOAD, VAR_SPEED_UPLOAD, VAR_HTTP_CODE, VAR_HTTP_CODE_PROXY, VAR_HEADER_SIZE, VAR_REQUEST_SIZE, VAR_EFFECTIVE_URL, VAR_CONTENT_TYPE, VAR_NUM_CONNECTS, VAR_REDIRECT_TIME, VAR_REDIRECT_COUNT, VAR_FTP_ENTRY_PATH, VAR_REDIRECT_URL, VAR_SSL_VERIFY_RESULT, VAR_PROXY_SSL_VERIFY_RESULT, VAR_EFFECTIVE_FILENAME, VAR_PRIMARY_IP, VAR_PRIMARY_PORT, VAR_LOCAL_IP, VAR_LOCAL_PORT, VAR_HTTP_VERSION, VAR_SCHEME, VAR_NUM_OF_VARS /* must be the last */ } replaceid; struct variable { const char *name; replaceid id; }; static const struct variable replacements[]={ {"url_effective", VAR_EFFECTIVE_URL}, {"http_code", VAR_HTTP_CODE}, {"response_code", VAR_HTTP_CODE}, {"http_connect", VAR_HTTP_CODE_PROXY}, {"time_total", VAR_TOTAL_TIME}, {"time_namelookup", VAR_NAMELOOKUP_TIME}, {"time_connect", VAR_CONNECT_TIME}, {"time_appconnect", VAR_APPCONNECT_TIME}, {"time_pretransfer", VAR_PRETRANSFER_TIME}, {"time_starttransfer", VAR_STARTTRANSFER_TIME}, {"size_header", VAR_HEADER_SIZE}, {"size_request", VAR_REQUEST_SIZE}, {"size_download", VAR_SIZE_DOWNLOAD}, {"size_upload", VAR_SIZE_UPLOAD}, {"speed_download", VAR_SPEED_DOWNLOAD}, {"speed_upload", VAR_SPEED_UPLOAD}, {"content_type", VAR_CONTENT_TYPE}, {"num_connects", VAR_NUM_CONNECTS}, {"time_redirect", VAR_REDIRECT_TIME}, {"num_redirects", VAR_REDIRECT_COUNT}, {"ftp_entry_path", VAR_FTP_ENTRY_PATH}, {"redirect_url", VAR_REDIRECT_URL}, {"ssl_verify_result", VAR_SSL_VERIFY_RESULT}, {"proxy_ssl_verify_result", VAR_PROXY_SSL_VERIFY_RESULT}, {"filename_effective", VAR_EFFECTIVE_FILENAME}, {"remote_ip", VAR_PRIMARY_IP}, {"remote_port", VAR_PRIMARY_PORT}, {"local_ip", VAR_LOCAL_IP}, {"local_port", VAR_LOCAL_PORT}, {"http_version", VAR_HTTP_VERSION}, {"scheme", VAR_SCHEME}, {NULL, VAR_NONE} }; void ourWriteOut(CURL *curl, struct OutStruct *outs, const char *writeinfo) { FILE *stream = stdout; const char *ptr = writeinfo; char *stringp = NULL; long longinfo; double doubleinfo; while(ptr && *ptr) { if('%' == *ptr && ptr[1]) { if('%' == ptr[1]) { /* an escaped %-letter */ fputc('%', stream); ptr += 2; } else { /* this is meant as a variable to output */ char *end; char keepit; int i; if('{' == ptr[1]) { bool match = FALSE; end = strchr(ptr, '}'); ptr += 2; /* pass the % and the { */ if(!end) { fputs("%{", stream); continue; } keepit = *end; *end = 0; /* zero terminate */ for(i = 0; replacements[i].name; i++) { if(curl_strequal(ptr, replacements[i].name)) { match = TRUE; switch(replacements[i].id) { case VAR_EFFECTIVE_URL: if((CURLE_OK == curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &stringp)) && stringp) fputs(stringp, stream); break; case VAR_HTTP_CODE: if(CURLE_OK == curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &longinfo)) fprintf(stream, "%03ld", longinfo); break; case VAR_HTTP_CODE_PROXY: if(CURLE_OK == curl_easy_getinfo(curl, CURLINFO_HTTP_CONNECTCODE, &longinfo)) fprintf(stream, "%03ld", longinfo); break; case VAR_HEADER_SIZE: if(CURLE_OK == curl_easy_getinfo(curl, CURLINFO_HEADER_SIZE, &longinfo)) fprintf(stream, "%ld", longinfo); break; case VAR_REQUEST_SIZE: if(CURLE_OK == curl_easy_getinfo(curl, CURLINFO_REQUEST_SIZE, &longinfo)) fprintf(stream, "%ld", longinfo); break; case VAR_NUM_CONNECTS: if(CURLE_OK == curl_easy_getinfo(curl, CURLINFO_NUM_CONNECTS, &longinfo)) fprintf(stream, "%ld", longinfo); break; case VAR_REDIRECT_COUNT: if(CURLE_OK == curl_easy_getinfo(curl, CURLINFO_REDIRECT_COUNT, &longinfo)) fprintf(stream, "%ld", longinfo); break; case VAR_REDIRECT_TIME: if(CURLE_OK == curl_easy_getinfo(curl, CURLINFO_REDIRECT_TIME, &doubleinfo)) fprintf(stream, "%.6f", doubleinfo); break; case VAR_TOTAL_TIME: if(CURLE_OK == curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME, &doubleinfo)) fprintf(stream, "%.6f", doubleinfo); break; case VAR_NAMELOOKUP_TIME: if(CURLE_OK == curl_easy_getinfo(curl, CURLINFO_NAMELOOKUP_TIME, &doubleinfo)) fprintf(stream, "%.6f", doubleinfo); break; case VAR_CONNECT_TIME: if(CURLE_OK == curl_easy_getinfo(curl, CURLINFO_CONNECT_TIME, &doubleinfo)) fprintf(stream, "%.6f", doubleinfo); break; case VAR_APPCONNECT_TIME: if(CURLE_OK == curl_easy_getinfo(curl, CURLINFO_APPCONNECT_TIME, &doubleinfo)) fprintf(stream, "%.6f", doubleinfo); break; case VAR_PRETRANSFER_TIME: if(CURLE_OK == curl_easy_getinfo(curl, CURLINFO_PRETRANSFER_TIME, &doubleinfo)) fprintf(stream, "%.6f", doubleinfo); break; case VAR_STARTTRANSFER_TIME: if(CURLE_OK == curl_easy_getinfo(curl, CURLINFO_STARTTRANSFER_TIME, &doubleinfo)) fprintf(stream, "%.6f", doubleinfo); break; case VAR_SIZE_UPLOAD: if(CURLE_OK == curl_easy_getinfo(curl, CURLINFO_SIZE_UPLOAD, &doubleinfo)) fprintf(stream, "%.0f", doubleinfo); break; case VAR_SIZE_DOWNLOAD: if(CURLE_OK == curl_easy_getinfo(curl, CURLINFO_SIZE_DOWNLOAD, &doubleinfo)) fprintf(stream, "%.0f", doubleinfo); break; case VAR_SPEED_DOWNLOAD: if(CURLE_OK == curl_easy_getinfo(curl, CURLINFO_SPEED_DOWNLOAD, &doubleinfo)) fprintf(stream, "%.3f", doubleinfo); break; case VAR_SPEED_UPLOAD: if(CURLE_OK == curl_easy_getinfo(curl, CURLINFO_SPEED_UPLOAD, &doubleinfo)) fprintf(stream, "%.3f", doubleinfo); break; case VAR_CONTENT_TYPE: if((CURLE_OK == curl_easy_getinfo(curl, CURLINFO_CONTENT_TYPE, &stringp)) && stringp) fputs(stringp, stream); break; case VAR_FTP_ENTRY_PATH: if((CURLE_OK == curl_easy_getinfo(curl, CURLINFO_FTP_ENTRY_PATH, &stringp)) && stringp) fputs(stringp, stream); break; case VAR_REDIRECT_URL: if((CURLE_OK == curl_easy_getinfo(curl, CURLINFO_REDIRECT_URL, &stringp)) && stringp) fputs(stringp, stream); break; case VAR_SSL_VERIFY_RESULT: if(CURLE_OK == curl_easy_getinfo(curl, CURLINFO_SSL_VERIFYRESULT, &longinfo)) fprintf(stream, "%ld", longinfo); break; case VAR_PROXY_SSL_VERIFY_RESULT: if(CURLE_OK == curl_easy_getinfo(curl, CURLINFO_PROXY_SSL_VERIFYRESULT, &longinfo)) fprintf(stream, "%ld", longinfo); break; case VAR_EFFECTIVE_FILENAME: if(outs->filename) fprintf(stream, "%s", outs->filename); break; case VAR_PRIMARY_IP: if(CURLE_OK == curl_easy_getinfo(curl, CURLINFO_PRIMARY_IP, &stringp)) fprintf(stream, "%s", stringp); break; case VAR_PRIMARY_PORT: if(CURLE_OK == curl_easy_getinfo(curl, CURLINFO_PRIMARY_PORT, &longinfo)) fprintf(stream, "%ld", longinfo); break; case VAR_LOCAL_IP: if(CURLE_OK == curl_easy_getinfo(curl, CURLINFO_LOCAL_IP, &stringp)) fprintf(stream, "%s", stringp); break; case VAR_LOCAL_PORT: if(CURLE_OK == curl_easy_getinfo(curl, CURLINFO_LOCAL_PORT, &longinfo)) fprintf(stream, "%ld", longinfo); break; case VAR_HTTP_VERSION: if(CURLE_OK == curl_easy_getinfo(curl, CURLINFO_HTTP_VERSION, &longinfo)) { const char *version = "0"; switch(longinfo) { case CURL_HTTP_VERSION_1_0: version = "1.0"; break; case CURL_HTTP_VERSION_1_1: version = "1.1"; break; case CURL_HTTP_VERSION_2_0: version = "2"; break; } fprintf(stream, version); } break; case VAR_SCHEME: if(CURLE_OK == curl_easy_getinfo(curl, CURLINFO_SCHEME, &stringp)) fprintf(stream, "%s", stringp); break; default: break; } break; } } if(!match) { fprintf(stderr, "curl: unknown --write-out variable: '%s'\n", ptr); } ptr = end + 1; /* pass the end */ *end = keepit; } else { /* illegal syntax, then just output the characters that are used */ fputc('%', stream); fputc(ptr[1], stream); ptr += 2; } } } else if('\\' == *ptr) { switch(ptr[1]) { case 'r': fputc('\r', stream); break; case 'n': fputc('\n', stream); break; case 't': fputc('\t', stream); break; default: /* unknown, just output this */ fputc(*ptr, stream); fputc(ptr[1], stream); break; } ptr += 2; } else { fputc(*ptr, stream); ptr++; } } }
./CrossVul/dataset_final_sorted/CWE-119/c/good_3259_0
crossvul-cpp_data_bad_341_8
/* * cryptoflex-tool.c: Tool for doing various Cryptoflex related stuff * * Copyright (C) 2001 Juha Yrjölä <juha.yrjola@iki.fi> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "config.h" #include "libopensc/sc-ossl-compat.h" #include <openssl/bn.h> #include <openssl/rsa.h> #include <openssl/x509.h> #include <openssl/pem.h> #include <openssl/err.h> #include "libopensc/pkcs15.h" #include "common/compat_strlcpy.h" #include "common/compat_strlcat.h" #include "util.h" static const char *app_name = "cryptoflex-tool"; static char * opt_reader = NULL; static int opt_wait = 0; static int opt_key_num = 1, opt_pin_num = -1; static int verbose = 0; static int opt_exponent = 3; static int opt_mod_length = 1024; static int opt_key_count = 1; static int opt_pin_attempts = 10; static int opt_puk_attempts = 10; static const char *opt_appdf = NULL, *opt_prkeyf = NULL, *opt_pubkeyf = NULL; static u8 *pincode = NULL; static const struct option options[] = { { "list-keys", 0, NULL, 'l' }, { "create-key-files", 1, NULL, 'c' }, { "create-pin-file", 1, NULL, 'P' }, { "generate-key", 0, NULL, 'g' }, { "read-key", 0, NULL, 'R' }, { "verify-pin", 0, NULL, 'V' }, { "key-num", 1, NULL, 'k' }, { "app-df", 1, NULL, 'a' }, { "prkey-file", 1, NULL, 'p' }, { "pubkey-file", 1, NULL, 'u' }, { "exponent", 1, NULL, 'e' }, { "modulus-length", 1, NULL, 'm' }, { "reader", 1, NULL, 'r' }, { "wait", 0, NULL, 'w' }, { "verbose", 0, NULL, 'v' }, { NULL, 0, NULL, 0 } }; static const char *option_help[] = { "Lists all keys in a public key file", "Creates new RSA key files for <arg> keys", "Creates a new CHV<arg> file", "Generates a new RSA key pair", "Reads a public key from the card", "Verifies CHV1 before issuing commands", "Selects which key number to operate on [1]", "Selects the DF to operate in", "Private key file", "Public key file", "The RSA exponent to use in key generation [3]", "Modulus length to use in key generation [1024]", "Uses reader <arg>", "Wait for card insertion", "Verbose operation. Use several times to enable debug output.", }; static sc_context_t *ctx = NULL; static sc_card_t *card = NULL; static char *getpin(const char *prompt) { char *buf, pass[20]; int i; printf("%s", prompt); fflush(stdout); if (fgets(pass, 20, stdin) == NULL) return NULL; for (i = 0; i < 20; i++) if (pass[i] == '\n') pass[i] = 0; if (strlen(pass) == 0) return NULL; buf = malloc(8); if (buf == NULL) return NULL; if (strlen(pass) > 8) { fprintf(stderr, "PIN code too long.\n"); free(buf); return NULL; } memset(buf, 0, 8); strlcpy(buf, pass, 8); return buf; } static int verify_pin(int pin) { char prompt[50]; int r, tries_left = -1; if (pincode == NULL) { sprintf(prompt, "Please enter CHV%d: ", pin); pincode = (u8 *) getpin(prompt); if (pincode == NULL || strlen((char *) pincode) == 0) return -1; } if (pin != 1 && pin != 2) return -3; r = sc_verify(card, SC_AC_CHV, pin, pincode, 8, &tries_left); if (r) { memset(pincode, 0, 8); free(pincode); pincode = NULL; fprintf(stderr, "PIN code verification failed: %s\n", sc_strerror(r)); return -1; } return 0; } static int select_app_df(void) { sc_path_t path; sc_file_t *file; char str[80]; int r; strcpy(str, "3F00"); if (opt_appdf != NULL) strlcat(str, opt_appdf, sizeof str); sc_format_path(str, &path); r = sc_select_file(card, &path, &file); if (r) { fprintf(stderr, "Unable to select application DF: %s\n", sc_strerror(r)); return -1; } if (file->type != SC_FILE_TYPE_DF) { fprintf(stderr, "Selected application DF is not a DF.\n"); return -1; } sc_file_free(file); if (opt_pin_num >= 0) return verify_pin(opt_pin_num); else return 0; } static void invert_buf(u8 *dest, const u8 *src, size_t c) { size_t i; for (i = 0; i < c; i++) dest[i] = src[c-1-i]; } static BIGNUM * cf2bn(const u8 *buf, size_t bufsize, BIGNUM *num) { u8 tmp[512]; invert_buf(tmp, buf, bufsize); return BN_bin2bn(tmp, bufsize, num); } static int bn2cf(const BIGNUM *num, u8 *buf) { u8 tmp[512]; int r; r = BN_bn2bin(num, tmp); if (r <= 0) return r; invert_buf(buf, tmp, r); return r; } static int parse_public_key(const u8 *key, size_t keysize, RSA *rsa) { const u8 *p = key; BIGNUM *n, *e; int base; base = (keysize - 7) / 5; if (base != 32 && base != 48 && base != 64 && base != 128) { fprintf(stderr, "Invalid public key.\n"); return -1; } p += 3; n = BN_new(); if (n == NULL) return -1; cf2bn(p, 2 * base, n); p += 2 * base; p += base; p += 2 * base; e = BN_new(); if (e == NULL) return -1; cf2bn(p, 4, e); if (RSA_set0_key(rsa, n, e, NULL) != 1) return -1; return 0; } static int gen_d(RSA *rsa) { BN_CTX *bnctx; BIGNUM *r0, *r1, *r2; const BIGNUM *rsa_p, *rsa_q, *rsa_n, *rsa_e, *rsa_d; BIGNUM *rsa_n_new, *rsa_e_new, *rsa_d_new; bnctx = BN_CTX_new(); if (bnctx == NULL) return -1; BN_CTX_start(bnctx); r0 = BN_CTX_get(bnctx); r1 = BN_CTX_get(bnctx); r2 = BN_CTX_get(bnctx); RSA_get0_key(rsa, &rsa_n, &rsa_e, &rsa_d); RSA_get0_factors(rsa, &rsa_p, &rsa_q); BN_sub(r1, rsa_p, BN_value_one()); BN_sub(r2, rsa_q, BN_value_one()); BN_mul(r0, r1, r2, bnctx); if ((rsa_d_new = BN_mod_inverse(NULL, rsa_e, r0, bnctx)) == NULL) { fprintf(stderr, "BN_mod_inverse() failed.\n"); return -1; } /* RSA_set0_key will free previous value, and replace with new value * Thus the need to copy the contents of rsa_n and rsa_e */ rsa_n_new = BN_dup(rsa_n); rsa_e_new = BN_dup(rsa_e); if (RSA_set0_key(rsa, rsa_n_new, rsa_e_new, rsa_d_new) != 1) return -1; BN_CTX_end(bnctx); BN_CTX_free(bnctx); return 0; } static int parse_private_key(const u8 *key, size_t keysize, RSA *rsa) { const u8 *p = key; BIGNUM *bn_p, *q, *dmp1, *dmq1, *iqmp; int base; base = (keysize - 3) / 5; if (base != 32 && base != 48 && base != 64 && base != 128) { fprintf(stderr, "Invalid private key.\n"); return -1; } p += 3; bn_p = BN_new(); if (bn_p == NULL) return -1; cf2bn(p, base, bn_p); p += base; q = BN_new(); if (q == NULL) return -1; cf2bn(p, base, q); p += base; iqmp = BN_new(); if (iqmp == NULL) return -1; cf2bn(p, base, iqmp); p += base; dmp1 = BN_new(); if (dmp1 == NULL) return -1; cf2bn(p, base, dmp1); p += base; dmq1 = BN_new(); if (dmq1 == NULL) return -1; cf2bn(p, base, dmq1); p += base; if (RSA_set0_factors(rsa, bn_p, q) != 1) return -1; if (RSA_set0_crt_params(rsa, dmp1, dmq1, iqmp) != 1) return -1; if (gen_d(rsa)) return -1; return 0; } static int read_public_key(RSA *rsa) { int r; sc_path_t path; sc_file_t *file; u8 buf[2048], *p = buf; size_t bufsize, keysize; r = select_app_df(); if (r) return 1; sc_format_path("I1012", &path); r = sc_select_file(card, &path, &file); if (r) { fprintf(stderr, "Unable to select public key file: %s\n", sc_strerror(r)); return 2; } bufsize = file->size; sc_file_free(file); r = sc_read_binary(card, 0, buf, bufsize, 0); if (r < 0) { fprintf(stderr, "Unable to read public key file: %s\n", sc_strerror(r)); return 2; } bufsize = r; do { if (bufsize < 4) return 3; keysize = (p[0] << 8) | p[1]; if (keysize == 0) break; if (keysize < 3) return 3; if (p[2] == opt_key_num) break; p += keysize; bufsize -= keysize; } while (1); if (keysize == 0) { printf("Key number %d not found.\n", opt_key_num); return 2; } return parse_public_key(p, keysize, rsa); } static int read_private_key(RSA *rsa) { int r; sc_path_t path; sc_file_t *file; const sc_acl_entry_t *e; u8 buf[2048], *p = buf; size_t bufsize, keysize; r = select_app_df(); if (r) return 1; sc_format_path("I0012", &path); r = sc_select_file(card, &path, &file); if (r) { fprintf(stderr, "Unable to select private key file: %s\n", sc_strerror(r)); return 2; } e = sc_file_get_acl_entry(file, SC_AC_OP_READ); if (e == NULL || e->method == SC_AC_NEVER) return 10; bufsize = file->size; sc_file_free(file); r = sc_read_binary(card, 0, buf, bufsize, 0); if (r < 0) { fprintf(stderr, "Unable to read private key file: %s\n", sc_strerror(r)); return 2; } bufsize = r; do { if (bufsize < 4) return 3; keysize = (p[0] << 8) | p[1]; if (keysize == 0) break; if (keysize < 3) return 3; if (p[2] == opt_key_num) break; p += keysize; bufsize -= keysize; } while (1); if (keysize == 0) { printf("Key number %d not found.\n", opt_key_num); return 2; } return parse_private_key(p, keysize, rsa); } static int read_key(void) { RSA *rsa = RSA_new(); u8 buf[1024], *p = buf; u8 b64buf[2048]; int r; if (rsa == NULL) return -1; r = read_public_key(rsa); if (r) return r; r = i2d_RSA_PUBKEY(rsa, &p); if (r <= 0) { fprintf(stderr, "Error encoding public key.\n"); return -1; } r = sc_base64_encode(buf, r, b64buf, sizeof(b64buf), 64); if (r < 0) { fprintf(stderr, "Error in Base64 encoding: %s\n", sc_strerror(r)); return -1; } printf("-----BEGIN PUBLIC KEY-----\n%s-----END PUBLIC KEY-----\n", b64buf); r = read_private_key(rsa); if (r == 10) return 0; else if (r) return r; p = buf; r = i2d_RSAPrivateKey(rsa, &p); if (r <= 0) { fprintf(stderr, "Error encoding private key.\n"); return -1; } r = sc_base64_encode(buf, r, b64buf, sizeof(b64buf), 64); if (r < 0) { fprintf(stderr, "Error in Base64 encoding: %s\n", sc_strerror(r)); return -1; } printf("-----BEGIN RSA PRIVATE KEY-----\n%s-----END RSA PRIVATE KEY-----\n", b64buf); return 0; } static int list_keys(void) { int r, idx = 0; sc_path_t path; u8 buf[2048], *p = buf; size_t keysize, i; int mod_lens[] = { 512, 768, 1024, 2048 }; size_t sizes[] = { 167, 247, 327, 647 }; r = select_app_df(); if (r) return 1; sc_format_path("I1012", &path); r = sc_select_file(card, &path, NULL); if (r) { fprintf(stderr, "Unable to select public key file: %s\n", sc_strerror(r)); return 2; } do { int mod_len = -1; r = sc_read_binary(card, idx, buf, 3, 0); if (r < 0) { fprintf(stderr, "Unable to read public key file: %s\n", sc_strerror(r)); return 2; } keysize = (p[0] << 8) | p[1]; if (keysize == 0) break; idx += keysize; for (i = 0; i < sizeof(sizes)/sizeof(sizes[ 0]); i++) if (sizes[i] == keysize) mod_len = mod_lens[i]; if (mod_len < 0) printf("Key %d -- unknown modulus length\n", p[2] & 0x0F); else printf("Key %d -- Modulus length %d\n", p[2] & 0x0F, mod_len); } while (1); return 0; } static int generate_key(void) { sc_apdu_t apdu; u8 sbuf[4]; u8 p2; int r; switch (opt_mod_length) { case 512: p2 = 0x40; break; case 768: p2 = 0x60; break; case 1024: p2 = 0x80; break; case 2048: p2 = 0x00; break; default: fprintf(stderr, "Invalid modulus length.\n"); return 2; } sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x46, (u8) opt_key_num-1, p2); apdu.cla = 0xF0; apdu.lc = 4; apdu.datalen = 4; apdu.data = sbuf; sbuf[0] = opt_exponent & 0xFF; sbuf[1] = (opt_exponent >> 8) & 0xFF; sbuf[2] = (opt_exponent >> 16) & 0xFF; sbuf[3] = (opt_exponent >> 24) & 0xFF; r = select_app_df(); if (r) return 1; if (verbose) printf("Generating key...\n"); r = sc_transmit_apdu(card, &apdu); if (r) { fprintf(stderr, "APDU transmit failed: %s\n", sc_strerror(r)); if (r == SC_ERROR_TRANSMIT_FAILED) fprintf(stderr, "Reader has timed out. It is still possible that the key generation has\n" "succeeded.\n"); return 1; } if (apdu.sw1 == 0x90 && apdu.sw2 == 0x00) { printf("Key generation successful.\n"); return 0; } if (apdu.sw1 == 0x69 && apdu.sw2 == 0x82) fprintf(stderr, "CHV1 not verified or invalid exponent value.\n"); else fprintf(stderr, "Card returned SW1=%02X, SW2=%02X.\n", apdu.sw1, apdu.sw2); return 1; } static int create_key_files(void) { sc_file_t *file; int mod_lens[] = { 512, 768, 1024, 2048 }; int sizes[] = { 163, 243, 323, 643 }; int size = -1; int r; size_t i; for (i = 0; i < sizeof(mod_lens) / sizeof(int); i++) if (mod_lens[i] == opt_mod_length) { size = sizes[i]; break; } if (size == -1) { fprintf(stderr, "Invalid modulus length.\n"); return 1; } if (verbose) printf("Creating key files for %d keys.\n", opt_key_count); file = sc_file_new(); if (!file) { fprintf(stderr, "out of memory.\n"); return 1; } file->type = SC_FILE_TYPE_WORKING_EF; file->ef_structure = SC_FILE_EF_TRANSPARENT; file->id = 0x0012; file->size = opt_key_count * size + 3; sc_file_add_acl_entry(file, SC_AC_OP_READ, SC_AC_NEVER, SC_AC_KEY_REF_NONE); sc_file_add_acl_entry(file, SC_AC_OP_UPDATE, SC_AC_CHV, 1); sc_file_add_acl_entry(file, SC_AC_OP_INVALIDATE, SC_AC_CHV, 1); sc_file_add_acl_entry(file, SC_AC_OP_REHABILITATE, SC_AC_CHV, 1); if (select_app_df()) { sc_file_free(file); return 1; } r = sc_create_file(card, file); sc_file_free(file); if (r) { fprintf(stderr, "Unable to create private key file: %s\n", sc_strerror(r)); return 1; } file = sc_file_new(); if (!file) { fprintf(stderr, "out of memory.\n"); return 1; } file->type = SC_FILE_TYPE_WORKING_EF; file->ef_structure = SC_FILE_EF_TRANSPARENT; file->id = 0x1012; file->size = opt_key_count * (size + 4) + 3; sc_file_add_acl_entry(file, SC_AC_OP_READ, SC_AC_NONE, SC_AC_KEY_REF_NONE); sc_file_add_acl_entry(file, SC_AC_OP_UPDATE, SC_AC_CHV, 1); sc_file_add_acl_entry(file, SC_AC_OP_INVALIDATE, SC_AC_CHV, 1); sc_file_add_acl_entry(file, SC_AC_OP_REHABILITATE, SC_AC_CHV, 1); if (select_app_df()) { sc_file_free(file); return 1; } r = sc_create_file(card, file); sc_file_free(file); if (r) { fprintf(stderr, "Unable to create public key file: %s\n", sc_strerror(r)); return 1; } if (verbose) printf("Key files generated successfully.\n"); return 0; } static int read_rsa_privkey(RSA **rsa_out) { RSA *rsa = NULL; BIO *in = NULL; int r; in = BIO_new(BIO_s_file()); if (opt_prkeyf == NULL) { fprintf(stderr, "Private key file must be set.\n"); return 2; } r = BIO_read_filename(in, opt_prkeyf); if (r <= 0) { perror(opt_prkeyf); return 2; } rsa = PEM_read_bio_RSAPrivateKey(in, NULL, NULL, NULL); if (rsa == NULL) { fprintf(stderr, "Unable to load private key.\n"); return 2; } BIO_free(in); *rsa_out = rsa; return 0; } static int encode_private_key(RSA *rsa, u8 *key, size_t *keysize) { u8 buf[1024], *p = buf; u8 bnbuf[256]; int base = 0; int r; const BIGNUM *rsa_p, *rsa_q, *rsa_dmp1, *rsa_dmq1, *rsa_iqmp; switch (RSA_bits(rsa)) { case 512: base = 32; break; case 768: base = 48; break; case 1024: base = 64; break; case 2048: base = 128; break; } if (base == 0) { fprintf(stderr, "Key length invalid.\n"); return 2; } *p++ = (5 * base + 3) >> 8; *p++ = (5 * base + 3) & 0xFF; *p++ = opt_key_num; RSA_get0_factors(rsa, &rsa_p, &rsa_q); r = bn2cf(rsa_p, bnbuf); if (r != base) { fprintf(stderr, "Invalid private key.\n"); return 2; } memcpy(p, bnbuf, base); p += base; r = bn2cf(rsa_q, bnbuf); if (r != base) { fprintf(stderr, "Invalid private key.\n"); return 2; } memcpy(p, bnbuf, base); p += base; RSA_get0_crt_params(rsa, &rsa_dmp1, &rsa_dmq1, &rsa_iqmp); r = bn2cf(rsa_iqmp, bnbuf); if (r != base) { fprintf(stderr, "Invalid private key.\n"); return 2; } memcpy(p, bnbuf, base); p += base; r = bn2cf(rsa_dmp1, bnbuf); if (r != base) { fprintf(stderr, "Invalid private key.\n"); return 2; } memcpy(p, bnbuf, base); p += base; r = bn2cf(rsa_dmq1, bnbuf); if (r != base) { fprintf(stderr, "Invalid private key.\n"); return 2; } memcpy(p, bnbuf, base); p += base; memcpy(key, buf, p - buf); *keysize = p - buf; return 0; } static int encode_public_key(RSA *rsa, u8 *key, size_t *keysize) { u8 buf[1024], *p = buf; u8 bnbuf[256]; int base = 0; int r; const BIGNUM *rsa_n, *rsa_e; switch (RSA_bits(rsa)) { case 512: base = 32; break; case 768: base = 48; break; case 1024: base = 64; break; case 2048: base = 128; break; } if (base == 0) { fprintf(stderr, "Key length invalid.\n"); return 2; } *p++ = (5 * base + 7) >> 8; *p++ = (5 * base + 7) & 0xFF; *p++ = opt_key_num; RSA_get0_key(rsa, &rsa_n, &rsa_e, NULL); r = bn2cf(rsa_n, bnbuf); if (r != 2*base) { fprintf(stderr, "Invalid public key.\n"); return 2; } memcpy(p, bnbuf, 2*base); p += 2*base; memset(p, 0, base); p += base; memset(bnbuf, 0, 2*base); memcpy(p, bnbuf, 2*base); p += 2*base; r = bn2cf(rsa_e, bnbuf); memcpy(p, bnbuf, 4); p += 4; memcpy(key, buf, p - buf); *keysize = p - buf; return 0; } static int update_public_key(const u8 *key, size_t keysize) { int r, idx = 0; sc_path_t path; r = select_app_df(); if (r) return 1; sc_format_path("I1012", &path); r = sc_select_file(card, &path, NULL); if (r) { fprintf(stderr, "Unable to select public key file: %s\n", sc_strerror(r)); return 2; } idx = keysize * (opt_key_num-1); r = sc_update_binary(card, idx, key, keysize, 0); if (r < 0) { fprintf(stderr, "Unable to write public key: %s\n", sc_strerror(r)); return 2; } return 0; } static int update_private_key(const u8 *key, size_t keysize) { int r, idx = 0; sc_path_t path; r = select_app_df(); if (r) return 1; sc_format_path("I0012", &path); r = sc_select_file(card, &path, NULL); if (r) { fprintf(stderr, "Unable to select private key file: %s\n", sc_strerror(r)); return 2; } idx = keysize * (opt_key_num-1); r = sc_update_binary(card, idx, key, keysize, 0); if (r < 0) { fprintf(stderr, "Unable to write private key: %s\n", sc_strerror(r)); return 2; } return 0; } static int store_key(void) { u8 prv[1024], pub[1024]; size_t prvsize, pubsize; int r; RSA *rsa; r = read_rsa_privkey(&rsa); if (r) return r; r = encode_private_key(rsa, prv, &prvsize); if (r) return r; r = encode_public_key(rsa, pub, &pubsize); if (r) return r; if (verbose) printf("Storing private key...\n"); r = select_app_df(); if (r) return r; r = update_private_key(prv, prvsize); if (r) return r; if (verbose) printf("Storing public key...\n"); r = select_app_df(); if (r) return r; r = update_public_key(pub, pubsize); if (r) return r; return 0; } static int create_pin_file(const sc_path_t *inpath, int chv, const char *key_id) { char prompt[40], *pin, *puk; char buf[30], *p = buf; sc_path_t file_id, path; sc_file_t *file; size_t len; int r; file_id = *inpath; if (file_id.len < 2) return -1; if (chv == 1) sc_format_path("I0000", &file_id); else if (chv == 2) sc_format_path("I0100", &file_id); else return -1; r = sc_select_file(card, inpath, NULL); if (r) return -1; r = sc_select_file(card, &file_id, NULL); if (r == 0) return 0; sprintf(prompt, "Please enter CHV%d%s: ", chv, key_id); pin = getpin(prompt); if (pin == NULL) return -1; sprintf(prompt, "Please enter PUK for CHV%d%s: ", chv, key_id); puk = getpin(prompt); if (puk == NULL) { free(pin); return -1; } memset(p, 0xFF, 3); p += 3; memcpy(p, pin, 8); p += 8; *p++ = opt_pin_attempts; *p++ = opt_pin_attempts; memcpy(p, puk, 8); p += 8; *p++ = opt_puk_attempts; *p++ = opt_puk_attempts; len = p - buf; free(pin); free(puk); file = sc_file_new(); file->type = SC_FILE_TYPE_WORKING_EF; file->ef_structure = SC_FILE_EF_TRANSPARENT; sc_file_add_acl_entry(file, SC_AC_OP_READ, SC_AC_NEVER, SC_AC_KEY_REF_NONE); if (inpath->len == 2 && inpath->value[0] == 0x3F && inpath->value[1] == 0x00) sc_file_add_acl_entry(file, SC_AC_OP_UPDATE, SC_AC_AUT, 1); else sc_file_add_acl_entry(file, SC_AC_OP_UPDATE, SC_AC_CHV, 2); sc_file_add_acl_entry(file, SC_AC_OP_INVALIDATE, SC_AC_AUT, 1); sc_file_add_acl_entry(file, SC_AC_OP_REHABILITATE, SC_AC_AUT, 1); file->size = len; file->id = (file_id.value[0] << 8) | file_id.value[1]; r = sc_create_file(card, file); sc_file_free(file); if (r) { fprintf(stderr, "PIN file creation failed: %s\n", sc_strerror(r)); return r; } path = *inpath; sc_append_path(&path, &file_id); r = sc_select_file(card, &path, NULL); if (r) { fprintf(stderr, "Unable to select created PIN file: %s\n", sc_strerror(r)); return r; } r = sc_update_binary(card, 0, (const u8 *) buf, len, 0); if (r < 0) { fprintf(stderr, "Unable to update created PIN file: %s\n", sc_strerror(r)); return r; } return 0; } static int create_pin(void) { sc_path_t path; char buf[80]; if (opt_pin_num != 1 && opt_pin_num != 2) { fprintf(stderr, "Invalid PIN number. Possible values: 1, 2.\n"); return 2; } strcpy(buf, "3F00"); if (opt_appdf != NULL) strlcat(buf, opt_appdf, sizeof buf); sc_format_path(buf, &path); return create_pin_file(&path, opt_pin_num, ""); } int main(int argc, char *argv[]) { int err = 0, r, c, long_optind = 0; int action_count = 0; int do_read_key = 0; int do_generate_key = 0; int do_create_key_files = 0; int do_list_keys = 0; int do_store_key = 0; int do_create_pin_file = 0; sc_context_param_t ctx_param; while (1) { c = getopt_long(argc, argv, "P:Vslgc:Rk:r:p:u:e:m:vwa:", options, &long_optind); if (c == -1) break; if (c == '?') util_print_usage_and_die(app_name, options, option_help, NULL); switch (c) { case 'l': do_list_keys = 1; action_count++; break; case 'P': do_create_pin_file = 1; opt_pin_num = atoi(optarg); action_count++; break; case 'R': do_read_key = 1; action_count++; break; case 'g': do_generate_key = 1; action_count++; break; case 'c': do_create_key_files = 1; opt_key_count = atoi(optarg); action_count++; break; case 's': do_store_key = 1; action_count++; break; case 'k': opt_key_num = atoi(optarg); if (opt_key_num < 1 || opt_key_num > 15) { fprintf(stderr, "Key number invalid.\n"); exit(2); } break; case 'V': opt_pin_num = 1; break; case 'e': opt_exponent = atoi(optarg); break; case 'm': opt_mod_length = atoi(optarg); break; case 'p': opt_prkeyf = optarg; break; case 'u': opt_pubkeyf = optarg; break; case 'r': opt_reader = optarg; break; case 'v': verbose++; break; case 'w': opt_wait = 1; break; case 'a': opt_appdf = optarg; break; } } if (action_count == 0) util_print_usage_and_die(app_name, options, option_help, NULL); memset(&ctx_param, 0, sizeof(ctx_param)); ctx_param.ver = 0; ctx_param.app_name = app_name; r = sc_context_create(&ctx, &ctx_param); if (r) { fprintf(stderr, "Failed to establish context: %s\n", sc_strerror(r)); return 1; } if (verbose > 1) { ctx->debug = verbose; sc_ctx_log_to_file(ctx, "stderr"); } err = util_connect_card(ctx, &card, opt_reader, opt_wait, verbose); printf("Using card driver: %s\n", card->driver->name); if (do_create_pin_file) { if ((err = create_pin()) != 0) goto end; action_count--; } if (do_create_key_files) { if ((err = create_key_files()) != 0) goto end; action_count--; } if (do_generate_key) { if ((err = generate_key()) != 0) goto end; action_count--; } if (do_store_key) { if ((err = store_key()) != 0) goto end; action_count--; } if (do_list_keys) { if ((err = list_keys()) != 0) goto end; action_count--; } if (do_read_key) { if ((err = read_key()) != 0) goto end; action_count--; } if (pincode != NULL) { memset(pincode, 0, 8); free(pincode); } end: if (card) { sc_unlock(card); sc_disconnect_card(card); } if (ctx) sc_release_context(ctx); return err; }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_341_8
crossvul-cpp_data_bad_3311_0
/* DVB USB framework compliant Linux driver for the * DVBWorld DVB-S 2101, 2102, DVB-S2 2104, DVB-C 3101, * TeVii S421, S480, S482, S600, S630, S632, S650, S660, S662, * Prof 1100, 7500, * Geniatech SU3000, T220, * TechnoTrend S2-4600, * Terratec Cinergy S2 cards * Copyright (C) 2008-2012 Igor M. Liplianin (liplianin@me.by) * * 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, version 2. * * see Documentation/dvb/README.dvb-usb for more information */ #include "dvb-usb-ids.h" #include "dw2102.h" #include "si21xx.h" #include "stv0299.h" #include "z0194a.h" #include "stv0288.h" #include "stb6000.h" #include "eds1547.h" #include "cx24116.h" #include "tda1002x.h" #include "mt312.h" #include "zl10039.h" #include "ts2020.h" #include "ds3000.h" #include "stv0900.h" #include "stv6110.h" #include "stb6100.h" #include "stb6100_proc.h" #include "m88rs2000.h" #include "tda18271.h" #include "cxd2820r.h" #include "m88ds3103.h" /* Max transfer size done by I2C transfer functions */ #define MAX_XFER_SIZE 64 #define DW210X_READ_MSG 0 #define DW210X_WRITE_MSG 1 #define REG_1F_SYMBOLRATE_BYTE0 0x1f #define REG_20_SYMBOLRATE_BYTE1 0x20 #define REG_21_SYMBOLRATE_BYTE2 0x21 /* on my own*/ #define DW2102_VOLTAGE_CTRL (0x1800) #define SU3000_STREAM_CTRL (0x1900) #define DW2102_RC_QUERY (0x1a00) #define DW2102_LED_CTRL (0x1b00) #define DW2101_FIRMWARE "dvb-usb-dw2101.fw" #define DW2102_FIRMWARE "dvb-usb-dw2102.fw" #define DW2104_FIRMWARE "dvb-usb-dw2104.fw" #define DW3101_FIRMWARE "dvb-usb-dw3101.fw" #define S630_FIRMWARE "dvb-usb-s630.fw" #define S660_FIRMWARE "dvb-usb-s660.fw" #define P1100_FIRMWARE "dvb-usb-p1100.fw" #define P7500_FIRMWARE "dvb-usb-p7500.fw" #define err_str "did not find the firmware file. (%s) " \ "Please see linux/Documentation/dvb/ for more details " \ "on firmware-problems." struct dw2102_state { u8 initialized; u8 last_lock; struct i2c_client *i2c_client_demod; struct i2c_client *i2c_client_tuner; /* fe hook functions*/ int (*old_set_voltage)(struct dvb_frontend *f, enum fe_sec_voltage v); int (*fe_read_status)(struct dvb_frontend *fe, enum fe_status *status); }; /* debug */ static int dvb_usb_dw2102_debug; module_param_named(debug, dvb_usb_dw2102_debug, int, 0644); MODULE_PARM_DESC(debug, "set debugging level (1=info 2=xfer 4=rc(or-able))." DVB_USB_DEBUG_STATUS); /* demod probe */ static int demod_probe = 1; module_param_named(demod, demod_probe, int, 0644); MODULE_PARM_DESC(demod, "demod to probe (1=cx24116 2=stv0903+stv6110 4=stv0903+stb6100(or-able))."); DVB_DEFINE_MOD_OPT_ADAPTER_NR(adapter_nr); static int dw210x_op_rw(struct usb_device *dev, u8 request, u16 value, u16 index, u8 * data, u16 len, int flags) { int ret; u8 *u8buf; unsigned int pipe = (flags == DW210X_READ_MSG) ? usb_rcvctrlpipe(dev, 0) : usb_sndctrlpipe(dev, 0); u8 request_type = (flags == DW210X_READ_MSG) ? USB_DIR_IN : USB_DIR_OUT; u8buf = kmalloc(len, GFP_KERNEL); if (!u8buf) return -ENOMEM; if (flags == DW210X_WRITE_MSG) memcpy(u8buf, data, len); ret = usb_control_msg(dev, pipe, request, request_type | USB_TYPE_VENDOR, value, index , u8buf, len, 2000); if (flags == DW210X_READ_MSG) memcpy(data, u8buf, len); kfree(u8buf); return ret; } /* I2C */ static int dw2102_i2c_transfer(struct i2c_adapter *adap, struct i2c_msg msg[], int num) { struct dvb_usb_device *d = i2c_get_adapdata(adap); int i = 0; u8 buf6[] = {0x2c, 0x05, 0xc0, 0, 0, 0, 0}; u16 value; if (!d) return -ENODEV; if (mutex_lock_interruptible(&d->i2c_mutex) < 0) return -EAGAIN; switch (num) { case 2: /* read stv0299 register */ value = msg[0].buf[0];/* register */ for (i = 0; i < msg[1].len; i++) { dw210x_op_rw(d->udev, 0xb5, value + i, 0, buf6, 2, DW210X_READ_MSG); msg[1].buf[i] = buf6[0]; } break; case 1: switch (msg[0].addr) { case 0x68: /* write to stv0299 register */ buf6[0] = 0x2a; buf6[1] = msg[0].buf[0]; buf6[2] = msg[0].buf[1]; dw210x_op_rw(d->udev, 0xb2, 0, 0, buf6, 3, DW210X_WRITE_MSG); break; case 0x60: if (msg[0].flags == 0) { /* write to tuner pll */ buf6[0] = 0x2c; buf6[1] = 5; buf6[2] = 0xc0; buf6[3] = msg[0].buf[0]; buf6[4] = msg[0].buf[1]; buf6[5] = msg[0].buf[2]; buf6[6] = msg[0].buf[3]; dw210x_op_rw(d->udev, 0xb2, 0, 0, buf6, 7, DW210X_WRITE_MSG); } else { /* read from tuner */ dw210x_op_rw(d->udev, 0xb5, 0, 0, buf6, 1, DW210X_READ_MSG); msg[0].buf[0] = buf6[0]; } break; case (DW2102_RC_QUERY): dw210x_op_rw(d->udev, 0xb8, 0, 0, buf6, 2, DW210X_READ_MSG); msg[0].buf[0] = buf6[0]; msg[0].buf[1] = buf6[1]; break; case (DW2102_VOLTAGE_CTRL): buf6[0] = 0x30; buf6[1] = msg[0].buf[0]; dw210x_op_rw(d->udev, 0xb2, 0, 0, buf6, 2, DW210X_WRITE_MSG); break; } break; } mutex_unlock(&d->i2c_mutex); return num; } static int dw2102_serit_i2c_transfer(struct i2c_adapter *adap, struct i2c_msg msg[], int num) { struct dvb_usb_device *d = i2c_get_adapdata(adap); u8 buf6[] = {0, 0, 0, 0, 0, 0, 0}; if (!d) return -ENODEV; if (mutex_lock_interruptible(&d->i2c_mutex) < 0) return -EAGAIN; switch (num) { case 2: /* read si2109 register by number */ buf6[0] = msg[0].addr << 1; buf6[1] = msg[0].len; buf6[2] = msg[0].buf[0]; dw210x_op_rw(d->udev, 0xc2, 0, 0, buf6, msg[0].len + 2, DW210X_WRITE_MSG); /* read si2109 register */ dw210x_op_rw(d->udev, 0xc3, 0xd0, 0, buf6, msg[1].len + 2, DW210X_READ_MSG); memcpy(msg[1].buf, buf6 + 2, msg[1].len); break; case 1: switch (msg[0].addr) { case 0x68: /* write to si2109 register */ buf6[0] = msg[0].addr << 1; buf6[1] = msg[0].len; memcpy(buf6 + 2, msg[0].buf, msg[0].len); dw210x_op_rw(d->udev, 0xc2, 0, 0, buf6, msg[0].len + 2, DW210X_WRITE_MSG); break; case(DW2102_RC_QUERY): dw210x_op_rw(d->udev, 0xb8, 0, 0, buf6, 2, DW210X_READ_MSG); msg[0].buf[0] = buf6[0]; msg[0].buf[1] = buf6[1]; break; case(DW2102_VOLTAGE_CTRL): buf6[0] = 0x30; buf6[1] = msg[0].buf[0]; dw210x_op_rw(d->udev, 0xb2, 0, 0, buf6, 2, DW210X_WRITE_MSG); break; } break; } mutex_unlock(&d->i2c_mutex); return num; } static int dw2102_earda_i2c_transfer(struct i2c_adapter *adap, struct i2c_msg msg[], int num) { struct dvb_usb_device *d = i2c_get_adapdata(adap); int ret; if (!d) return -ENODEV; if (mutex_lock_interruptible(&d->i2c_mutex) < 0) return -EAGAIN; switch (num) { case 2: { /* read */ /* first write first register number */ u8 ibuf[MAX_XFER_SIZE], obuf[3]; if (2 + msg[1].len > sizeof(ibuf)) { warn("i2c rd: len=%d is too big!\n", msg[1].len); ret = -EOPNOTSUPP; goto unlock; } obuf[0] = msg[0].addr << 1; obuf[1] = msg[0].len; obuf[2] = msg[0].buf[0]; dw210x_op_rw(d->udev, 0xc2, 0, 0, obuf, msg[0].len + 2, DW210X_WRITE_MSG); /* second read registers */ dw210x_op_rw(d->udev, 0xc3, 0xd1 , 0, ibuf, msg[1].len + 2, DW210X_READ_MSG); memcpy(msg[1].buf, ibuf + 2, msg[1].len); break; } case 1: switch (msg[0].addr) { case 0x68: { /* write to register */ u8 obuf[MAX_XFER_SIZE]; if (2 + msg[0].len > sizeof(obuf)) { warn("i2c wr: len=%d is too big!\n", msg[1].len); ret = -EOPNOTSUPP; goto unlock; } obuf[0] = msg[0].addr << 1; obuf[1] = msg[0].len; memcpy(obuf + 2, msg[0].buf, msg[0].len); dw210x_op_rw(d->udev, 0xc2, 0, 0, obuf, msg[0].len + 2, DW210X_WRITE_MSG); break; } case 0x61: { /* write to tuner */ u8 obuf[MAX_XFER_SIZE]; if (2 + msg[0].len > sizeof(obuf)) { warn("i2c wr: len=%d is too big!\n", msg[1].len); ret = -EOPNOTSUPP; goto unlock; } obuf[0] = msg[0].addr << 1; obuf[1] = msg[0].len; memcpy(obuf + 2, msg[0].buf, msg[0].len); dw210x_op_rw(d->udev, 0xc2, 0, 0, obuf, msg[0].len + 2, DW210X_WRITE_MSG); break; } case(DW2102_RC_QUERY): { u8 ibuf[2]; dw210x_op_rw(d->udev, 0xb8, 0, 0, ibuf, 2, DW210X_READ_MSG); memcpy(msg[0].buf, ibuf , 2); break; } case(DW2102_VOLTAGE_CTRL): { u8 obuf[2]; obuf[0] = 0x30; obuf[1] = msg[0].buf[0]; dw210x_op_rw(d->udev, 0xb2, 0, 0, obuf, 2, DW210X_WRITE_MSG); break; } } break; } ret = num; unlock: mutex_unlock(&d->i2c_mutex); return ret; } static int dw2104_i2c_transfer(struct i2c_adapter *adap, struct i2c_msg msg[], int num) { struct dvb_usb_device *d = i2c_get_adapdata(adap); int len, i, j, ret; if (!d) return -ENODEV; if (mutex_lock_interruptible(&d->i2c_mutex) < 0) return -EAGAIN; for (j = 0; j < num; j++) { switch (msg[j].addr) { case(DW2102_RC_QUERY): { u8 ibuf[2]; dw210x_op_rw(d->udev, 0xb8, 0, 0, ibuf, 2, DW210X_READ_MSG); memcpy(msg[j].buf, ibuf , 2); break; } case(DW2102_VOLTAGE_CTRL): { u8 obuf[2]; obuf[0] = 0x30; obuf[1] = msg[j].buf[0]; dw210x_op_rw(d->udev, 0xb2, 0, 0, obuf, 2, DW210X_WRITE_MSG); break; } /*case 0x55: cx24116 case 0x6a: stv0903 case 0x68: ds3000, stv0903 case 0x60: ts2020, stv6110, stb6100 */ default: { if (msg[j].flags == I2C_M_RD) { /* read registers */ u8 ibuf[MAX_XFER_SIZE]; if (2 + msg[j].len > sizeof(ibuf)) { warn("i2c rd: len=%d is too big!\n", msg[j].len); ret = -EOPNOTSUPP; goto unlock; } dw210x_op_rw(d->udev, 0xc3, (msg[j].addr << 1) + 1, 0, ibuf, msg[j].len + 2, DW210X_READ_MSG); memcpy(msg[j].buf, ibuf + 2, msg[j].len); mdelay(10); } else if (((msg[j].buf[0] == 0xb0) && (msg[j].addr == 0x68)) || ((msg[j].buf[0] == 0xf7) && (msg[j].addr == 0x55))) { /* write firmware */ u8 obuf[19]; obuf[0] = msg[j].addr << 1; obuf[1] = (msg[j].len > 15 ? 17 : msg[j].len); obuf[2] = msg[j].buf[0]; len = msg[j].len - 1; i = 1; do { memcpy(obuf + 3, msg[j].buf + i, (len > 16 ? 16 : len)); dw210x_op_rw(d->udev, 0xc2, 0, 0, obuf, (len > 16 ? 16 : len) + 3, DW210X_WRITE_MSG); i += 16; len -= 16; } while (len > 0); } else { /* write registers */ u8 obuf[MAX_XFER_SIZE]; if (2 + msg[j].len > sizeof(obuf)) { warn("i2c wr: len=%d is too big!\n", msg[j].len); ret = -EOPNOTSUPP; goto unlock; } obuf[0] = msg[j].addr << 1; obuf[1] = msg[j].len; memcpy(obuf + 2, msg[j].buf, msg[j].len); dw210x_op_rw(d->udev, 0xc2, 0, 0, obuf, msg[j].len + 2, DW210X_WRITE_MSG); } break; } } } ret = num; unlock: mutex_unlock(&d->i2c_mutex); return ret; } static int dw3101_i2c_transfer(struct i2c_adapter *adap, struct i2c_msg msg[], int num) { struct dvb_usb_device *d = i2c_get_adapdata(adap); int ret; int i; if (!d) return -ENODEV; if (mutex_lock_interruptible(&d->i2c_mutex) < 0) return -EAGAIN; switch (num) { case 2: { /* read */ /* first write first register number */ u8 ibuf[MAX_XFER_SIZE], obuf[3]; if (2 + msg[1].len > sizeof(ibuf)) { warn("i2c rd: len=%d is too big!\n", msg[1].len); ret = -EOPNOTSUPP; goto unlock; } obuf[0] = msg[0].addr << 1; obuf[1] = msg[0].len; obuf[2] = msg[0].buf[0]; dw210x_op_rw(d->udev, 0xc2, 0, 0, obuf, msg[0].len + 2, DW210X_WRITE_MSG); /* second read registers */ dw210x_op_rw(d->udev, 0xc3, 0x19 , 0, ibuf, msg[1].len + 2, DW210X_READ_MSG); memcpy(msg[1].buf, ibuf + 2, msg[1].len); break; } case 1: switch (msg[0].addr) { case 0x60: case 0x0c: { /* write to register */ u8 obuf[MAX_XFER_SIZE]; if (2 + msg[0].len > sizeof(obuf)) { warn("i2c wr: len=%d is too big!\n", msg[0].len); ret = -EOPNOTSUPP; goto unlock; } obuf[0] = msg[0].addr << 1; obuf[1] = msg[0].len; memcpy(obuf + 2, msg[0].buf, msg[0].len); dw210x_op_rw(d->udev, 0xc2, 0, 0, obuf, msg[0].len + 2, DW210X_WRITE_MSG); break; } case(DW2102_RC_QUERY): { u8 ibuf[2]; dw210x_op_rw(d->udev, 0xb8, 0, 0, ibuf, 2, DW210X_READ_MSG); memcpy(msg[0].buf, ibuf , 2); break; } } break; } for (i = 0; i < num; i++) { deb_xfer("%02x:%02x: %s ", i, msg[i].addr, msg[i].flags == 0 ? ">>>" : "<<<"); debug_dump(msg[i].buf, msg[i].len, deb_xfer); } ret = num; unlock: mutex_unlock(&d->i2c_mutex); return ret; } static int s6x0_i2c_transfer(struct i2c_adapter *adap, struct i2c_msg msg[], int num) { struct dvb_usb_device *d = i2c_get_adapdata(adap); struct usb_device *udev; int len, i, j, ret; if (!d) return -ENODEV; udev = d->udev; if (mutex_lock_interruptible(&d->i2c_mutex) < 0) return -EAGAIN; for (j = 0; j < num; j++) { switch (msg[j].addr) { case (DW2102_RC_QUERY): { u8 ibuf[5]; dw210x_op_rw(d->udev, 0xb8, 0, 0, ibuf, 5, DW210X_READ_MSG); memcpy(msg[j].buf, ibuf + 3, 2); break; } case (DW2102_VOLTAGE_CTRL): { u8 obuf[2]; obuf[0] = 1; obuf[1] = msg[j].buf[1];/* off-on */ dw210x_op_rw(d->udev, 0x8a, 0, 0, obuf, 2, DW210X_WRITE_MSG); obuf[0] = 3; obuf[1] = msg[j].buf[0];/* 13v-18v */ dw210x_op_rw(d->udev, 0x8a, 0, 0, obuf, 2, DW210X_WRITE_MSG); break; } case (DW2102_LED_CTRL): { u8 obuf[2]; obuf[0] = 5; obuf[1] = msg[j].buf[0]; dw210x_op_rw(d->udev, 0x8a, 0, 0, obuf, 2, DW210X_WRITE_MSG); break; } /*case 0x55: cx24116 case 0x6a: stv0903 case 0x68: ds3000, stv0903, rs2000 case 0x60: ts2020, stv6110, stb6100 case 0xa0: eeprom */ default: { if (msg[j].flags == I2C_M_RD) { /* read registers */ u8 ibuf[MAX_XFER_SIZE]; if (msg[j].len > sizeof(ibuf)) { warn("i2c rd: len=%d is too big!\n", msg[j].len); ret = -EOPNOTSUPP; goto unlock; } dw210x_op_rw(d->udev, 0x91, 0, 0, ibuf, msg[j].len, DW210X_READ_MSG); memcpy(msg[j].buf, ibuf, msg[j].len); break; } else if ((msg[j].buf[0] == 0xb0) && (msg[j].addr == 0x68)) { /* write firmware */ u8 obuf[19]; obuf[0] = (msg[j].len > 16 ? 18 : msg[j].len + 1); obuf[1] = msg[j].addr << 1; obuf[2] = msg[j].buf[0]; len = msg[j].len - 1; i = 1; do { memcpy(obuf + 3, msg[j].buf + i, (len > 16 ? 16 : len)); dw210x_op_rw(d->udev, 0x80, 0, 0, obuf, (len > 16 ? 16 : len) + 3, DW210X_WRITE_MSG); i += 16; len -= 16; } while (len > 0); } else if (j < (num - 1)) { /* write register addr before read */ u8 obuf[MAX_XFER_SIZE]; if (2 + msg[j].len > sizeof(obuf)) { warn("i2c wr: len=%d is too big!\n", msg[j].len); ret = -EOPNOTSUPP; goto unlock; } obuf[0] = msg[j + 1].len; obuf[1] = (msg[j].addr << 1); memcpy(obuf + 2, msg[j].buf, msg[j].len); dw210x_op_rw(d->udev, le16_to_cpu(udev->descriptor.idProduct) == 0x7500 ? 0x92 : 0x90, 0, 0, obuf, msg[j].len + 2, DW210X_WRITE_MSG); break; } else { /* write registers */ u8 obuf[MAX_XFER_SIZE]; if (2 + msg[j].len > sizeof(obuf)) { warn("i2c wr: len=%d is too big!\n", msg[j].len); ret = -EOPNOTSUPP; goto unlock; } obuf[0] = msg[j].len + 1; obuf[1] = (msg[j].addr << 1); memcpy(obuf + 2, msg[j].buf, msg[j].len); dw210x_op_rw(d->udev, 0x80, 0, 0, obuf, msg[j].len + 2, DW210X_WRITE_MSG); break; } break; } } } ret = num; unlock: mutex_unlock(&d->i2c_mutex); return ret; } static int su3000_i2c_transfer(struct i2c_adapter *adap, struct i2c_msg msg[], int num) { struct dvb_usb_device *d = i2c_get_adapdata(adap); u8 obuf[0x40], ibuf[0x40]; if (!d) return -ENODEV; if (mutex_lock_interruptible(&d->i2c_mutex) < 0) return -EAGAIN; switch (num) { case 1: switch (msg[0].addr) { case SU3000_STREAM_CTRL: obuf[0] = msg[0].buf[0] + 0x36; obuf[1] = 3; obuf[2] = 0; if (dvb_usb_generic_rw(d, obuf, 3, ibuf, 0, 0) < 0) err("i2c transfer failed."); break; case DW2102_RC_QUERY: obuf[0] = 0x10; if (dvb_usb_generic_rw(d, obuf, 1, ibuf, 2, 0) < 0) err("i2c transfer failed."); msg[0].buf[1] = ibuf[0]; msg[0].buf[0] = ibuf[1]; break; default: /* always i2c write*/ obuf[0] = 0x08; obuf[1] = msg[0].addr; obuf[2] = msg[0].len; memcpy(&obuf[3], msg[0].buf, msg[0].len); if (dvb_usb_generic_rw(d, obuf, msg[0].len + 3, ibuf, 1, 0) < 0) err("i2c transfer failed."); } break; case 2: /* always i2c read */ obuf[0] = 0x09; obuf[1] = msg[0].len; obuf[2] = msg[1].len; obuf[3] = msg[0].addr; memcpy(&obuf[4], msg[0].buf, msg[0].len); if (dvb_usb_generic_rw(d, obuf, msg[0].len + 4, ibuf, msg[1].len + 1, 0) < 0) err("i2c transfer failed."); memcpy(msg[1].buf, &ibuf[1], msg[1].len); break; default: warn("more than 2 i2c messages at a time is not handled yet."); break; } mutex_unlock(&d->i2c_mutex); return num; } static u32 dw210x_i2c_func(struct i2c_adapter *adapter) { return I2C_FUNC_I2C; } static struct i2c_algorithm dw2102_i2c_algo = { .master_xfer = dw2102_i2c_transfer, .functionality = dw210x_i2c_func, }; static struct i2c_algorithm dw2102_serit_i2c_algo = { .master_xfer = dw2102_serit_i2c_transfer, .functionality = dw210x_i2c_func, }; static struct i2c_algorithm dw2102_earda_i2c_algo = { .master_xfer = dw2102_earda_i2c_transfer, .functionality = dw210x_i2c_func, }; static struct i2c_algorithm dw2104_i2c_algo = { .master_xfer = dw2104_i2c_transfer, .functionality = dw210x_i2c_func, }; static struct i2c_algorithm dw3101_i2c_algo = { .master_xfer = dw3101_i2c_transfer, .functionality = dw210x_i2c_func, }; static struct i2c_algorithm s6x0_i2c_algo = { .master_xfer = s6x0_i2c_transfer, .functionality = dw210x_i2c_func, }; static struct i2c_algorithm su3000_i2c_algo = { .master_xfer = su3000_i2c_transfer, .functionality = dw210x_i2c_func, }; static int dw210x_read_mac_address(struct dvb_usb_device *d, u8 mac[6]) { int i; u8 ibuf[] = {0, 0}; u8 eeprom[256], eepromline[16]; for (i = 0; i < 256; i++) { if (dw210x_op_rw(d->udev, 0xb6, 0xa0 , i, ibuf, 2, DW210X_READ_MSG) < 0) { err("read eeprom failed."); return -1; } else { eepromline[i%16] = ibuf[0]; eeprom[i] = ibuf[0]; } if ((i % 16) == 15) { deb_xfer("%02x: ", i - 15); debug_dump(eepromline, 16, deb_xfer); } } memcpy(mac, eeprom + 8, 6); return 0; }; static int s6x0_read_mac_address(struct dvb_usb_device *d, u8 mac[6]) { int i, ret; u8 ibuf[] = { 0 }, obuf[] = { 0 }; u8 eeprom[256], eepromline[16]; struct i2c_msg msg[] = { { .addr = 0xa0 >> 1, .flags = 0, .buf = obuf, .len = 1, }, { .addr = 0xa0 >> 1, .flags = I2C_M_RD, .buf = ibuf, .len = 1, } }; for (i = 0; i < 256; i++) { obuf[0] = i; ret = s6x0_i2c_transfer(&d->i2c_adap, msg, 2); if (ret != 2) { err("read eeprom failed."); return -1; } else { eepromline[i % 16] = ibuf[0]; eeprom[i] = ibuf[0]; } if ((i % 16) == 15) { deb_xfer("%02x: ", i - 15); debug_dump(eepromline, 16, deb_xfer); } } memcpy(mac, eeprom + 16, 6); return 0; }; static int su3000_streaming_ctrl(struct dvb_usb_adapter *adap, int onoff) { static u8 command_start[] = {0x00}; static u8 command_stop[] = {0x01}; struct i2c_msg msg = { .addr = SU3000_STREAM_CTRL, .flags = 0, .buf = onoff ? command_start : command_stop, .len = 1 }; i2c_transfer(&adap->dev->i2c_adap, &msg, 1); return 0; } static int su3000_power_ctrl(struct dvb_usb_device *d, int i) { struct dw2102_state *state = (struct dw2102_state *)d->priv; u8 obuf[] = {0xde, 0}; info("%s: %d, initialized %d", __func__, i, state->initialized); if (i && !state->initialized) { state->initialized = 1; /* reset board */ return dvb_usb_generic_rw(d, obuf, 2, NULL, 0, 0); } return 0; } static int su3000_read_mac_address(struct dvb_usb_device *d, u8 mac[6]) { int i; u8 obuf[] = { 0x1f, 0xf0 }; u8 ibuf[] = { 0 }; struct i2c_msg msg[] = { { .addr = 0x51, .flags = 0, .buf = obuf, .len = 2, }, { .addr = 0x51, .flags = I2C_M_RD, .buf = ibuf, .len = 1, } }; for (i = 0; i < 6; i++) { obuf[1] = 0xf0 + i; if (i2c_transfer(&d->i2c_adap, msg, 2) != 2) break; else mac[i] = ibuf[0]; } return 0; } static int su3000_identify_state(struct usb_device *udev, struct dvb_usb_device_properties *props, struct dvb_usb_device_description **desc, int *cold) { info("%s", __func__); *cold = 0; return 0; } static int dw210x_set_voltage(struct dvb_frontend *fe, enum fe_sec_voltage voltage) { static u8 command_13v[] = {0x00, 0x01}; static u8 command_18v[] = {0x01, 0x01}; static u8 command_off[] = {0x00, 0x00}; struct i2c_msg msg = { .addr = DW2102_VOLTAGE_CTRL, .flags = 0, .buf = command_off, .len = 2, }; struct dvb_usb_adapter *udev_adap = (struct dvb_usb_adapter *)(fe->dvb->priv); if (voltage == SEC_VOLTAGE_18) msg.buf = command_18v; else if (voltage == SEC_VOLTAGE_13) msg.buf = command_13v; i2c_transfer(&udev_adap->dev->i2c_adap, &msg, 1); return 0; } static int s660_set_voltage(struct dvb_frontend *fe, enum fe_sec_voltage voltage) { struct dvb_usb_adapter *d = (struct dvb_usb_adapter *)(fe->dvb->priv); struct dw2102_state *st = (struct dw2102_state *)d->dev->priv; dw210x_set_voltage(fe, voltage); if (st->old_set_voltage) st->old_set_voltage(fe, voltage); return 0; } static void dw210x_led_ctrl(struct dvb_frontend *fe, int offon) { static u8 led_off[] = { 0 }; static u8 led_on[] = { 1 }; struct i2c_msg msg = { .addr = DW2102_LED_CTRL, .flags = 0, .buf = led_off, .len = 1 }; struct dvb_usb_adapter *udev_adap = (struct dvb_usb_adapter *)(fe->dvb->priv); if (offon) msg.buf = led_on; i2c_transfer(&udev_adap->dev->i2c_adap, &msg, 1); } static int tt_s2_4600_read_status(struct dvb_frontend *fe, enum fe_status *status) { struct dvb_usb_adapter *d = (struct dvb_usb_adapter *)(fe->dvb->priv); struct dw2102_state *st = (struct dw2102_state *)d->dev->priv; int ret; ret = st->fe_read_status(fe, status); /* resync slave fifo when signal change from unlock to lock */ if ((*status & FE_HAS_LOCK) && (!st->last_lock)) su3000_streaming_ctrl(d, 1); st->last_lock = (*status & FE_HAS_LOCK) ? 1 : 0; return ret; } static struct stv0299_config sharp_z0194a_config = { .demod_address = 0x68, .inittab = sharp_z0194a_inittab, .mclk = 88000000UL, .invert = 1, .skip_reinit = 0, .lock_output = STV0299_LOCKOUTPUT_1, .volt13_op0_op1 = STV0299_VOLT13_OP1, .min_delay_ms = 100, .set_symbol_rate = sharp_z0194a_set_symbol_rate, }; static struct cx24116_config dw2104_config = { .demod_address = 0x55, .mpg_clk_pos_pol = 0x01, }; static struct si21xx_config serit_sp1511lhb_config = { .demod_address = 0x68, .min_delay_ms = 100, }; static struct tda10023_config dw3101_tda10023_config = { .demod_address = 0x0c, .invert = 1, }; static struct mt312_config zl313_config = { .demod_address = 0x0e, }; static struct ds3000_config dw2104_ds3000_config = { .demod_address = 0x68, }; static struct ts2020_config dw2104_ts2020_config = { .tuner_address = 0x60, .clk_out_div = 1, .frequency_div = 1060000, }; static struct ds3000_config s660_ds3000_config = { .demod_address = 0x68, .ci_mode = 1, .set_lock_led = dw210x_led_ctrl, }; static struct ts2020_config s660_ts2020_config = { .tuner_address = 0x60, .clk_out_div = 1, .frequency_div = 1146000, }; static struct stv0900_config dw2104a_stv0900_config = { .demod_address = 0x6a, .demod_mode = 0, .xtal = 27000000, .clkmode = 3,/* 0-CLKI, 2-XTALI, else AUTO */ .diseqc_mode = 2,/* 2/3 PWM */ .tun1_maddress = 0,/* 0x60 */ .tun1_adc = 0,/* 2 Vpp */ .path1_mode = 3, }; static struct stb6100_config dw2104a_stb6100_config = { .tuner_address = 0x60, .refclock = 27000000, }; static struct stv0900_config dw2104_stv0900_config = { .demod_address = 0x68, .demod_mode = 0, .xtal = 8000000, .clkmode = 3, .diseqc_mode = 2, .tun1_maddress = 0, .tun1_adc = 1,/* 1 Vpp */ .path1_mode = 3, }; static struct stv6110_config dw2104_stv6110_config = { .i2c_address = 0x60, .mclk = 16000000, .clk_div = 1, }; static struct stv0900_config prof_7500_stv0900_config = { .demod_address = 0x6a, .demod_mode = 0, .xtal = 27000000, .clkmode = 3,/* 0-CLKI, 2-XTALI, else AUTO */ .diseqc_mode = 2,/* 2/3 PWM */ .tun1_maddress = 0,/* 0x60 */ .tun1_adc = 0,/* 2 Vpp */ .path1_mode = 3, .tun1_type = 3, .set_lock_led = dw210x_led_ctrl, }; static struct ds3000_config su3000_ds3000_config = { .demod_address = 0x68, .ci_mode = 1, .set_lock_led = dw210x_led_ctrl, }; static struct cxd2820r_config cxd2820r_config = { .i2c_address = 0x6c, /* (0xd8 >> 1) */ .ts_mode = 0x38, .ts_clock_inv = 1, }; static struct tda18271_config tda18271_config = { .output_opt = TDA18271_OUTPUT_LT_OFF, .gate = TDA18271_GATE_DIGITAL, }; static u8 m88rs2000_inittab[] = { DEMOD_WRITE, 0x9a, 0x30, DEMOD_WRITE, 0x00, 0x01, WRITE_DELAY, 0x19, 0x00, DEMOD_WRITE, 0x00, 0x00, DEMOD_WRITE, 0x9a, 0xb0, DEMOD_WRITE, 0x81, 0xc1, DEMOD_WRITE, 0x81, 0x81, DEMOD_WRITE, 0x86, 0xc6, DEMOD_WRITE, 0x9a, 0x30, DEMOD_WRITE, 0xf0, 0x80, DEMOD_WRITE, 0xf1, 0xbf, DEMOD_WRITE, 0xb0, 0x45, DEMOD_WRITE, 0xb2, 0x01, DEMOD_WRITE, 0x9a, 0xb0, 0xff, 0xaa, 0xff }; static struct m88rs2000_config s421_m88rs2000_config = { .demod_addr = 0x68, .inittab = m88rs2000_inittab, }; static int dw2104_frontend_attach(struct dvb_usb_adapter *d) { struct dvb_tuner_ops *tuner_ops = NULL; if (demod_probe & 4) { d->fe_adap[0].fe = dvb_attach(stv0900_attach, &dw2104a_stv0900_config, &d->dev->i2c_adap, 0); if (d->fe_adap[0].fe != NULL) { if (dvb_attach(stb6100_attach, d->fe_adap[0].fe, &dw2104a_stb6100_config, &d->dev->i2c_adap)) { tuner_ops = &d->fe_adap[0].fe->ops.tuner_ops; tuner_ops->set_frequency = stb6100_set_freq; tuner_ops->get_frequency = stb6100_get_freq; tuner_ops->set_bandwidth = stb6100_set_bandw; tuner_ops->get_bandwidth = stb6100_get_bandw; d->fe_adap[0].fe->ops.set_voltage = dw210x_set_voltage; info("Attached STV0900+STB6100!"); return 0; } } } if (demod_probe & 2) { d->fe_adap[0].fe = dvb_attach(stv0900_attach, &dw2104_stv0900_config, &d->dev->i2c_adap, 0); if (d->fe_adap[0].fe != NULL) { if (dvb_attach(stv6110_attach, d->fe_adap[0].fe, &dw2104_stv6110_config, &d->dev->i2c_adap)) { d->fe_adap[0].fe->ops.set_voltage = dw210x_set_voltage; info("Attached STV0900+STV6110A!"); return 0; } } } if (demod_probe & 1) { d->fe_adap[0].fe = dvb_attach(cx24116_attach, &dw2104_config, &d->dev->i2c_adap); if (d->fe_adap[0].fe != NULL) { d->fe_adap[0].fe->ops.set_voltage = dw210x_set_voltage; info("Attached cx24116!"); return 0; } } d->fe_adap[0].fe = dvb_attach(ds3000_attach, &dw2104_ds3000_config, &d->dev->i2c_adap); if (d->fe_adap[0].fe != NULL) { dvb_attach(ts2020_attach, d->fe_adap[0].fe, &dw2104_ts2020_config, &d->dev->i2c_adap); d->fe_adap[0].fe->ops.set_voltage = dw210x_set_voltage; info("Attached DS3000!"); return 0; } return -EIO; } static struct dvb_usb_device_properties dw2102_properties; static struct dvb_usb_device_properties dw2104_properties; static struct dvb_usb_device_properties s6x0_properties; static int dw2102_frontend_attach(struct dvb_usb_adapter *d) { if (dw2102_properties.i2c_algo == &dw2102_serit_i2c_algo) { /*dw2102_properties.adapter->tuner_attach = NULL;*/ d->fe_adap[0].fe = dvb_attach(si21xx_attach, &serit_sp1511lhb_config, &d->dev->i2c_adap); if (d->fe_adap[0].fe != NULL) { d->fe_adap[0].fe->ops.set_voltage = dw210x_set_voltage; info("Attached si21xx!"); return 0; } } if (dw2102_properties.i2c_algo == &dw2102_earda_i2c_algo) { d->fe_adap[0].fe = dvb_attach(stv0288_attach, &earda_config, &d->dev->i2c_adap); if (d->fe_adap[0].fe != NULL) { if (dvb_attach(stb6000_attach, d->fe_adap[0].fe, 0x61, &d->dev->i2c_adap)) { d->fe_adap[0].fe->ops.set_voltage = dw210x_set_voltage; info("Attached stv0288!"); return 0; } } } if (dw2102_properties.i2c_algo == &dw2102_i2c_algo) { /*dw2102_properties.adapter->tuner_attach = dw2102_tuner_attach;*/ d->fe_adap[0].fe = dvb_attach(stv0299_attach, &sharp_z0194a_config, &d->dev->i2c_adap); if (d->fe_adap[0].fe != NULL) { d->fe_adap[0].fe->ops.set_voltage = dw210x_set_voltage; info("Attached stv0299!"); return 0; } } return -EIO; } static int dw3101_frontend_attach(struct dvb_usb_adapter *d) { d->fe_adap[0].fe = dvb_attach(tda10023_attach, &dw3101_tda10023_config, &d->dev->i2c_adap, 0x48); if (d->fe_adap[0].fe != NULL) { info("Attached tda10023!"); return 0; } return -EIO; } static int zl100313_frontend_attach(struct dvb_usb_adapter *d) { d->fe_adap[0].fe = dvb_attach(mt312_attach, &zl313_config, &d->dev->i2c_adap); if (d->fe_adap[0].fe != NULL) { if (dvb_attach(zl10039_attach, d->fe_adap[0].fe, 0x60, &d->dev->i2c_adap)) { d->fe_adap[0].fe->ops.set_voltage = dw210x_set_voltage; info("Attached zl100313+zl10039!"); return 0; } } return -EIO; } static int stv0288_frontend_attach(struct dvb_usb_adapter *d) { u8 obuf[] = {7, 1}; d->fe_adap[0].fe = dvb_attach(stv0288_attach, &earda_config, &d->dev->i2c_adap); if (d->fe_adap[0].fe == NULL) return -EIO; if (NULL == dvb_attach(stb6000_attach, d->fe_adap[0].fe, 0x61, &d->dev->i2c_adap)) return -EIO; d->fe_adap[0].fe->ops.set_voltage = dw210x_set_voltage; dw210x_op_rw(d->dev->udev, 0x8a, 0, 0, obuf, 2, DW210X_WRITE_MSG); info("Attached stv0288+stb6000!"); return 0; } static int ds3000_frontend_attach(struct dvb_usb_adapter *d) { struct dw2102_state *st = d->dev->priv; u8 obuf[] = {7, 1}; d->fe_adap[0].fe = dvb_attach(ds3000_attach, &s660_ds3000_config, &d->dev->i2c_adap); if (d->fe_adap[0].fe == NULL) return -EIO; dvb_attach(ts2020_attach, d->fe_adap[0].fe, &s660_ts2020_config, &d->dev->i2c_adap); st->old_set_voltage = d->fe_adap[0].fe->ops.set_voltage; d->fe_adap[0].fe->ops.set_voltage = s660_set_voltage; dw210x_op_rw(d->dev->udev, 0x8a, 0, 0, obuf, 2, DW210X_WRITE_MSG); info("Attached ds3000+ts2020!"); return 0; } static int prof_7500_frontend_attach(struct dvb_usb_adapter *d) { u8 obuf[] = {7, 1}; d->fe_adap[0].fe = dvb_attach(stv0900_attach, &prof_7500_stv0900_config, &d->dev->i2c_adap, 0); if (d->fe_adap[0].fe == NULL) return -EIO; d->fe_adap[0].fe->ops.set_voltage = dw210x_set_voltage; dw210x_op_rw(d->dev->udev, 0x8a, 0, 0, obuf, 2, DW210X_WRITE_MSG); info("Attached STV0900+STB6100A!"); return 0; } static int su3000_frontend_attach(struct dvb_usb_adapter *d) { u8 obuf[3] = { 0xe, 0x80, 0 }; u8 ibuf[] = { 0 }; if (dvb_usb_generic_rw(d->dev, obuf, 3, ibuf, 1, 0) < 0) err("command 0x0e transfer failed."); obuf[0] = 0xe; obuf[1] = 0x02; obuf[2] = 1; if (dvb_usb_generic_rw(d->dev, obuf, 3, ibuf, 1, 0) < 0) err("command 0x0e transfer failed."); msleep(300); obuf[0] = 0xe; obuf[1] = 0x83; obuf[2] = 0; if (dvb_usb_generic_rw(d->dev, obuf, 3, ibuf, 1, 0) < 0) err("command 0x0e transfer failed."); obuf[0] = 0xe; obuf[1] = 0x83; obuf[2] = 1; if (dvb_usb_generic_rw(d->dev, obuf, 3, ibuf, 1, 0) < 0) err("command 0x0e transfer failed."); obuf[0] = 0x51; if (dvb_usb_generic_rw(d->dev, obuf, 1, ibuf, 1, 0) < 0) err("command 0x51 transfer failed."); d->fe_adap[0].fe = dvb_attach(ds3000_attach, &su3000_ds3000_config, &d->dev->i2c_adap); if (d->fe_adap[0].fe == NULL) return -EIO; if (dvb_attach(ts2020_attach, d->fe_adap[0].fe, &dw2104_ts2020_config, &d->dev->i2c_adap)) { info("Attached DS3000/TS2020!"); return 0; } info("Failed to attach DS3000/TS2020!"); return -EIO; } static int t220_frontend_attach(struct dvb_usb_adapter *d) { u8 obuf[3] = { 0xe, 0x87, 0 }; u8 ibuf[] = { 0 }; if (dvb_usb_generic_rw(d->dev, obuf, 3, ibuf, 1, 0) < 0) err("command 0x0e transfer failed."); obuf[0] = 0xe; obuf[1] = 0x86; obuf[2] = 1; if (dvb_usb_generic_rw(d->dev, obuf, 3, ibuf, 1, 0) < 0) err("command 0x0e transfer failed."); obuf[0] = 0xe; obuf[1] = 0x80; obuf[2] = 0; if (dvb_usb_generic_rw(d->dev, obuf, 3, ibuf, 1, 0) < 0) err("command 0x0e transfer failed."); msleep(50); obuf[0] = 0xe; obuf[1] = 0x80; obuf[2] = 1; if (dvb_usb_generic_rw(d->dev, obuf, 3, ibuf, 1, 0) < 0) err("command 0x0e transfer failed."); obuf[0] = 0x51; if (dvb_usb_generic_rw(d->dev, obuf, 1, ibuf, 1, 0) < 0) err("command 0x51 transfer failed."); d->fe_adap[0].fe = dvb_attach(cxd2820r_attach, &cxd2820r_config, &d->dev->i2c_adap, NULL); if (d->fe_adap[0].fe != NULL) { if (dvb_attach(tda18271_attach, d->fe_adap[0].fe, 0x60, &d->dev->i2c_adap, &tda18271_config)) { info("Attached TDA18271HD/CXD2820R!"); return 0; } } info("Failed to attach TDA18271HD/CXD2820R!"); return -EIO; } static int m88rs2000_frontend_attach(struct dvb_usb_adapter *d) { u8 obuf[] = { 0x51 }; u8 ibuf[] = { 0 }; if (dvb_usb_generic_rw(d->dev, obuf, 1, ibuf, 1, 0) < 0) err("command 0x51 transfer failed."); d->fe_adap[0].fe = dvb_attach(m88rs2000_attach, &s421_m88rs2000_config, &d->dev->i2c_adap); if (d->fe_adap[0].fe == NULL) return -EIO; if (dvb_attach(ts2020_attach, d->fe_adap[0].fe, &dw2104_ts2020_config, &d->dev->i2c_adap)) { info("Attached RS2000/TS2020!"); return 0; } info("Failed to attach RS2000/TS2020!"); return -EIO; } static int tt_s2_4600_frontend_attach(struct dvb_usb_adapter *adap) { struct dvb_usb_device *d = adap->dev; struct dw2102_state *state = d->priv; u8 obuf[3] = { 0xe, 0x80, 0 }; u8 ibuf[] = { 0 }; struct i2c_adapter *i2c_adapter; struct i2c_client *client; struct i2c_board_info board_info; struct m88ds3103_platform_data m88ds3103_pdata = {}; struct ts2020_config ts2020_config = {}; if (dvb_usb_generic_rw(d, obuf, 3, ibuf, 1, 0) < 0) err("command 0x0e transfer failed."); obuf[0] = 0xe; obuf[1] = 0x02; obuf[2] = 1; if (dvb_usb_generic_rw(d, obuf, 3, ibuf, 1, 0) < 0) err("command 0x0e transfer failed."); msleep(300); obuf[0] = 0xe; obuf[1] = 0x83; obuf[2] = 0; if (dvb_usb_generic_rw(d, obuf, 3, ibuf, 1, 0) < 0) err("command 0x0e transfer failed."); obuf[0] = 0xe; obuf[1] = 0x83; obuf[2] = 1; if (dvb_usb_generic_rw(d, obuf, 3, ibuf, 1, 0) < 0) err("command 0x0e transfer failed."); obuf[0] = 0x51; if (dvb_usb_generic_rw(d, obuf, 1, ibuf, 1, 0) < 0) err("command 0x51 transfer failed."); /* attach demod */ m88ds3103_pdata.clk = 27000000; m88ds3103_pdata.i2c_wr_max = 33; m88ds3103_pdata.ts_mode = M88DS3103_TS_CI; m88ds3103_pdata.ts_clk = 16000; m88ds3103_pdata.ts_clk_pol = 0; m88ds3103_pdata.spec_inv = 0; m88ds3103_pdata.agc = 0x99; m88ds3103_pdata.agc_inv = 0; m88ds3103_pdata.clk_out = M88DS3103_CLOCK_OUT_ENABLED; m88ds3103_pdata.envelope_mode = 0; m88ds3103_pdata.lnb_hv_pol = 1; m88ds3103_pdata.lnb_en_pol = 0; memset(&board_info, 0, sizeof(board_info)); strlcpy(board_info.type, "m88ds3103", I2C_NAME_SIZE); board_info.addr = 0x68; board_info.platform_data = &m88ds3103_pdata; request_module("m88ds3103"); client = i2c_new_device(&d->i2c_adap, &board_info); if (client == NULL || client->dev.driver == NULL) return -ENODEV; if (!try_module_get(client->dev.driver->owner)) { i2c_unregister_device(client); return -ENODEV; } adap->fe_adap[0].fe = m88ds3103_pdata.get_dvb_frontend(client); i2c_adapter = m88ds3103_pdata.get_i2c_adapter(client); state->i2c_client_demod = client; /* attach tuner */ ts2020_config.fe = adap->fe_adap[0].fe; memset(&board_info, 0, sizeof(board_info)); strlcpy(board_info.type, "ts2022", I2C_NAME_SIZE); board_info.addr = 0x60; board_info.platform_data = &ts2020_config; request_module("ts2020"); client = i2c_new_device(i2c_adapter, &board_info); if (client == NULL || client->dev.driver == NULL) { dvb_frontend_detach(adap->fe_adap[0].fe); return -ENODEV; } if (!try_module_get(client->dev.driver->owner)) { i2c_unregister_device(client); dvb_frontend_detach(adap->fe_adap[0].fe); return -ENODEV; } /* delegate signal strength measurement to tuner */ adap->fe_adap[0].fe->ops.read_signal_strength = adap->fe_adap[0].fe->ops.tuner_ops.get_rf_strength; state->i2c_client_tuner = client; /* hook fe: need to resync the slave fifo when signal locks */ state->fe_read_status = adap->fe_adap[0].fe->ops.read_status; adap->fe_adap[0].fe->ops.read_status = tt_s2_4600_read_status; state->last_lock = 0; return 0; } static int dw2102_tuner_attach(struct dvb_usb_adapter *adap) { dvb_attach(dvb_pll_attach, adap->fe_adap[0].fe, 0x60, &adap->dev->i2c_adap, DVB_PLL_OPERA1); return 0; } static int dw3101_tuner_attach(struct dvb_usb_adapter *adap) { dvb_attach(dvb_pll_attach, adap->fe_adap[0].fe, 0x60, &adap->dev->i2c_adap, DVB_PLL_TUA6034); return 0; } static int dw2102_rc_query(struct dvb_usb_device *d) { u8 key[2]; struct i2c_msg msg = { .addr = DW2102_RC_QUERY, .flags = I2C_M_RD, .buf = key, .len = 2 }; if (d->props.i2c_algo->master_xfer(&d->i2c_adap, &msg, 1) == 1) { if (msg.buf[0] != 0xff) { deb_rc("%s: rc code: %x, %x\n", __func__, key[0], key[1]); rc_keydown(d->rc_dev, RC_TYPE_UNKNOWN, key[0], 0); } } return 0; } static int prof_rc_query(struct dvb_usb_device *d) { u8 key[2]; struct i2c_msg msg = { .addr = DW2102_RC_QUERY, .flags = I2C_M_RD, .buf = key, .len = 2 }; if (d->props.i2c_algo->master_xfer(&d->i2c_adap, &msg, 1) == 1) { if (msg.buf[0] != 0xff) { deb_rc("%s: rc code: %x, %x\n", __func__, key[0], key[1]); rc_keydown(d->rc_dev, RC_TYPE_UNKNOWN, key[0]^0xff, 0); } } return 0; } static int su3000_rc_query(struct dvb_usb_device *d) { u8 key[2]; struct i2c_msg msg = { .addr = DW2102_RC_QUERY, .flags = I2C_M_RD, .buf = key, .len = 2 }; if (d->props.i2c_algo->master_xfer(&d->i2c_adap, &msg, 1) == 1) { if (msg.buf[0] != 0xff) { deb_rc("%s: rc code: %x, %x\n", __func__, key[0], key[1]); rc_keydown(d->rc_dev, RC_TYPE_RC5, RC_SCANCODE_RC5(key[1], key[0]), 0); } } return 0; } enum dw2102_table_entry { CYPRESS_DW2102, CYPRESS_DW2101, CYPRESS_DW2104, TEVII_S650, TERRATEC_CINERGY_S, CYPRESS_DW3101, TEVII_S630, PROF_1100, TEVII_S660, PROF_7500, GENIATECH_SU3000, TERRATEC_CINERGY_S2, TEVII_S480_1, TEVII_S480_2, X3M_SPC1400HD, TEVII_S421, TEVII_S632, TERRATEC_CINERGY_S2_R2, TERRATEC_CINERGY_S2_R3, TERRATEC_CINERGY_S2_R4, GOTVIEW_SAT_HD, GENIATECH_T220, TECHNOTREND_S2_4600, TEVII_S482_1, TEVII_S482_2, TERRATEC_CINERGY_S2_BOX, TEVII_S662 }; static struct usb_device_id dw2102_table[] = { [CYPRESS_DW2102] = {USB_DEVICE(USB_VID_CYPRESS, USB_PID_DW2102)}, [CYPRESS_DW2101] = {USB_DEVICE(USB_VID_CYPRESS, 0x2101)}, [CYPRESS_DW2104] = {USB_DEVICE(USB_VID_CYPRESS, USB_PID_DW2104)}, [TEVII_S650] = {USB_DEVICE(0x9022, USB_PID_TEVII_S650)}, [TERRATEC_CINERGY_S] = {USB_DEVICE(USB_VID_TERRATEC, USB_PID_TERRATEC_CINERGY_S)}, [CYPRESS_DW3101] = {USB_DEVICE(USB_VID_CYPRESS, USB_PID_DW3101)}, [TEVII_S630] = {USB_DEVICE(0x9022, USB_PID_TEVII_S630)}, [PROF_1100] = {USB_DEVICE(0x3011, USB_PID_PROF_1100)}, [TEVII_S660] = {USB_DEVICE(0x9022, USB_PID_TEVII_S660)}, [PROF_7500] = {USB_DEVICE(0x3034, 0x7500)}, [GENIATECH_SU3000] = {USB_DEVICE(0x1f4d, 0x3000)}, [TERRATEC_CINERGY_S2] = {USB_DEVICE(USB_VID_TERRATEC, USB_PID_TERRATEC_CINERGY_S2_R1)}, [TEVII_S480_1] = {USB_DEVICE(0x9022, USB_PID_TEVII_S480_1)}, [TEVII_S480_2] = {USB_DEVICE(0x9022, USB_PID_TEVII_S480_2)}, [X3M_SPC1400HD] = {USB_DEVICE(0x1f4d, 0x3100)}, [TEVII_S421] = {USB_DEVICE(0x9022, USB_PID_TEVII_S421)}, [TEVII_S632] = {USB_DEVICE(0x9022, USB_PID_TEVII_S632)}, [TERRATEC_CINERGY_S2_R2] = {USB_DEVICE(USB_VID_TERRATEC, USB_PID_TERRATEC_CINERGY_S2_R2)}, [TERRATEC_CINERGY_S2_R3] = {USB_DEVICE(USB_VID_TERRATEC, USB_PID_TERRATEC_CINERGY_S2_R3)}, [TERRATEC_CINERGY_S2_R4] = {USB_DEVICE(USB_VID_TERRATEC, USB_PID_TERRATEC_CINERGY_S2_R4)}, [GOTVIEW_SAT_HD] = {USB_DEVICE(0x1FE1, USB_PID_GOTVIEW_SAT_HD)}, [GENIATECH_T220] = {USB_DEVICE(0x1f4d, 0xD220)}, [TECHNOTREND_S2_4600] = {USB_DEVICE(USB_VID_TECHNOTREND, USB_PID_TECHNOTREND_CONNECT_S2_4600)}, [TEVII_S482_1] = {USB_DEVICE(0x9022, 0xd483)}, [TEVII_S482_2] = {USB_DEVICE(0x9022, 0xd484)}, [TERRATEC_CINERGY_S2_BOX] = {USB_DEVICE(USB_VID_TERRATEC, 0x0105)}, [TEVII_S662] = {USB_DEVICE(0x9022, USB_PID_TEVII_S662)}, { } }; MODULE_DEVICE_TABLE(usb, dw2102_table); static int dw2102_load_firmware(struct usb_device *dev, const struct firmware *frmwr) { u8 *b, *p; int ret = 0, i; u8 reset; u8 reset16[] = {0, 0, 0, 0, 0, 0, 0}; const struct firmware *fw; switch (le16_to_cpu(dev->descriptor.idProduct)) { case 0x2101: ret = request_firmware(&fw, DW2101_FIRMWARE, &dev->dev); if (ret != 0) { err(err_str, DW2101_FIRMWARE); return ret; } break; default: fw = frmwr; break; } info("start downloading DW210X firmware"); p = kmalloc(fw->size, GFP_KERNEL); reset = 1; /*stop the CPU*/ dw210x_op_rw(dev, 0xa0, 0x7f92, 0, &reset, 1, DW210X_WRITE_MSG); dw210x_op_rw(dev, 0xa0, 0xe600, 0, &reset, 1, DW210X_WRITE_MSG); if (p != NULL) { memcpy(p, fw->data, fw->size); for (i = 0; i < fw->size; i += 0x40) { b = (u8 *) p + i; if (dw210x_op_rw(dev, 0xa0, i, 0, b , 0x40, DW210X_WRITE_MSG) != 0x40) { err("error while transferring firmware"); ret = -EINVAL; break; } } /* restart the CPU */ reset = 0; if (ret || dw210x_op_rw(dev, 0xa0, 0x7f92, 0, &reset, 1, DW210X_WRITE_MSG) != 1) { err("could not restart the USB controller CPU."); ret = -EINVAL; } if (ret || dw210x_op_rw(dev, 0xa0, 0xe600, 0, &reset, 1, DW210X_WRITE_MSG) != 1) { err("could not restart the USB controller CPU."); ret = -EINVAL; } /* init registers */ switch (le16_to_cpu(dev->descriptor.idProduct)) { case USB_PID_TEVII_S650: dw2104_properties.rc.core.rc_codes = RC_MAP_TEVII_NEC; case USB_PID_DW2104: reset = 1; dw210x_op_rw(dev, 0xc4, 0x0000, 0, &reset, 1, DW210X_WRITE_MSG); /* break omitted intentionally */ case USB_PID_DW3101: reset = 0; dw210x_op_rw(dev, 0xbf, 0x0040, 0, &reset, 0, DW210X_WRITE_MSG); break; case USB_PID_TERRATEC_CINERGY_S: case USB_PID_DW2102: dw210x_op_rw(dev, 0xbf, 0x0040, 0, &reset, 0, DW210X_WRITE_MSG); dw210x_op_rw(dev, 0xb9, 0x0000, 0, &reset16[0], 2, DW210X_READ_MSG); /* check STV0299 frontend */ dw210x_op_rw(dev, 0xb5, 0, 0, &reset16[0], 2, DW210X_READ_MSG); if ((reset16[0] == 0xa1) || (reset16[0] == 0x80)) { dw2102_properties.i2c_algo = &dw2102_i2c_algo; dw2102_properties.adapter->fe[0].tuner_attach = &dw2102_tuner_attach; break; } else { /* check STV0288 frontend */ reset16[0] = 0xd0; reset16[1] = 1; reset16[2] = 0; dw210x_op_rw(dev, 0xc2, 0, 0, &reset16[0], 3, DW210X_WRITE_MSG); dw210x_op_rw(dev, 0xc3, 0xd1, 0, &reset16[0], 3, DW210X_READ_MSG); if (reset16[2] == 0x11) { dw2102_properties.i2c_algo = &dw2102_earda_i2c_algo; break; } } case 0x2101: dw210x_op_rw(dev, 0xbc, 0x0030, 0, &reset16[0], 2, DW210X_READ_MSG); dw210x_op_rw(dev, 0xba, 0x0000, 0, &reset16[0], 7, DW210X_READ_MSG); dw210x_op_rw(dev, 0xba, 0x0000, 0, &reset16[0], 7, DW210X_READ_MSG); dw210x_op_rw(dev, 0xb9, 0x0000, 0, &reset16[0], 2, DW210X_READ_MSG); break; } msleep(100); kfree(p); } if (le16_to_cpu(dev->descriptor.idProduct) == 0x2101) release_firmware(fw); return ret; } static struct dvb_usb_device_properties dw2102_properties = { .caps = DVB_USB_IS_AN_I2C_ADAPTER, .usb_ctrl = DEVICE_SPECIFIC, .firmware = DW2102_FIRMWARE, .no_reconnect = 1, .i2c_algo = &dw2102_serit_i2c_algo, .rc.core = { .rc_interval = 150, .rc_codes = RC_MAP_DM1105_NEC, .module_name = "dw2102", .allowed_protos = RC_BIT_NEC, .rc_query = dw2102_rc_query, }, .generic_bulk_ctrl_endpoint = 0x81, /* parameter for the MPEG2-data transfer */ .num_adapters = 1, .download_firmware = dw2102_load_firmware, .read_mac_address = dw210x_read_mac_address, .adapter = { { .num_frontends = 1, .fe = {{ .frontend_attach = dw2102_frontend_attach, .stream = { .type = USB_BULK, .count = 8, .endpoint = 0x82, .u = { .bulk = { .buffersize = 4096, } } }, }}, } }, .num_device_descs = 3, .devices = { {"DVBWorld DVB-S 2102 USB2.0", {&dw2102_table[CYPRESS_DW2102], NULL}, {NULL}, }, {"DVBWorld DVB-S 2101 USB2.0", {&dw2102_table[CYPRESS_DW2101], NULL}, {NULL}, }, {"TerraTec Cinergy S USB", {&dw2102_table[TERRATEC_CINERGY_S], NULL}, {NULL}, }, } }; static struct dvb_usb_device_properties dw2104_properties = { .caps = DVB_USB_IS_AN_I2C_ADAPTER, .usb_ctrl = DEVICE_SPECIFIC, .firmware = DW2104_FIRMWARE, .no_reconnect = 1, .i2c_algo = &dw2104_i2c_algo, .rc.core = { .rc_interval = 150, .rc_codes = RC_MAP_DM1105_NEC, .module_name = "dw2102", .allowed_protos = RC_BIT_NEC, .rc_query = dw2102_rc_query, }, .generic_bulk_ctrl_endpoint = 0x81, /* parameter for the MPEG2-data transfer */ .num_adapters = 1, .download_firmware = dw2102_load_firmware, .read_mac_address = dw210x_read_mac_address, .adapter = { { .num_frontends = 1, .fe = {{ .frontend_attach = dw2104_frontend_attach, .stream = { .type = USB_BULK, .count = 8, .endpoint = 0x82, .u = { .bulk = { .buffersize = 4096, } } }, }}, } }, .num_device_descs = 2, .devices = { { "DVBWorld DW2104 USB2.0", {&dw2102_table[CYPRESS_DW2104], NULL}, {NULL}, }, { "TeVii S650 USB2.0", {&dw2102_table[TEVII_S650], NULL}, {NULL}, }, } }; static struct dvb_usb_device_properties dw3101_properties = { .caps = DVB_USB_IS_AN_I2C_ADAPTER, .usb_ctrl = DEVICE_SPECIFIC, .firmware = DW3101_FIRMWARE, .no_reconnect = 1, .i2c_algo = &dw3101_i2c_algo, .rc.core = { .rc_interval = 150, .rc_codes = RC_MAP_DM1105_NEC, .module_name = "dw2102", .allowed_protos = RC_BIT_NEC, .rc_query = dw2102_rc_query, }, .generic_bulk_ctrl_endpoint = 0x81, /* parameter for the MPEG2-data transfer */ .num_adapters = 1, .download_firmware = dw2102_load_firmware, .read_mac_address = dw210x_read_mac_address, .adapter = { { .num_frontends = 1, .fe = {{ .frontend_attach = dw3101_frontend_attach, .tuner_attach = dw3101_tuner_attach, .stream = { .type = USB_BULK, .count = 8, .endpoint = 0x82, .u = { .bulk = { .buffersize = 4096, } } }, }}, } }, .num_device_descs = 1, .devices = { { "DVBWorld DVB-C 3101 USB2.0", {&dw2102_table[CYPRESS_DW3101], NULL}, {NULL}, }, } }; static struct dvb_usb_device_properties s6x0_properties = { .caps = DVB_USB_IS_AN_I2C_ADAPTER, .usb_ctrl = DEVICE_SPECIFIC, .size_of_priv = sizeof(struct dw2102_state), .firmware = S630_FIRMWARE, .no_reconnect = 1, .i2c_algo = &s6x0_i2c_algo, .rc.core = { .rc_interval = 150, .rc_codes = RC_MAP_TEVII_NEC, .module_name = "dw2102", .allowed_protos = RC_BIT_NEC, .rc_query = dw2102_rc_query, }, .generic_bulk_ctrl_endpoint = 0x81, .num_adapters = 1, .download_firmware = dw2102_load_firmware, .read_mac_address = s6x0_read_mac_address, .adapter = { { .num_frontends = 1, .fe = {{ .frontend_attach = zl100313_frontend_attach, .stream = { .type = USB_BULK, .count = 8, .endpoint = 0x82, .u = { .bulk = { .buffersize = 4096, } } }, }}, } }, .num_device_descs = 1, .devices = { {"TeVii S630 USB", {&dw2102_table[TEVII_S630], NULL}, {NULL}, }, } }; static struct dvb_usb_device_properties *p1100; static struct dvb_usb_device_description d1100 = { "Prof 1100 USB ", {&dw2102_table[PROF_1100], NULL}, {NULL}, }; static struct dvb_usb_device_properties *s660; static struct dvb_usb_device_description d660 = { "TeVii S660 USB", {&dw2102_table[TEVII_S660], NULL}, {NULL}, }; static struct dvb_usb_device_description d480_1 = { "TeVii S480.1 USB", {&dw2102_table[TEVII_S480_1], NULL}, {NULL}, }; static struct dvb_usb_device_description d480_2 = { "TeVii S480.2 USB", {&dw2102_table[TEVII_S480_2], NULL}, {NULL}, }; static struct dvb_usb_device_properties *p7500; static struct dvb_usb_device_description d7500 = { "Prof 7500 USB DVB-S2", {&dw2102_table[PROF_7500], NULL}, {NULL}, }; static struct dvb_usb_device_properties *s421; static struct dvb_usb_device_description d421 = { "TeVii S421 PCI", {&dw2102_table[TEVII_S421], NULL}, {NULL}, }; static struct dvb_usb_device_description d632 = { "TeVii S632 USB", {&dw2102_table[TEVII_S632], NULL}, {NULL}, }; static struct dvb_usb_device_properties su3000_properties = { .caps = DVB_USB_IS_AN_I2C_ADAPTER, .usb_ctrl = DEVICE_SPECIFIC, .size_of_priv = sizeof(struct dw2102_state), .power_ctrl = su3000_power_ctrl, .num_adapters = 1, .identify_state = su3000_identify_state, .i2c_algo = &su3000_i2c_algo, .rc.core = { .rc_interval = 150, .rc_codes = RC_MAP_SU3000, .module_name = "dw2102", .allowed_protos = RC_BIT_RC5, .rc_query = su3000_rc_query, }, .read_mac_address = su3000_read_mac_address, .generic_bulk_ctrl_endpoint = 0x01, .adapter = { { .num_frontends = 1, .fe = {{ .streaming_ctrl = su3000_streaming_ctrl, .frontend_attach = su3000_frontend_attach, .stream = { .type = USB_BULK, .count = 8, .endpoint = 0x82, .u = { .bulk = { .buffersize = 4096, } } } }}, } }, .num_device_descs = 6, .devices = { { "SU3000HD DVB-S USB2.0", { &dw2102_table[GENIATECH_SU3000], NULL }, { NULL }, }, { "Terratec Cinergy S2 USB HD", { &dw2102_table[TERRATEC_CINERGY_S2], NULL }, { NULL }, }, { "X3M TV SPC1400HD PCI", { &dw2102_table[X3M_SPC1400HD], NULL }, { NULL }, }, { "Terratec Cinergy S2 USB HD Rev.2", { &dw2102_table[TERRATEC_CINERGY_S2_R2], NULL }, { NULL }, }, { "Terratec Cinergy S2 USB HD Rev.3", { &dw2102_table[TERRATEC_CINERGY_S2_R3], NULL }, { NULL }, }, { "GOTVIEW Satellite HD", { &dw2102_table[GOTVIEW_SAT_HD], NULL }, { NULL }, }, } }; static struct dvb_usb_device_properties t220_properties = { .caps = DVB_USB_IS_AN_I2C_ADAPTER, .usb_ctrl = DEVICE_SPECIFIC, .size_of_priv = sizeof(struct dw2102_state), .power_ctrl = su3000_power_ctrl, .num_adapters = 1, .identify_state = su3000_identify_state, .i2c_algo = &su3000_i2c_algo, .rc.core = { .rc_interval = 150, .rc_codes = RC_MAP_SU3000, .module_name = "dw2102", .allowed_protos = RC_BIT_RC5, .rc_query = su3000_rc_query, }, .read_mac_address = su3000_read_mac_address, .generic_bulk_ctrl_endpoint = 0x01, .adapter = { { .num_frontends = 1, .fe = { { .streaming_ctrl = su3000_streaming_ctrl, .frontend_attach = t220_frontend_attach, .stream = { .type = USB_BULK, .count = 8, .endpoint = 0x82, .u = { .bulk = { .buffersize = 4096, } } } } }, } }, .num_device_descs = 1, .devices = { { "Geniatech T220 DVB-T/T2 USB2.0", { &dw2102_table[GENIATECH_T220], NULL }, { NULL }, }, } }; static struct dvb_usb_device_properties tt_s2_4600_properties = { .caps = DVB_USB_IS_AN_I2C_ADAPTER, .usb_ctrl = DEVICE_SPECIFIC, .size_of_priv = sizeof(struct dw2102_state), .power_ctrl = su3000_power_ctrl, .num_adapters = 1, .identify_state = su3000_identify_state, .i2c_algo = &su3000_i2c_algo, .rc.core = { .rc_interval = 250, .rc_codes = RC_MAP_TT_1500, .module_name = "dw2102", .allowed_protos = RC_BIT_RC5, .rc_query = su3000_rc_query, }, .read_mac_address = su3000_read_mac_address, .generic_bulk_ctrl_endpoint = 0x01, .adapter = { { .num_frontends = 1, .fe = {{ .streaming_ctrl = su3000_streaming_ctrl, .frontend_attach = tt_s2_4600_frontend_attach, .stream = { .type = USB_BULK, .count = 8, .endpoint = 0x82, .u = { .bulk = { .buffersize = 4096, } } } } }, } }, .num_device_descs = 5, .devices = { { "TechnoTrend TT-connect S2-4600", { &dw2102_table[TECHNOTREND_S2_4600], NULL }, { NULL }, }, { "TeVii S482 (tuner 1)", { &dw2102_table[TEVII_S482_1], NULL }, { NULL }, }, { "TeVii S482 (tuner 2)", { &dw2102_table[TEVII_S482_2], NULL }, { NULL }, }, { "Terratec Cinergy S2 USB BOX", { &dw2102_table[TERRATEC_CINERGY_S2_BOX], NULL }, { NULL }, }, { "TeVii S662", { &dw2102_table[TEVII_S662], NULL }, { NULL }, }, } }; static int dw2102_probe(struct usb_interface *intf, const struct usb_device_id *id) { p1100 = kmemdup(&s6x0_properties, sizeof(struct dvb_usb_device_properties), GFP_KERNEL); if (!p1100) return -ENOMEM; /* copy default structure */ /* fill only different fields */ p1100->firmware = P1100_FIRMWARE; p1100->devices[0] = d1100; p1100->rc.core.rc_query = prof_rc_query; p1100->rc.core.rc_codes = RC_MAP_TBS_NEC; p1100->adapter->fe[0].frontend_attach = stv0288_frontend_attach; s660 = kmemdup(&s6x0_properties, sizeof(struct dvb_usb_device_properties), GFP_KERNEL); if (!s660) { kfree(p1100); return -ENOMEM; } s660->firmware = S660_FIRMWARE; s660->num_device_descs = 3; s660->devices[0] = d660; s660->devices[1] = d480_1; s660->devices[2] = d480_2; s660->adapter->fe[0].frontend_attach = ds3000_frontend_attach; p7500 = kmemdup(&s6x0_properties, sizeof(struct dvb_usb_device_properties), GFP_KERNEL); if (!p7500) { kfree(p1100); kfree(s660); return -ENOMEM; } p7500->firmware = P7500_FIRMWARE; p7500->devices[0] = d7500; p7500->rc.core.rc_query = prof_rc_query; p7500->rc.core.rc_codes = RC_MAP_TBS_NEC; p7500->adapter->fe[0].frontend_attach = prof_7500_frontend_attach; s421 = kmemdup(&su3000_properties, sizeof(struct dvb_usb_device_properties), GFP_KERNEL); if (!s421) { kfree(p1100); kfree(s660); kfree(p7500); return -ENOMEM; } s421->num_device_descs = 2; s421->devices[0] = d421; s421->devices[1] = d632; s421->adapter->fe[0].frontend_attach = m88rs2000_frontend_attach; if (0 == dvb_usb_device_init(intf, &dw2102_properties, THIS_MODULE, NULL, adapter_nr) || 0 == dvb_usb_device_init(intf, &dw2104_properties, THIS_MODULE, NULL, adapter_nr) || 0 == dvb_usb_device_init(intf, &dw3101_properties, THIS_MODULE, NULL, adapter_nr) || 0 == dvb_usb_device_init(intf, &s6x0_properties, THIS_MODULE, NULL, adapter_nr) || 0 == dvb_usb_device_init(intf, p1100, THIS_MODULE, NULL, adapter_nr) || 0 == dvb_usb_device_init(intf, s660, THIS_MODULE, NULL, adapter_nr) || 0 == dvb_usb_device_init(intf, p7500, THIS_MODULE, NULL, adapter_nr) || 0 == dvb_usb_device_init(intf, s421, THIS_MODULE, NULL, adapter_nr) || 0 == dvb_usb_device_init(intf, &su3000_properties, THIS_MODULE, NULL, adapter_nr) || 0 == dvb_usb_device_init(intf, &t220_properties, THIS_MODULE, NULL, adapter_nr) || 0 == dvb_usb_device_init(intf, &tt_s2_4600_properties, THIS_MODULE, NULL, adapter_nr)) return 0; return -ENODEV; } static void dw2102_disconnect(struct usb_interface *intf) { struct dvb_usb_device *d = usb_get_intfdata(intf); struct dw2102_state *st = (struct dw2102_state *)d->priv; struct i2c_client *client; /* remove I2C client for tuner */ client = st->i2c_client_tuner; if (client) { module_put(client->dev.driver->owner); i2c_unregister_device(client); } /* remove I2C client for demodulator */ client = st->i2c_client_demod; if (client) { module_put(client->dev.driver->owner); i2c_unregister_device(client); } dvb_usb_device_exit(intf); } static struct usb_driver dw2102_driver = { .name = "dw2102", .probe = dw2102_probe, .disconnect = dw2102_disconnect, .id_table = dw2102_table, }; module_usb_driver(dw2102_driver); MODULE_AUTHOR("Igor M. Liplianin (c) liplianin@me.by"); MODULE_DESCRIPTION("Driver for DVBWorld DVB-S 2101, 2102, DVB-S2 2104, DVB-C 3101 USB2.0, TeVii S421, S480, S482, S600, S630, S632, S650, TeVii S660, S662, Prof 1100, 7500 USB2.0, Geniatech SU3000, T220, TechnoTrend S2-4600, Terratec Cinergy S2 devices"); MODULE_VERSION("0.1"); MODULE_LICENSE("GPL"); MODULE_FIRMWARE(DW2101_FIRMWARE); MODULE_FIRMWARE(DW2102_FIRMWARE); MODULE_FIRMWARE(DW2104_FIRMWARE); MODULE_FIRMWARE(DW3101_FIRMWARE); MODULE_FIRMWARE(S630_FIRMWARE); MODULE_FIRMWARE(S660_FIRMWARE); MODULE_FIRMWARE(P1100_FIRMWARE); MODULE_FIRMWARE(P7500_FIRMWARE);
./CrossVul/dataset_final_sorted/CWE-119/c/bad_3311_0
crossvul-cpp_data_bad_3337_0
/*- * Copyright (c) 2006 Verdens Gang AS * Copyright (c) 2006-2015 Varnish Software AS * All rights reserved. * * Author: Poul-Henning Kamp <phk@phk.freebsd.dk> * * 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 AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "config.h" #include "cache.h" #include "cache_director.h" #include "cache_filter.h" #include "hash/hash_slinger.h" #include "storage/storage.h" #include "vcl.h" #include "vtim.h" /*-------------------------------------------------------------------- * Allocate an object, with fall-back to Transient. * XXX: This somewhat overlaps the stuff in stevedore.c * XXX: Should this be merged over there ? */ static int vbf_allocobj(struct busyobj *bo, unsigned l) { struct objcore *oc; const struct stevedore *stv; double lifetime; CHECK_OBJ_NOTNULL(bo, BUSYOBJ_MAGIC); oc = bo->fetch_objcore; CHECK_OBJ_NOTNULL(oc, OBJCORE_MAGIC); lifetime = oc->ttl + oc->grace + oc->keep; if (bo->uncacheable || lifetime < cache_param->shortlived) stv = stv_transient; else stv = bo->storage; bo->storage = NULL; bo->storage_hint = NULL; if (stv == NULL) return (0); if (STV_NewObject(bo->wrk, bo->fetch_objcore, stv, l)) return (1); if (stv == stv_transient) return (0); /* * Try to salvage the transaction by allocating a shortlived object * on Transient storage. */ if (oc->ttl > cache_param->shortlived) oc->ttl = cache_param->shortlived; oc->grace = 0.0; oc->keep = 0.0; return (STV_NewObject(bo->wrk, bo->fetch_objcore, stv_transient, l)); } /*-------------------------------------------------------------------- * Turn the beresp into a obj */ static int vbf_beresp2obj(struct busyobj *bo) { unsigned l, l2; const char *b; uint8_t *bp; struct vsb *vary = NULL; int varyl = 0; l = 0; /* Create Vary instructions */ if (!(bo->fetch_objcore->flags & OC_F_PRIVATE)) { varyl = VRY_Create(bo, &vary); if (varyl > 0) { AN(vary); assert(varyl == VSB_len(vary)); l += PRNDUP((intptr_t)varyl); } else if (varyl < 0) { /* * Vary parse error * Complain about it, and make this a pass. */ VSLb(bo->vsl, SLT_Error, "Illegal 'Vary' header from backend, " "making this a pass."); bo->uncacheable = 1; AZ(vary); } else /* No vary */ AZ(vary); } l2 = http_EstimateWS(bo->beresp, bo->uncacheable ? HTTPH_A_PASS : HTTPH_A_INS); l += l2; if (bo->uncacheable) bo->fetch_objcore->flags |= OC_F_PASS; if (!vbf_allocobj(bo, l)) return (-1); if (vary != NULL) { AN(ObjSetAttr(bo->wrk, bo->fetch_objcore, OA_VARY, varyl, VSB_data(vary))); VSB_destroy(&vary); } AZ(ObjSetU32(bo->wrk, bo->fetch_objcore, OA_VXID, VXID(bo->vsl->wid))); /* for HTTP_Encode() VSLH call */ bo->beresp->logtag = SLT_ObjMethod; /* Filter into object */ bp = ObjSetAttr(bo->wrk, bo->fetch_objcore, OA_HEADERS, l2, NULL); AN(bp); HTTP_Encode(bo->beresp, bp, l2, bo->uncacheable ? HTTPH_A_PASS : HTTPH_A_INS); if (http_GetHdr(bo->beresp, H_Last_Modified, &b)) AZ(ObjSetDouble(bo->wrk, bo->fetch_objcore, OA_LASTMODIFIED, VTIM_parse(b))); else AZ(ObjSetDouble(bo->wrk, bo->fetch_objcore, OA_LASTMODIFIED, floor(bo->fetch_objcore->t_origin))); return (0); } /*-------------------------------------------------------------------- * Copy req->bereq and release req if not pass fetch */ static enum fetch_step vbf_stp_mkbereq(struct worker *wrk, struct busyobj *bo) { const char *q; CHECK_OBJ_NOTNULL(wrk, WORKER_MAGIC); CHECK_OBJ_NOTNULL(bo, BUSYOBJ_MAGIC); CHECK_OBJ_NOTNULL(bo->req, REQ_MAGIC); assert(bo->fetch_objcore->boc->state == BOS_INVALID); AZ(bo->storage); AZ(bo->storage_hint); HTTP_Setup(bo->bereq0, bo->ws, bo->vsl, SLT_BereqMethod); http_FilterReq(bo->bereq0, bo->req->http, bo->do_pass ? HTTPH_R_PASS : HTTPH_R_FETCH); if (!bo->do_pass) { http_ForceField(bo->bereq0, HTTP_HDR_METHOD, "GET"); http_ForceField(bo->bereq0, HTTP_HDR_PROTO, "HTTP/1.1"); if (cache_param->http_gzip_support) http_ForceHeader(bo->bereq0, H_Accept_Encoding, "gzip"); } else { AZ(bo->stale_oc); if (bo->bereq0->protover > 11) http_ForceField(bo->bereq0, HTTP_HDR_PROTO, "HTTP/1.1"); } http_CopyHome(bo->bereq0); if (bo->stale_oc != NULL && ObjCheckFlag(bo->wrk, bo->stale_oc, OF_IMSCAND) && (bo->stale_oc->boc != NULL || ObjGetLen(wrk, bo->stale_oc) != 0)) { AZ(bo->stale_oc->flags & OC_F_PASS); q = HTTP_GetHdrPack(bo->wrk, bo->stale_oc, H_Last_Modified); if (q != NULL) http_PrintfHeader(bo->bereq0, "If-Modified-Since: %s", q); q = HTTP_GetHdrPack(bo->wrk, bo->stale_oc, H_ETag); if (q != NULL) http_PrintfHeader(bo->bereq0, "If-None-Match: %s", q); } HTTP_Setup(bo->bereq, bo->ws, bo->vsl, SLT_BereqMethod); bo->ws_bo = WS_Snapshot(bo->ws); HTTP_Copy(bo->bereq, bo->bereq0); if (bo->req->req_body_status == REQ_BODY_NONE) { bo->req = NULL; ObjSetState(bo->wrk, bo->fetch_objcore, BOS_REQ_DONE); } return (F_STP_STARTFETCH); } /*-------------------------------------------------------------------- * Start a new VSL transaction and try again * Prepare the busyobj and fetch processors */ static enum fetch_step vbf_stp_retry(struct worker *wrk, struct busyobj *bo) { struct vfp_ctx *vfc; CHECK_OBJ_NOTNULL(wrk, WORKER_MAGIC); CHECK_OBJ_NOTNULL(bo, BUSYOBJ_MAGIC); vfc = bo->vfc; CHECK_OBJ_NOTNULL(vfc, VFP_CTX_MAGIC); assert(bo->fetch_objcore->boc->state <= BOS_REQ_DONE); VSLb_ts_busyobj(bo, "Retry", W_TIM_real(wrk)); /* VDI_Finish must have been called before */ assert(bo->director_state == DIR_S_NULL); /* reset other bo attributes - See VBO_GetBusyObj */ bo->storage = NULL; bo->storage_hint = NULL; bo->do_esi = 0; bo->do_stream = 1; /* reset fetch processors */ VFP_Setup(vfc); // XXX: BereqEnd + BereqAcct ? VSL_ChgId(bo->vsl, "bereq", "retry", VXID_Get(wrk, VSL_BACKENDMARKER)); VSLb_ts_busyobj(bo, "Start", bo->t_prev); http_VSL_log(bo->bereq); return (F_STP_STARTFETCH); } /*-------------------------------------------------------------------- * Setup bereq from bereq0, run vcl_backend_fetch */ static enum fetch_step vbf_stp_startfetch(struct worker *wrk, struct busyobj *bo) { int i; double now; CHECK_OBJ_NOTNULL(wrk, WORKER_MAGIC); CHECK_OBJ_NOTNULL(bo, BUSYOBJ_MAGIC); AZ(bo->storage); AZ(bo->storage_hint); bo->storage = STV_next(); if (bo->retries > 0) http_Unset(bo->bereq, "\012X-Varnish:"); http_PrintfHeader(bo->bereq, "X-Varnish: %u", VXID(bo->vsl->wid)); VCL_backend_fetch_method(bo->vcl, wrk, NULL, bo, NULL); bo->uncacheable = bo->do_pass; if (wrk->handling == VCL_RET_ABANDON || wrk->handling == VCL_RET_FAIL) return (F_STP_FAIL); assert (wrk->handling == VCL_RET_FETCH); HTTP_Setup(bo->beresp, bo->ws, bo->vsl, SLT_BerespMethod); assert(bo->fetch_objcore->boc->state <= BOS_REQ_DONE); AZ(bo->htc); i = VDI_GetHdr(wrk, bo); now = W_TIM_real(wrk); VSLb_ts_busyobj(bo, "Beresp", now); if (i) { assert(bo->director_state == DIR_S_NULL); return (F_STP_ERROR); } http_VSL_log(bo->beresp); if (!http_GetHdr(bo->beresp, H_Date, NULL)) { /* * RFC 2616 14.18 Date: The Date general-header field * represents the date and time at which the message was * originated, having the same semantics as orig-date in * RFC 822. ... A received message that does not have a * Date header field MUST be assigned one by the recipient * if the message will be cached by that recipient or * gatewayed via a protocol which requires a Date. * * If we didn't get a Date header, we assign one here. */ http_TimeHeader(bo->beresp, "Date: ", now); } /* * These two headers can be spread over multiple actual headers * and we rely on their content outside of VCL, so collect them * into one line here. */ http_CollectHdr(bo->beresp, H_Cache_Control); http_CollectHdr(bo->beresp, H_Vary); /* * Figure out how the fetch is supposed to happen, before the * headers are adultered by VCL */ if (!strcasecmp(http_GetMethod(bo->bereq), "head")) { /* * A HEAD request can never have a body in the reply, * no matter what the headers might say. * [RFC7231 4.3.2 p25] */ wrk->stats->fetch_head++; bo->htc->body_status = BS_NONE; } else if (http_GetStatus(bo->beresp) <= 199) { /* * 1xx responses never have a body. * [RFC7230 3.3.2 p31] * ... but we should never see them. */ wrk->stats->fetch_1xx++; bo->htc->body_status = BS_ERROR; } else if (http_IsStatus(bo->beresp, 204)) { /* * 204 is "No Content", obviously don't expect a body. * [RFC7230 3.3.1 p29 and 3.3.2 p31] */ wrk->stats->fetch_204++; if ((http_GetHdr(bo->beresp, H_Content_Length, NULL) && bo->htc->content_length != 0) || http_GetHdr(bo->beresp, H_Transfer_Encoding, NULL)) bo->htc->body_status = BS_ERROR; else bo->htc->body_status = BS_NONE; } else if (http_IsStatus(bo->beresp, 304)) { /* * 304 is "Not Modified" it has no body. * [RFC7230 3.3 p28] */ wrk->stats->fetch_304++; bo->htc->body_status = BS_NONE; } else if (bo->htc->body_status == BS_CHUNKED) { wrk->stats->fetch_chunked++; } else if (bo->htc->body_status == BS_LENGTH) { assert(bo->htc->content_length > 0); wrk->stats->fetch_length++; } else if (bo->htc->body_status == BS_EOF) { wrk->stats->fetch_eof++; } else if (bo->htc->body_status == BS_ERROR) { wrk->stats->fetch_bad++; } else if (bo->htc->body_status == BS_NONE) { wrk->stats->fetch_none++; } else { WRONG("wrong bodystatus"); } if (bo->htc->body_status == BS_ERROR) { bo->htc->doclose = SC_RX_BODY; VDI_Finish(bo->wrk, bo); VSLb(bo->vsl, SLT_Error, "Body cannot be fetched"); assert(bo->director_state == DIR_S_NULL); return (F_STP_ERROR); } if (bo->fetch_objcore->flags & OC_F_PRIVATE) { /* private objects have negative TTL */ bo->fetch_objcore->t_origin = now; bo->fetch_objcore->ttl = -1.; bo->fetch_objcore->grace = 0; bo->fetch_objcore->keep = 0; } else { /* What does RFC2616 think about TTL ? */ RFC2616_Ttl(bo, now, &bo->fetch_objcore->t_origin, &bo->fetch_objcore->ttl, &bo->fetch_objcore->grace, &bo->fetch_objcore->keep ); } AZ(bo->do_esi); AZ(bo->was_304); if (http_IsStatus(bo->beresp, 304)) { if (bo->stale_oc != NULL && ObjCheckFlag(bo->wrk, bo->stale_oc, OF_IMSCAND)) { if (ObjCheckFlag(bo->wrk, bo->stale_oc, OF_CHGGZIP)) { /* * If we changed the gzip status of the object * the stored Content_Encoding controls we * must weaken any new ETag we get. */ http_Unset(bo->beresp, H_Content_Encoding); RFC2616_Weaken_Etag(bo->beresp); } http_Unset(bo->beresp, H_Content_Length); HTTP_Merge(bo->wrk, bo->stale_oc, bo->beresp); assert(http_IsStatus(bo->beresp, 200)); bo->was_304 = 1; } else if (!bo->do_pass) { /* * Backend sent unallowed 304 */ VSLb(bo->vsl, SLT_Error, "304 response but not conditional fetch"); bo->htc->doclose = SC_RX_BAD; VDI_Finish(bo->wrk, bo); return (F_STP_ERROR); } } bo->vfc->bo = bo; bo->vfc->oc = bo->fetch_objcore; bo->vfc->wrk = bo->wrk; bo->vfc->http = bo->beresp; bo->vfc->esi_req = bo->bereq; VCL_backend_response_method(bo->vcl, wrk, NULL, bo, NULL); if (wrk->handling == VCL_RET_ABANDON || wrk->handling == VCL_RET_FAIL) { bo->htc->doclose = SC_RESP_CLOSE; VDI_Finish(bo->wrk, bo); return (F_STP_FAIL); } if (wrk->handling == VCL_RET_RETRY) { if (bo->htc->body_status != BS_NONE) bo->htc->doclose = SC_RESP_CLOSE; if (bo->director_state != DIR_S_NULL) VDI_Finish(bo->wrk, bo); if (bo->retries++ < cache_param->max_retries) return (F_STP_RETRY); VSLb(bo->vsl, SLT_VCL_Error, "Too many retries, delivering 503"); assert(bo->director_state == DIR_S_NULL); return (F_STP_ERROR); } assert(bo->fetch_objcore->boc->state <= BOS_REQ_DONE); if (bo->fetch_objcore->boc->state != BOS_REQ_DONE) { bo->req = NULL; ObjSetState(wrk, bo->fetch_objcore, BOS_REQ_DONE); } if (bo->do_esi) bo->do_stream = 0; if (wrk->handling == VCL_RET_PASS) { bo->fetch_objcore->flags |= OC_F_HFP; bo->uncacheable = 1; wrk->handling = VCL_RET_DELIVER; } if (bo->do_pass || bo->uncacheable) bo->fetch_objcore->flags |= OC_F_PASS; assert(wrk->handling == VCL_RET_DELIVER); return (bo->was_304 ? F_STP_CONDFETCH : F_STP_FETCH); } /*-------------------------------------------------------------------- */ static enum fetch_step vbf_stp_fetchbody(struct worker *wrk, struct busyobj *bo) { ssize_t l; uint8_t *ptr; enum vfp_status vfps = VFP_ERROR; ssize_t est; struct vfp_ctx *vfc; CHECK_OBJ_NOTNULL(bo, BUSYOBJ_MAGIC); vfc = bo->vfc; CHECK_OBJ_NOTNULL(vfc, VFP_CTX_MAGIC); AN(vfc->vfp_nxt); est = bo->htc->content_length; if (est < 0) est = 0; do { if (vfc->oc->flags & OC_F_ABANDON) { /* * A pass object and delivery was terminated * We don't fail the fetch, in order for hit-for-pass * objects to be created. */ AN(vfc->oc->flags & OC_F_PASS); VSLb(wrk->vsl, SLT_FetchError, "Pass delivery abandoned"); bo->htc->doclose = SC_RX_BODY; break; } AZ(vfc->failed); l = est; assert(l >= 0); if (VFP_GetStorage(vfc, &l, &ptr) != VFP_OK) { bo->htc->doclose = SC_RX_BODY; break; } AZ(vfc->failed); vfps = VFP_Suck(vfc, ptr, &l); if (l > 0 && vfps != VFP_ERROR) { bo->acct.beresp_bodybytes += l; VFP_Extend(vfc, l); if (est >= l) est -= l; else est = 0; } } while (vfps == VFP_OK); if (vfc->failed) { (void)VFP_Error(vfc, "Fetch pipeline failed to process"); bo->htc->doclose = SC_RX_BODY; VFP_Close(vfc); VDI_Finish(wrk, bo); if (!bo->do_stream) { assert(bo->fetch_objcore->boc->state < BOS_STREAM); // XXX: doclose = ? return (F_STP_ERROR); } else { wrk->stats->fetch_failed++; return (F_STP_FAIL); } } ObjTrimStore(wrk, vfc->oc); return (F_STP_FETCHEND); } /*-------------------------------------------------------------------- */ #define vbf_vfp_push(bo, vfp, top) \ do { \ if (VFP_Push((bo)->vfc, (vfp), (top)) == NULL) { \ assert (WS_Overflowed((bo)->vfc->http->ws)); \ (void)VFP_Error((bo)->vfc, \ "workspace_backend overflow"); \ (bo)->htc->doclose = SC_OVERLOAD; \ VDI_Finish((bo)->wrk, bo); \ return (F_STP_ERROR); \ } \ } while (0) static enum fetch_step vbf_stp_fetch(struct worker *wrk, struct busyobj *bo) { const char *p; CHECK_OBJ_NOTNULL(wrk, WORKER_MAGIC); CHECK_OBJ_NOTNULL(bo, BUSYOBJ_MAGIC); CHECK_OBJ_NOTNULL(bo->fetch_objcore, OBJCORE_MAGIC); assert(wrk->handling == VCL_RET_DELIVER); /* * The VCL variables beresp.do_g[un]zip tells us how we want the * object processed before it is stored. * * The backend Content-Encoding header tells us what we are going * to receive, which we classify in the following three classes: * * "Content-Encoding: gzip" --> object is gzip'ed. * no Content-Encoding --> object is not gzip'ed. * anything else --> do nothing wrt gzip * */ /* We do nothing unless the param is set */ if (!cache_param->http_gzip_support) bo->do_gzip = bo->do_gunzip = 0; if (bo->htc->content_length == 0) http_Unset(bo->beresp, H_Content_Encoding); if (bo->htc->body_status != BS_NONE) { bo->is_gzip = http_HdrIs(bo->beresp, H_Content_Encoding, "gzip"); bo->is_gunzip = !http_GetHdr(bo->beresp, H_Content_Encoding, NULL); assert(bo->is_gzip == 0 || bo->is_gunzip == 0); } /* We won't gunzip unless it is non-empty and gzip'ed */ if (bo->htc->body_status == BS_NONE || bo->htc->content_length == 0 || (bo->do_gunzip && !bo->is_gzip)) bo->do_gunzip = 0; /* We wont gzip unless it is non-empty and ungzip'ed */ if (bo->htc->body_status == BS_NONE || bo->htc->content_length == 0 || (bo->do_gzip && !bo->is_gunzip)) bo->do_gzip = 0; /* But we can't do both at the same time */ assert(bo->do_gzip == 0 || bo->do_gunzip == 0); if (bo->do_gunzip || (bo->is_gzip && bo->do_esi)) vbf_vfp_push(bo, &vfp_gunzip, 1); if (bo->htc->content_length != 0) { if (bo->do_esi && bo->do_gzip) { vbf_vfp_push(bo, &vfp_esi_gzip, 1); } else if (bo->do_esi && bo->is_gzip && !bo->do_gunzip) { vbf_vfp_push(bo, &vfp_esi_gzip, 1); } else if (bo->do_esi) { vbf_vfp_push(bo, &vfp_esi, 1); } else if (bo->do_gzip) { vbf_vfp_push(bo, &vfp_gzip, 1); } else if (bo->is_gzip && !bo->do_gunzip) { vbf_vfp_push(bo, &vfp_testgunzip, 1); } } if (bo->fetch_objcore->flags & OC_F_PRIVATE) AN(bo->uncacheable); /* No reason to try streaming a non-existing body */ if (bo->htc->body_status == BS_NONE) bo->do_stream = 0; bo->fetch_objcore->boc->len_so_far = 0; if (VFP_Open(bo->vfc)) { (void)VFP_Error(bo->vfc, "Fetch pipeline failed to open"); bo->htc->doclose = SC_RX_BODY; VDI_Finish(bo->wrk, bo); return (F_STP_ERROR); } if (vbf_beresp2obj(bo)) { (void)VFP_Error(bo->vfc, "Could not get storage"); bo->htc->doclose = SC_RX_BODY; VFP_Close(bo->vfc); VDI_Finish(bo->wrk, bo); return (F_STP_ERROR); } if (bo->do_esi) ObjSetFlag(bo->wrk, bo->fetch_objcore, OF_ESIPROC, 1); if (bo->do_gzip || (bo->is_gzip && !bo->do_gunzip)) ObjSetFlag(bo->wrk, bo->fetch_objcore, OF_GZIPED, 1); if (bo->do_gzip || bo->do_gunzip) ObjSetFlag(bo->wrk, bo->fetch_objcore, OF_CHGGZIP, 1); if (!(bo->fetch_objcore->flags & OC_F_PASS) && http_IsStatus(bo->beresp, 200) && ( http_GetHdr(bo->beresp, H_Last_Modified, &p) || http_GetHdr(bo->beresp, H_ETag, &p))) ObjSetFlag(bo->wrk, bo->fetch_objcore, OF_IMSCAND, 1); if (bo->htc->body_status != BS_NONE && VDI_GetBody(bo->wrk, bo) != 0) { (void)VFP_Error(bo->vfc, "GetBody failed - workspace_backend overflow?"); VFP_Close(bo->vfc); bo->htc->doclose = SC_OVERLOAD; VDI_Finish(bo->wrk, bo); return (F_STP_ERROR); } assert(bo->fetch_objcore->boc->refcount >= 1); assert(bo->fetch_objcore->boc->state == BOS_REQ_DONE); if (bo->do_stream) { ObjSetState(wrk, bo->fetch_objcore, BOS_PREP_STREAM); HSH_Unbusy(wrk, bo->fetch_objcore); ObjSetState(wrk, bo->fetch_objcore, BOS_STREAM); } VSLb(bo->vsl, SLT_Fetch_Body, "%u %s %s", bo->htc->body_status, body_status_2str(bo->htc->body_status), bo->do_stream ? "stream" : "-"); if (bo->htc->body_status != BS_NONE) { assert(bo->htc->body_status != BS_ERROR); return (F_STP_FETCHBODY); } AZ(bo->vfc->failed); return (F_STP_FETCHEND); } static enum fetch_step vbf_stp_fetchend(struct worker *wrk, struct busyobj *bo) { AZ(bo->vfc->failed); VFP_Close(bo->vfc); AZ(ObjSetU64(wrk, bo->fetch_objcore, OA_LEN, bo->fetch_objcore->boc->len_so_far)); if (bo->do_stream) assert(bo->fetch_objcore->boc->state == BOS_STREAM); else { assert(bo->fetch_objcore->boc->state == BOS_REQ_DONE); HSH_Unbusy(wrk, bo->fetch_objcore); } /* Recycle the backend connection before setting BOS_FINISHED to give predictable backend reuse behavior for varnishtest */ VDI_Finish(bo->wrk, bo); ObjSetState(wrk, bo->fetch_objcore, BOS_FINISHED); VSLb_ts_busyobj(bo, "BerespBody", W_TIM_real(wrk)); if (bo->stale_oc != NULL) HSH_Kill(bo->stale_oc); return (F_STP_DONE); } /*-------------------------------------------------------------------- */ static int vbf_objiterator(void *priv, int flush, const void *ptr, ssize_t len) { struct busyobj *bo; ssize_t l; const uint8_t *ps = ptr; uint8_t *pd; (void)flush; CAST_OBJ_NOTNULL(bo, priv, BUSYOBJ_MAGIC); while (len > 0) { l = len; if (VFP_GetStorage(bo->vfc, &l, &pd) != VFP_OK) return (1); if (len < l) l = len; memcpy(pd, ps, l); VFP_Extend(bo->vfc, l); ps += l; len -= l; } return (0); } static enum fetch_step vbf_stp_condfetch(struct worker *wrk, struct busyobj *bo) { CHECK_OBJ_NOTNULL(wrk, WORKER_MAGIC); CHECK_OBJ_NOTNULL(bo, BUSYOBJ_MAGIC); AZ(vbf_beresp2obj(bo)); if (ObjHasAttr(bo->wrk, bo->stale_oc, OA_ESIDATA)) AZ(ObjCopyAttr(bo->wrk, bo->fetch_objcore, bo->stale_oc, OA_ESIDATA)); AZ(ObjCopyAttr(bo->wrk, bo->fetch_objcore, bo->stale_oc, OA_FLAGS)); AZ(ObjCopyAttr(bo->wrk, bo->fetch_objcore, bo->stale_oc, OA_GZIPBITS)); if (bo->do_stream) { ObjSetState(wrk, bo->fetch_objcore, BOS_PREP_STREAM); HSH_Unbusy(wrk, bo->fetch_objcore); ObjSetState(wrk, bo->fetch_objcore, BOS_STREAM); } if (ObjIterate(wrk, bo->stale_oc, bo, vbf_objiterator, 0)) (void)VFP_Error(bo->vfc, "Template object failed"); if (bo->stale_oc->flags & OC_F_FAILED) (void)VFP_Error(bo->vfc, "Template object failed"); if (bo->vfc->failed) { VDI_Finish(bo->wrk, bo); wrk->stats->fetch_failed++; return (F_STP_FAIL); } return (F_STP_FETCHEND); } /*-------------------------------------------------------------------- * Create synth object */ static enum fetch_step vbf_stp_error(struct worker *wrk, struct busyobj *bo) { ssize_t l, ll, o; double now; uint8_t *ptr; struct vsb *synth_body; CHECK_OBJ_NOTNULL(wrk, WORKER_MAGIC); CHECK_OBJ_NOTNULL(bo, BUSYOBJ_MAGIC); CHECK_OBJ_NOTNULL(bo->fetch_objcore, OBJCORE_MAGIC); AN(bo->fetch_objcore->flags & OC_F_BUSY); assert(bo->director_state == DIR_S_NULL); wrk->stats->fetch_failed++; now = W_TIM_real(wrk); VSLb_ts_busyobj(bo, "Error", now); if (bo->fetch_objcore->stobj->stevedore != NULL) ObjFreeObj(bo->wrk, bo->fetch_objcore); // XXX: reset all beresp flags ? HTTP_Setup(bo->beresp, bo->ws, bo->vsl, SLT_BerespMethod); http_PutResponse(bo->beresp, "HTTP/1.1", 503, "Backend fetch failed"); http_TimeHeader(bo->beresp, "Date: ", now); http_SetHeader(bo->beresp, "Server: Varnish"); bo->fetch_objcore->t_origin = now; if (!VTAILQ_EMPTY(&bo->fetch_objcore->objhead->waitinglist)) { /* * If there is a waitinglist, it means that there is no * grace-able object, so cache the error return for a * short time, so the waiting list can drain, rather than * each objcore on the waiting list sequentially attempt * to fetch from the backend. */ bo->fetch_objcore->ttl = 1; bo->fetch_objcore->grace = 5; bo->fetch_objcore->keep = 5; } else { bo->fetch_objcore->ttl = 0; bo->fetch_objcore->grace = 0; bo->fetch_objcore->keep = 0; } synth_body = VSB_new_auto(); AN(synth_body); VCL_backend_error_method(bo->vcl, wrk, NULL, bo, synth_body); AZ(VSB_finish(synth_body)); if (wrk->handling == VCL_RET_ABANDON || wrk->handling == VCL_RET_FAIL) { VSB_destroy(&synth_body); return (F_STP_FAIL); } if (wrk->handling == VCL_RET_RETRY) { VSB_destroy(&synth_body); if (bo->retries++ < cache_param->max_retries) return (F_STP_RETRY); VSLb(bo->vsl, SLT_VCL_Error, "Too many retries, failing"); return (F_STP_FAIL); } assert(wrk->handling == VCL_RET_DELIVER); bo->vfc->bo = bo; bo->vfc->wrk = bo->wrk; bo->vfc->oc = bo->fetch_objcore; bo->vfc->http = bo->beresp; bo->vfc->esi_req = bo->bereq; if (vbf_beresp2obj(bo)) { (void)VFP_Error(bo->vfc, "Could not get storage"); VSB_destroy(&synth_body); return (F_STP_FAIL); } ll = VSB_len(synth_body); o = 0; while (ll > 0) { l = ll; if (VFP_GetStorage(bo->vfc, &l, &ptr) != VFP_OK) break; memcpy(ptr, VSB_data(synth_body) + o, l); VFP_Extend(bo->vfc, l); ll -= l; o += l; } AZ(ObjSetU64(wrk, bo->fetch_objcore, OA_LEN, o)); VSB_destroy(&synth_body); HSH_Unbusy(wrk, bo->fetch_objcore); ObjSetState(wrk, bo->fetch_objcore, BOS_FINISHED); return (F_STP_DONE); } /*-------------------------------------------------------------------- */ static enum fetch_step vbf_stp_fail(struct worker *wrk, const struct busyobj *bo) { CHECK_OBJ_NOTNULL(wrk, WORKER_MAGIC); CHECK_OBJ_NOTNULL(bo, BUSYOBJ_MAGIC); CHECK_OBJ_NOTNULL(bo->fetch_objcore, OBJCORE_MAGIC); assert(bo->fetch_objcore->boc->state < BOS_FINISHED); HSH_Fail(bo->fetch_objcore); if (!(bo->fetch_objcore->flags & OC_F_BUSY)) HSH_Kill(bo->fetch_objcore); ObjSetState(wrk, bo->fetch_objcore, BOS_FAILED); return (F_STP_DONE); } /*-------------------------------------------------------------------- */ static enum fetch_step vbf_stp_done(void) { WRONG("Just plain wrong"); NEEDLESS(return(F_STP_DONE)); } static void __match_proto__(task_func_t) vbf_fetch_thread(struct worker *wrk, void *priv) { struct busyobj *bo; enum fetch_step stp; CHECK_OBJ_NOTNULL(wrk, WORKER_MAGIC); CAST_OBJ_NOTNULL(bo, priv, BUSYOBJ_MAGIC); CHECK_OBJ_NOTNULL(bo->req, REQ_MAGIC); CHECK_OBJ_NOTNULL(bo->fetch_objcore, OBJCORE_MAGIC); THR_SetBusyobj(bo); stp = F_STP_MKBEREQ; assert(isnan(bo->t_first)); assert(isnan(bo->t_prev)); VSLb_ts_busyobj(bo, "Start", W_TIM_real(wrk)); bo->wrk = wrk; wrk->vsl = bo->vsl; #if 0 if (bo->stale_oc != NULL) { CHECK_OBJ_NOTNULL(bo->stale_oc, OBJCORE_MAGIC); /* We don't want the oc/stevedore ops in fetching thread */ if (!ObjCheckFlag(wrk, bo->stale_oc, OF_IMSCAND)) (void)HSH_DerefObjCore(wrk, &bo->stale_oc, 0); } #endif while (stp != F_STP_DONE) { CHECK_OBJ_NOTNULL(bo, BUSYOBJ_MAGIC); assert(bo->fetch_objcore->boc->refcount >= 1); switch (stp) { #define FETCH_STEP(l, U, arg) \ case F_STP_##U: \ stp = vbf_stp_##l arg; \ break; #include "tbl/steps.h" default: WRONG("Illegal fetch_step"); } } assert(bo->director_state == DIR_S_NULL); http_Teardown(bo->bereq); http_Teardown(bo->beresp); if (bo->fetch_objcore->boc->state == BOS_FINISHED) { AZ(bo->fetch_objcore->flags & OC_F_FAILED); VSLb(bo->vsl, SLT_Length, "%ju", (uintmax_t)ObjGetLen(bo->wrk, bo->fetch_objcore)); } // AZ(bo->fetch_objcore->boc); // XXX if (bo->stale_oc != NULL) (void)HSH_DerefObjCore(wrk, &bo->stale_oc, 0); wrk->vsl = NULL; HSH_DerefBoc(wrk, bo->fetch_objcore); SES_Rel(bo->sp); VBO_ReleaseBusyObj(wrk, &bo); THR_SetBusyobj(NULL); } /*-------------------------------------------------------------------- */ void VBF_Fetch(struct worker *wrk, struct req *req, struct objcore *oc, struct objcore *oldoc, enum vbf_fetch_mode_e mode) { struct boc *boc; struct busyobj *bo; const char *how; CHECK_OBJ_NOTNULL(wrk, WORKER_MAGIC); CHECK_OBJ_NOTNULL(req, REQ_MAGIC); CHECK_OBJ_NOTNULL(oc, OBJCORE_MAGIC); AN(oc->flags & OC_F_BUSY); CHECK_OBJ_ORNULL(oldoc, OBJCORE_MAGIC); bo = VBO_GetBusyObj(wrk, req); CHECK_OBJ_NOTNULL(bo, BUSYOBJ_MAGIC); boc = HSH_RefBoc(oc); CHECK_OBJ_NOTNULL(boc, BOC_MAGIC); switch (mode) { case VBF_PASS: how = "pass"; bo->do_pass = 1; break; case VBF_NORMAL: how = "fetch"; break; case VBF_BACKGROUND: how = "bgfetch"; bo->is_bgfetch = 1; break; default: WRONG("Wrong fetch mode"); } VSLb(bo->vsl, SLT_Begin, "bereq %u %s", VXID(req->vsl->wid), how); VSLb(req->vsl, SLT_Link, "bereq %u %s", VXID(bo->vsl->wid), how); THR_SetBusyobj(bo); bo->sp = req->sp; SES_Ref(bo->sp); AN(bo->vcl); oc->boc->vary = req->vary_b; req->vary_b = NULL; HSH_Ref(oc); AZ(bo->fetch_objcore); bo->fetch_objcore = oc; AZ(bo->stale_oc); if (oldoc != NULL) { assert(oldoc->refcnt > 0); HSH_Ref(oldoc); bo->stale_oc = oldoc; } AZ(bo->req); bo->req = req; bo->fetch_task.priv = bo; bo->fetch_task.func = vbf_fetch_thread; if (Pool_Task(wrk->pool, &bo->fetch_task, TASK_QUEUE_BO)) { wrk->stats->fetch_no_thread++; (void)vbf_stp_fail(req->wrk, bo); if (bo->stale_oc != NULL) (void)HSH_DerefObjCore(wrk, &bo->stale_oc, 0); HSH_DerefBoc(wrk, oc); SES_Rel(bo->sp); VBO_ReleaseBusyObj(wrk, &bo); } else { bo = NULL; /* ref transferred to fetch thread */ if (mode == VBF_BACKGROUND) { ObjWaitState(oc, BOS_REQ_DONE); (void)VRB_Ignore(req); } else { ObjWaitState(oc, BOS_STREAM); if (oc->boc->state == BOS_FAILED) { AN((oc->flags & OC_F_FAILED)); } else { AZ(oc->flags & OC_F_BUSY); } } } AZ(bo); VSLb_ts_req(req, "Fetch", W_TIM_real(wrk)); assert(oc->boc == boc); HSH_DerefBoc(wrk, oc); if (mode == VBF_BACKGROUND) (void)HSH_DerefObjCore(wrk, &oc, HSH_RUSH_POLICY); THR_SetBusyobj(NULL); }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_3337_0
crossvul-cpp_data_bad_5096_1
/* * Copyright (c) 2011-2012, Centre National d'Etudes Spatiales (CNES), 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. */ /* * compare_dump_files.c * * Created on: 25 juil. 2011 * Author: mickael */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <assert.h> #include "opj_getopt.h" typedef struct test_cmp_parameters { /** */ char* base_filename; /** */ char* test_filename; } test_cmp_parameters; /******************************************************************************* * Command line help function *******************************************************************************/ static void compare_dump_files_help_display(void) { fprintf(stdout,"\nList of parameters for the compare_dump_files function \n"); fprintf(stdout,"\n"); fprintf(stdout," -b \t REQUIRED \t filename to the reference/baseline dump file \n"); fprintf(stdout," -t \t REQUIRED \t filename to the test dump file image\n"); fprintf(stdout,"\n"); } /******************************************************************************* * Parse command line *******************************************************************************/ static int parse_cmdline_cmp(int argc, char **argv, test_cmp_parameters* param) { size_t sizemembasefile, sizememtestfile; int index; const char optlist[] = "b:t:"; int c; /* Init parameters */ param->base_filename = NULL; param->test_filename = NULL; opj_opterr = 0; while ((c = opj_getopt(argc, argv, optlist)) != -1) switch (c) { case 'b': sizemembasefile = strlen(opj_optarg) + 1; param->base_filename = (char*) malloc(sizemembasefile); strcpy(param->base_filename, opj_optarg); /*printf("param->base_filename = %s [%d / %d]\n", param->base_filename, strlen(param->base_filename), sizemembasefile );*/ break; case 't': sizememtestfile = strlen(opj_optarg) + 1; param->test_filename = (char*) malloc(sizememtestfile); strcpy(param->test_filename, opj_optarg); /*printf("param->test_filename = %s [%d / %d]\n", param->test_filename, strlen(param->test_filename), sizememtestfile);*/ break; case '?': if ( (opj_optopt == 'b') || (opj_optopt == 't') ) fprintf(stderr, "Option -%c requires an argument.\n", opj_optopt); else if (isprint(opj_optopt)) fprintf(stderr, "Unknown option `-%c'.\n", opj_optopt); else fprintf(stderr, "Unknown option character `\\x%x'.\n", opj_optopt); return 1; default: fprintf(stderr, "WARNING -> this option is not valid \"-%c %s\"\n", c, opj_optarg); break; } if (opj_optind != argc) { for (index = opj_optind; index < argc; index++) fprintf(stderr,"Non-option argument %s\n", argv[index]); return 1; } return 0; } /******************************************************************************* * MAIN *******************************************************************************/ int main(int argc, char **argv) { test_cmp_parameters inParam; FILE *fbase=NULL, *ftest=NULL; int same = 0; char lbase[256]; char strbase[256]; char ltest[256]; char strtest[256]; if( parse_cmdline_cmp(argc, argv, &inParam) == 1 ) { compare_dump_files_help_display(); goto cleanup; } /* Display Parameters*/ printf("******Parameters********* \n"); printf(" base_filename = %s\n" " test_filename = %s\n", inParam.base_filename, inParam.test_filename); printf("************************* \n"); /* open base file */ printf("Try to open: %s for reading ... ", inParam.base_filename); if((fbase = fopen(inParam.base_filename, "rb"))==NULL) { goto cleanup; } printf("Ok.\n"); /* open test file */ printf("Try to open: %s for reading ... ", inParam.test_filename); if((ftest = fopen(inParam.test_filename, "rb"))==NULL) { goto cleanup; } printf("Ok.\n"); while (fgets(lbase, sizeof(lbase), fbase) && fgets(ltest,sizeof(ltest),ftest)) { int nbase = sscanf(lbase, "%255[^\r\n]", strbase); int ntest = sscanf(ltest, "%255[^\r\n]", strtest); assert( nbase != 255 && ntest != 255 ); if( nbase != 1 || ntest != 1 ) { fprintf(stderr, "could not parse line from files\n" ); goto cleanup; } if( strcmp( strbase, strtest ) != 0 ) { fprintf(stderr,"<%s> vs. <%s>\n", strbase, strtest); goto cleanup; } } same = 1; printf("\n***** TEST SUCCEED: Files are the same. *****\n"); cleanup: /*Close File*/ if(fbase) fclose(fbase); if(ftest) fclose(ftest); /* Free memory*/ free(inParam.base_filename); free(inParam.test_filename); return same ? EXIT_SUCCESS : EXIT_FAILURE; }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_5096_1
crossvul-cpp_data_bad_2131_2
/* * HID driver for some logitech "special" devices * * Copyright (c) 1999 Andreas Gal * Copyright (c) 2000-2005 Vojtech Pavlik <vojtech@suse.cz> * Copyright (c) 2005 Michael Haboustak <mike-@cinci.rr.com> for Concept2, Inc * Copyright (c) 2006-2007 Jiri Kosina * Copyright (c) 2008 Jiri Slaby * Copyright (c) 2010 Hendrik Iben */ /* * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. */ #include <linux/device.h> #include <linux/hid.h> #include <linux/module.h> #include <linux/random.h> #include <linux/sched.h> #include <linux/usb.h> #include <linux/wait.h> #include "usbhid/usbhid.h" #include "hid-ids.h" #include "hid-lg.h" #define LG_RDESC 0x001 #define LG_BAD_RELATIVE_KEYS 0x002 #define LG_DUPLICATE_USAGES 0x004 #define LG_EXPANDED_KEYMAP 0x010 #define LG_IGNORE_DOUBLED_WHEEL 0x020 #define LG_WIRELESS 0x040 #define LG_INVERT_HWHEEL 0x080 #define LG_NOGET 0x100 #define LG_FF 0x200 #define LG_FF2 0x400 #define LG_RDESC_REL_ABS 0x800 #define LG_FF3 0x1000 #define LG_FF4 0x2000 /* Size of the original descriptors of the Driving Force (and Pro) wheels */ #define DF_RDESC_ORIG_SIZE 130 #define DFP_RDESC_ORIG_SIZE 97 #define FV_RDESC_ORIG_SIZE 130 #define MOMO_RDESC_ORIG_SIZE 87 #define MOMO2_RDESC_ORIG_SIZE 87 /* Fixed report descriptors for Logitech Driving Force (and Pro) * wheel controllers * * The original descriptors hide the separate throttle and brake axes in * a custom vendor usage page, providing only a combined value as * GenericDesktop.Y. * These descriptors remove the combined Y axis and instead report * separate throttle (Y) and brake (RZ). */ static __u8 df_rdesc_fixed[] = { 0x05, 0x01, /* Usage Page (Desktop), */ 0x09, 0x04, /* Usage (Joystik), */ 0xA1, 0x01, /* Collection (Application), */ 0xA1, 0x02, /* Collection (Logical), */ 0x95, 0x01, /* Report Count (1), */ 0x75, 0x0A, /* Report Size (10), */ 0x14, /* Logical Minimum (0), */ 0x26, 0xFF, 0x03, /* Logical Maximum (1023), */ 0x34, /* Physical Minimum (0), */ 0x46, 0xFF, 0x03, /* Physical Maximum (1023), */ 0x09, 0x30, /* Usage (X), */ 0x81, 0x02, /* Input (Variable), */ 0x95, 0x0C, /* Report Count (12), */ 0x75, 0x01, /* Report Size (1), */ 0x25, 0x01, /* Logical Maximum (1), */ 0x45, 0x01, /* Physical Maximum (1), */ 0x05, 0x09, /* Usage (Buttons), */ 0x19, 0x01, /* Usage Minimum (1), */ 0x29, 0x0c, /* Usage Maximum (12), */ 0x81, 0x02, /* Input (Variable), */ 0x95, 0x02, /* Report Count (2), */ 0x06, 0x00, 0xFF, /* Usage Page (Vendor: 65280), */ 0x09, 0x01, /* Usage (?: 1), */ 0x81, 0x02, /* Input (Variable), */ 0x05, 0x01, /* Usage Page (Desktop), */ 0x26, 0xFF, 0x00, /* Logical Maximum (255), */ 0x46, 0xFF, 0x00, /* Physical Maximum (255), */ 0x95, 0x01, /* Report Count (1), */ 0x75, 0x08, /* Report Size (8), */ 0x81, 0x02, /* Input (Variable), */ 0x25, 0x07, /* Logical Maximum (7), */ 0x46, 0x3B, 0x01, /* Physical Maximum (315), */ 0x75, 0x04, /* Report Size (4), */ 0x65, 0x14, /* Unit (Degrees), */ 0x09, 0x39, /* Usage (Hat Switch), */ 0x81, 0x42, /* Input (Variable, Null State), */ 0x75, 0x01, /* Report Size (1), */ 0x95, 0x04, /* Report Count (4), */ 0x65, 0x00, /* Unit (none), */ 0x06, 0x00, 0xFF, /* Usage Page (Vendor: 65280), */ 0x09, 0x01, /* Usage (?: 1), */ 0x25, 0x01, /* Logical Maximum (1), */ 0x45, 0x01, /* Physical Maximum (1), */ 0x81, 0x02, /* Input (Variable), */ 0x05, 0x01, /* Usage Page (Desktop), */ 0x95, 0x01, /* Report Count (1), */ 0x75, 0x08, /* Report Size (8), */ 0x26, 0xFF, 0x00, /* Logical Maximum (255), */ 0x46, 0xFF, 0x00, /* Physical Maximum (255), */ 0x09, 0x31, /* Usage (Y), */ 0x81, 0x02, /* Input (Variable), */ 0x09, 0x35, /* Usage (Rz), */ 0x81, 0x02, /* Input (Variable), */ 0xC0, /* End Collection, */ 0xA1, 0x02, /* Collection (Logical), */ 0x26, 0xFF, 0x00, /* Logical Maximum (255), */ 0x46, 0xFF, 0x00, /* Physical Maximum (255), */ 0x95, 0x07, /* Report Count (7), */ 0x75, 0x08, /* Report Size (8), */ 0x09, 0x03, /* Usage (?: 3), */ 0x91, 0x02, /* Output (Variable), */ 0xC0, /* End Collection, */ 0xC0 /* End Collection */ }; static __u8 dfp_rdesc_fixed[] = { 0x05, 0x01, /* Usage Page (Desktop), */ 0x09, 0x04, /* Usage (Joystik), */ 0xA1, 0x01, /* Collection (Application), */ 0xA1, 0x02, /* Collection (Logical), */ 0x95, 0x01, /* Report Count (1), */ 0x75, 0x0E, /* Report Size (14), */ 0x14, /* Logical Minimum (0), */ 0x26, 0xFF, 0x3F, /* Logical Maximum (16383), */ 0x34, /* Physical Minimum (0), */ 0x46, 0xFF, 0x3F, /* Physical Maximum (16383), */ 0x09, 0x30, /* Usage (X), */ 0x81, 0x02, /* Input (Variable), */ 0x95, 0x0E, /* Report Count (14), */ 0x75, 0x01, /* Report Size (1), */ 0x25, 0x01, /* Logical Maximum (1), */ 0x45, 0x01, /* Physical Maximum (1), */ 0x05, 0x09, /* Usage Page (Button), */ 0x19, 0x01, /* Usage Minimum (01h), */ 0x29, 0x0E, /* Usage Maximum (0Eh), */ 0x81, 0x02, /* Input (Variable), */ 0x05, 0x01, /* Usage Page (Desktop), */ 0x95, 0x01, /* Report Count (1), */ 0x75, 0x04, /* Report Size (4), */ 0x25, 0x07, /* Logical Maximum (7), */ 0x46, 0x3B, 0x01, /* Physical Maximum (315), */ 0x65, 0x14, /* Unit (Degrees), */ 0x09, 0x39, /* Usage (Hat Switch), */ 0x81, 0x42, /* Input (Variable, Nullstate), */ 0x65, 0x00, /* Unit, */ 0x26, 0xFF, 0x00, /* Logical Maximum (255), */ 0x46, 0xFF, 0x00, /* Physical Maximum (255), */ 0x75, 0x08, /* Report Size (8), */ 0x81, 0x01, /* Input (Constant), */ 0x09, 0x31, /* Usage (Y), */ 0x81, 0x02, /* Input (Variable), */ 0x09, 0x35, /* Usage (Rz), */ 0x81, 0x02, /* Input (Variable), */ 0x81, 0x01, /* Input (Constant), */ 0xC0, /* End Collection, */ 0xA1, 0x02, /* Collection (Logical), */ 0x09, 0x02, /* Usage (02h), */ 0x95, 0x07, /* Report Count (7), */ 0x91, 0x02, /* Output (Variable), */ 0xC0, /* End Collection, */ 0xC0 /* End Collection */ }; static __u8 fv_rdesc_fixed[] = { 0x05, 0x01, /* Usage Page (Desktop), */ 0x09, 0x04, /* Usage (Joystik), */ 0xA1, 0x01, /* Collection (Application), */ 0xA1, 0x02, /* Collection (Logical), */ 0x95, 0x01, /* Report Count (1), */ 0x75, 0x0A, /* Report Size (10), */ 0x15, 0x00, /* Logical Minimum (0), */ 0x26, 0xFF, 0x03, /* Logical Maximum (1023), */ 0x35, 0x00, /* Physical Minimum (0), */ 0x46, 0xFF, 0x03, /* Physical Maximum (1023), */ 0x09, 0x30, /* Usage (X), */ 0x81, 0x02, /* Input (Variable), */ 0x95, 0x0C, /* Report Count (12), */ 0x75, 0x01, /* Report Size (1), */ 0x25, 0x01, /* Logical Maximum (1), */ 0x45, 0x01, /* Physical Maximum (1), */ 0x05, 0x09, /* Usage Page (Button), */ 0x19, 0x01, /* Usage Minimum (01h), */ 0x29, 0x0C, /* Usage Maximum (0Ch), */ 0x81, 0x02, /* Input (Variable), */ 0x95, 0x02, /* Report Count (2), */ 0x06, 0x00, 0xFF, /* Usage Page (FF00h), */ 0x09, 0x01, /* Usage (01h), */ 0x81, 0x02, /* Input (Variable), */ 0x09, 0x02, /* Usage (02h), */ 0x26, 0xFF, 0x00, /* Logical Maximum (255), */ 0x46, 0xFF, 0x00, /* Physical Maximum (255), */ 0x95, 0x01, /* Report Count (1), */ 0x75, 0x08, /* Report Size (8), */ 0x81, 0x02, /* Input (Variable), */ 0x05, 0x01, /* Usage Page (Desktop), */ 0x25, 0x07, /* Logical Maximum (7), */ 0x46, 0x3B, 0x01, /* Physical Maximum (315), */ 0x75, 0x04, /* Report Size (4), */ 0x65, 0x14, /* Unit (Degrees), */ 0x09, 0x39, /* Usage (Hat Switch), */ 0x81, 0x42, /* Input (Variable, Null State), */ 0x75, 0x01, /* Report Size (1), */ 0x95, 0x04, /* Report Count (4), */ 0x65, 0x00, /* Unit, */ 0x06, 0x00, 0xFF, /* Usage Page (FF00h), */ 0x09, 0x01, /* Usage (01h), */ 0x25, 0x01, /* Logical Maximum (1), */ 0x45, 0x01, /* Physical Maximum (1), */ 0x81, 0x02, /* Input (Variable), */ 0x05, 0x01, /* Usage Page (Desktop), */ 0x95, 0x01, /* Report Count (1), */ 0x75, 0x08, /* Report Size (8), */ 0x26, 0xFF, 0x00, /* Logical Maximum (255), */ 0x46, 0xFF, 0x00, /* Physical Maximum (255), */ 0x09, 0x31, /* Usage (Y), */ 0x81, 0x02, /* Input (Variable), */ 0x09, 0x32, /* Usage (Z), */ 0x81, 0x02, /* Input (Variable), */ 0xC0, /* End Collection, */ 0xA1, 0x02, /* Collection (Logical), */ 0x26, 0xFF, 0x00, /* Logical Maximum (255), */ 0x46, 0xFF, 0x00, /* Physical Maximum (255), */ 0x95, 0x07, /* Report Count (7), */ 0x75, 0x08, /* Report Size (8), */ 0x09, 0x03, /* Usage (03h), */ 0x91, 0x02, /* Output (Variable), */ 0xC0, /* End Collection, */ 0xC0 /* End Collection */ }; static __u8 momo_rdesc_fixed[] = { 0x05, 0x01, /* Usage Page (Desktop), */ 0x09, 0x04, /* Usage (Joystik), */ 0xA1, 0x01, /* Collection (Application), */ 0xA1, 0x02, /* Collection (Logical), */ 0x95, 0x01, /* Report Count (1), */ 0x75, 0x0A, /* Report Size (10), */ 0x15, 0x00, /* Logical Minimum (0), */ 0x26, 0xFF, 0x03, /* Logical Maximum (1023), */ 0x35, 0x00, /* Physical Minimum (0), */ 0x46, 0xFF, 0x03, /* Physical Maximum (1023), */ 0x09, 0x30, /* Usage (X), */ 0x81, 0x02, /* Input (Variable), */ 0x95, 0x08, /* Report Count (8), */ 0x75, 0x01, /* Report Size (1), */ 0x25, 0x01, /* Logical Maximum (1), */ 0x45, 0x01, /* Physical Maximum (1), */ 0x05, 0x09, /* Usage Page (Button), */ 0x19, 0x01, /* Usage Minimum (01h), */ 0x29, 0x08, /* Usage Maximum (08h), */ 0x81, 0x02, /* Input (Variable), */ 0x06, 0x00, 0xFF, /* Usage Page (FF00h), */ 0x75, 0x0E, /* Report Size (14), */ 0x95, 0x01, /* Report Count (1), */ 0x26, 0xFF, 0x00, /* Logical Maximum (255), */ 0x46, 0xFF, 0x00, /* Physical Maximum (255), */ 0x09, 0x00, /* Usage (00h), */ 0x81, 0x02, /* Input (Variable), */ 0x05, 0x01, /* Usage Page (Desktop), */ 0x75, 0x08, /* Report Size (8), */ 0x09, 0x31, /* Usage (Y), */ 0x81, 0x02, /* Input (Variable), */ 0x09, 0x32, /* Usage (Z), */ 0x81, 0x02, /* Input (Variable), */ 0x06, 0x00, 0xFF, /* Usage Page (FF00h), */ 0x09, 0x01, /* Usage (01h), */ 0x81, 0x02, /* Input (Variable), */ 0xC0, /* End Collection, */ 0xA1, 0x02, /* Collection (Logical), */ 0x09, 0x02, /* Usage (02h), */ 0x95, 0x07, /* Report Count (7), */ 0x91, 0x02, /* Output (Variable), */ 0xC0, /* End Collection, */ 0xC0 /* End Collection */ }; static __u8 momo2_rdesc_fixed[] = { 0x05, 0x01, /* Usage Page (Desktop), */ 0x09, 0x04, /* Usage (Joystik), */ 0xA1, 0x01, /* Collection (Application), */ 0xA1, 0x02, /* Collection (Logical), */ 0x95, 0x01, /* Report Count (1), */ 0x75, 0x0A, /* Report Size (10), */ 0x15, 0x00, /* Logical Minimum (0), */ 0x26, 0xFF, 0x03, /* Logical Maximum (1023), */ 0x35, 0x00, /* Physical Minimum (0), */ 0x46, 0xFF, 0x03, /* Physical Maximum (1023), */ 0x09, 0x30, /* Usage (X), */ 0x81, 0x02, /* Input (Variable), */ 0x95, 0x0A, /* Report Count (10), */ 0x75, 0x01, /* Report Size (1), */ 0x25, 0x01, /* Logical Maximum (1), */ 0x45, 0x01, /* Physical Maximum (1), */ 0x05, 0x09, /* Usage Page (Button), */ 0x19, 0x01, /* Usage Minimum (01h), */ 0x29, 0x0A, /* Usage Maximum (0Ah), */ 0x81, 0x02, /* Input (Variable), */ 0x06, 0x00, 0xFF, /* Usage Page (FF00h), */ 0x09, 0x00, /* Usage (00h), */ 0x95, 0x04, /* Report Count (4), */ 0x81, 0x02, /* Input (Variable), */ 0x95, 0x01, /* Report Count (1), */ 0x75, 0x08, /* Report Size (8), */ 0x26, 0xFF, 0x00, /* Logical Maximum (255), */ 0x46, 0xFF, 0x00, /* Physical Maximum (255), */ 0x09, 0x01, /* Usage (01h), */ 0x81, 0x02, /* Input (Variable), */ 0x05, 0x01, /* Usage Page (Desktop), */ 0x09, 0x31, /* Usage (Y), */ 0x81, 0x02, /* Input (Variable), */ 0x09, 0x32, /* Usage (Z), */ 0x81, 0x02, /* Input (Variable), */ 0x06, 0x00, 0xFF, /* Usage Page (FF00h), */ 0x09, 0x00, /* Usage (00h), */ 0x81, 0x02, /* Input (Variable), */ 0xC0, /* End Collection, */ 0xA1, 0x02, /* Collection (Logical), */ 0x09, 0x02, /* Usage (02h), */ 0x95, 0x07, /* Report Count (7), */ 0x91, 0x02, /* Output (Variable), */ 0xC0, /* End Collection, */ 0xC0 /* End Collection */ }; /* * Certain Logitech keyboards send in report #3 keys which are far * above the logical maximum described in descriptor. This extends * the original value of 0x28c of logical maximum to 0x104d */ static __u8 *lg_report_fixup(struct hid_device *hdev, __u8 *rdesc, unsigned int *rsize) { struct lg_drv_data *drv_data = hid_get_drvdata(hdev); struct usb_device_descriptor *udesc; __u16 bcdDevice, rev_maj, rev_min; if ((drv_data->quirks & LG_RDESC) && *rsize >= 90 && rdesc[83] == 0x26 && rdesc[84] == 0x8c && rdesc[85] == 0x02) { hid_info(hdev, "fixing up Logitech keyboard report descriptor\n"); rdesc[84] = rdesc[89] = 0x4d; rdesc[85] = rdesc[90] = 0x10; } if ((drv_data->quirks & LG_RDESC_REL_ABS) && *rsize >= 50 && rdesc[32] == 0x81 && rdesc[33] == 0x06 && rdesc[49] == 0x81 && rdesc[50] == 0x06) { hid_info(hdev, "fixing up rel/abs in Logitech report descriptor\n"); rdesc[33] = rdesc[50] = 0x02; } switch (hdev->product) { /* Several wheels report as this id when operating in emulation mode. */ case USB_DEVICE_ID_LOGITECH_WHEEL: udesc = &(hid_to_usb_dev(hdev)->descriptor); if (!udesc) { hid_err(hdev, "NULL USB device descriptor\n"); break; } bcdDevice = le16_to_cpu(udesc->bcdDevice); rev_maj = bcdDevice >> 8; rev_min = bcdDevice & 0xff; /* Update the report descriptor for only the Driving Force wheel */ if (rev_maj == 1 && rev_min == 2 && *rsize == DF_RDESC_ORIG_SIZE) { hid_info(hdev, "fixing up Logitech Driving Force report descriptor\n"); rdesc = df_rdesc_fixed; *rsize = sizeof(df_rdesc_fixed); } break; case USB_DEVICE_ID_LOGITECH_MOMO_WHEEL: if (*rsize == MOMO_RDESC_ORIG_SIZE) { hid_info(hdev, "fixing up Logitech Momo Force (Red) report descriptor\n"); rdesc = momo_rdesc_fixed; *rsize = sizeof(momo_rdesc_fixed); } break; case USB_DEVICE_ID_LOGITECH_MOMO_WHEEL2: if (*rsize == MOMO2_RDESC_ORIG_SIZE) { hid_info(hdev, "fixing up Logitech Momo Racing Force (Black) report descriptor\n"); rdesc = momo2_rdesc_fixed; *rsize = sizeof(momo2_rdesc_fixed); } break; case USB_DEVICE_ID_LOGITECH_VIBRATION_WHEEL: if (*rsize == FV_RDESC_ORIG_SIZE) { hid_info(hdev, "fixing up Logitech Formula Vibration report descriptor\n"); rdesc = fv_rdesc_fixed; *rsize = sizeof(fv_rdesc_fixed); } break; case USB_DEVICE_ID_LOGITECH_DFP_WHEEL: if (*rsize == DFP_RDESC_ORIG_SIZE) { hid_info(hdev, "fixing up Logitech Driving Force Pro report descriptor\n"); rdesc = dfp_rdesc_fixed; *rsize = sizeof(dfp_rdesc_fixed); } break; case USB_DEVICE_ID_LOGITECH_WII_WHEEL: if (*rsize >= 101 && rdesc[41] == 0x95 && rdesc[42] == 0x0B && rdesc[47] == 0x05 && rdesc[48] == 0x09) { hid_info(hdev, "fixing up Logitech Speed Force Wireless report descriptor\n"); rdesc[41] = 0x05; rdesc[42] = 0x09; rdesc[47] = 0x95; rdesc[48] = 0x0B; } break; } return rdesc; } #define lg_map_key_clear(c) hid_map_usage_clear(hi, usage, bit, max, \ EV_KEY, (c)) static int lg_ultrax_remote_mapping(struct hid_input *hi, struct hid_usage *usage, unsigned long **bit, int *max) { if ((usage->hid & HID_USAGE_PAGE) != HID_UP_LOGIVENDOR) return 0; set_bit(EV_REP, hi->input->evbit); switch (usage->hid & HID_USAGE) { /* Reported on Logitech Ultra X Media Remote */ case 0x004: lg_map_key_clear(KEY_AGAIN); break; case 0x00d: lg_map_key_clear(KEY_HOME); break; case 0x024: lg_map_key_clear(KEY_SHUFFLE); break; case 0x025: lg_map_key_clear(KEY_TV); break; case 0x026: lg_map_key_clear(KEY_MENU); break; case 0x031: lg_map_key_clear(KEY_AUDIO); break; case 0x032: lg_map_key_clear(KEY_TEXT); break; case 0x033: lg_map_key_clear(KEY_LAST); break; case 0x047: lg_map_key_clear(KEY_MP3); break; case 0x048: lg_map_key_clear(KEY_DVD); break; case 0x049: lg_map_key_clear(KEY_MEDIA); break; case 0x04a: lg_map_key_clear(KEY_VIDEO); break; case 0x04b: lg_map_key_clear(KEY_ANGLE); break; case 0x04c: lg_map_key_clear(KEY_LANGUAGE); break; case 0x04d: lg_map_key_clear(KEY_SUBTITLE); break; case 0x051: lg_map_key_clear(KEY_RED); break; case 0x052: lg_map_key_clear(KEY_CLOSE); break; default: return 0; } return 1; } static int lg_dinovo_mapping(struct hid_input *hi, struct hid_usage *usage, unsigned long **bit, int *max) { if ((usage->hid & HID_USAGE_PAGE) != HID_UP_LOGIVENDOR) return 0; switch (usage->hid & HID_USAGE) { case 0x00d: lg_map_key_clear(KEY_MEDIA); break; default: return 0; } return 1; } static int lg_wireless_mapping(struct hid_input *hi, struct hid_usage *usage, unsigned long **bit, int *max) { if ((usage->hid & HID_USAGE_PAGE) != HID_UP_CONSUMER) return 0; switch (usage->hid & HID_USAGE) { case 0x1001: lg_map_key_clear(KEY_MESSENGER); break; case 0x1003: lg_map_key_clear(KEY_SOUND); break; case 0x1004: lg_map_key_clear(KEY_VIDEO); break; case 0x1005: lg_map_key_clear(KEY_AUDIO); break; case 0x100a: lg_map_key_clear(KEY_DOCUMENTS); break; /* The following two entries are Playlist 1 and 2 on the MX3200 */ case 0x100f: lg_map_key_clear(KEY_FN_1); break; case 0x1010: lg_map_key_clear(KEY_FN_2); break; case 0x1011: lg_map_key_clear(KEY_PREVIOUSSONG); break; case 0x1012: lg_map_key_clear(KEY_NEXTSONG); break; case 0x1013: lg_map_key_clear(KEY_CAMERA); break; case 0x1014: lg_map_key_clear(KEY_MESSENGER); break; case 0x1015: lg_map_key_clear(KEY_RECORD); break; case 0x1016: lg_map_key_clear(KEY_PLAYER); break; case 0x1017: lg_map_key_clear(KEY_EJECTCD); break; case 0x1018: lg_map_key_clear(KEY_MEDIA); break; case 0x1019: lg_map_key_clear(KEY_PROG1); break; case 0x101a: lg_map_key_clear(KEY_PROG2); break; case 0x101b: lg_map_key_clear(KEY_PROG3); break; case 0x101c: lg_map_key_clear(KEY_CYCLEWINDOWS); break; case 0x101f: lg_map_key_clear(KEY_ZOOMIN); break; case 0x1020: lg_map_key_clear(KEY_ZOOMOUT); break; case 0x1021: lg_map_key_clear(KEY_ZOOMRESET); break; case 0x1023: lg_map_key_clear(KEY_CLOSE); break; case 0x1027: lg_map_key_clear(KEY_MENU); break; /* this one is marked as 'Rotate' */ case 0x1028: lg_map_key_clear(KEY_ANGLE); break; case 0x1029: lg_map_key_clear(KEY_SHUFFLE); break; case 0x102a: lg_map_key_clear(KEY_BACK); break; case 0x102b: lg_map_key_clear(KEY_CYCLEWINDOWS); break; case 0x102d: lg_map_key_clear(KEY_WWW); break; /* The following two are 'Start/answer call' and 'End/reject call' on the MX3200 */ case 0x1031: lg_map_key_clear(KEY_OK); break; case 0x1032: lg_map_key_clear(KEY_CANCEL); break; case 0x1041: lg_map_key_clear(KEY_BATTERY); break; case 0x1042: lg_map_key_clear(KEY_WORDPROCESSOR); break; case 0x1043: lg_map_key_clear(KEY_SPREADSHEET); break; case 0x1044: lg_map_key_clear(KEY_PRESENTATION); break; case 0x1045: lg_map_key_clear(KEY_UNDO); break; case 0x1046: lg_map_key_clear(KEY_REDO); break; case 0x1047: lg_map_key_clear(KEY_PRINT); break; case 0x1048: lg_map_key_clear(KEY_SAVE); break; case 0x1049: lg_map_key_clear(KEY_PROG1); break; case 0x104a: lg_map_key_clear(KEY_PROG2); break; case 0x104b: lg_map_key_clear(KEY_PROG3); break; case 0x104c: lg_map_key_clear(KEY_PROG4); break; default: return 0; } return 1; } static int lg_input_mapping(struct hid_device *hdev, struct hid_input *hi, struct hid_field *field, struct hid_usage *usage, unsigned long **bit, int *max) { /* extended mapping for certain Logitech hardware (Logitech cordless desktop LX500) */ static const u8 e_keymap[] = { 0,216, 0,213,175,156, 0, 0, 0, 0, 144, 0, 0, 0, 0, 0, 0, 0, 0,212, 174,167,152,161,112, 0, 0, 0,154, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,183,184,185,186,187, 188,189,190,191,192,193,194, 0, 0, 0 }; struct lg_drv_data *drv_data = hid_get_drvdata(hdev); unsigned int hid = usage->hid; if (hdev->product == USB_DEVICE_ID_LOGITECH_RECEIVER && lg_ultrax_remote_mapping(hi, usage, bit, max)) return 1; if (hdev->product == USB_DEVICE_ID_DINOVO_MINI && lg_dinovo_mapping(hi, usage, bit, max)) return 1; if ((drv_data->quirks & LG_WIRELESS) && lg_wireless_mapping(hi, usage, bit, max)) return 1; if ((hid & HID_USAGE_PAGE) != HID_UP_BUTTON) return 0; hid &= HID_USAGE; /* Special handling for Logitech Cordless Desktop */ if (field->application == HID_GD_MOUSE) { if ((drv_data->quirks & LG_IGNORE_DOUBLED_WHEEL) && (hid == 7 || hid == 8)) return -1; } else { if ((drv_data->quirks & LG_EXPANDED_KEYMAP) && hid < ARRAY_SIZE(e_keymap) && e_keymap[hid] != 0) { hid_map_usage(hi, usage, bit, max, EV_KEY, e_keymap[hid]); return 1; } } return 0; } static int lg_input_mapped(struct hid_device *hdev, struct hid_input *hi, struct hid_field *field, struct hid_usage *usage, unsigned long **bit, int *max) { struct lg_drv_data *drv_data = hid_get_drvdata(hdev); if ((drv_data->quirks & LG_BAD_RELATIVE_KEYS) && usage->type == EV_KEY && (field->flags & HID_MAIN_ITEM_RELATIVE)) field->flags &= ~HID_MAIN_ITEM_RELATIVE; if ((drv_data->quirks & LG_DUPLICATE_USAGES) && (usage->type == EV_KEY || usage->type == EV_REL || usage->type == EV_ABS)) clear_bit(usage->code, *bit); /* Ensure that Logitech wheels are not given a default fuzz/flat value */ if (usage->type == EV_ABS && (usage->code == ABS_X || usage->code == ABS_Y || usage->code == ABS_Z || usage->code == ABS_RZ)) { switch (hdev->product) { case USB_DEVICE_ID_LOGITECH_WHEEL: case USB_DEVICE_ID_LOGITECH_MOMO_WHEEL: case USB_DEVICE_ID_LOGITECH_DFP_WHEEL: case USB_DEVICE_ID_LOGITECH_G25_WHEEL: case USB_DEVICE_ID_LOGITECH_DFGT_WHEEL: case USB_DEVICE_ID_LOGITECH_G27_WHEEL: case USB_DEVICE_ID_LOGITECH_WII_WHEEL: case USB_DEVICE_ID_LOGITECH_MOMO_WHEEL2: case USB_DEVICE_ID_LOGITECH_VIBRATION_WHEEL: field->application = HID_GD_MULTIAXIS; break; default: break; } } return 0; } static int lg_event(struct hid_device *hdev, struct hid_field *field, struct hid_usage *usage, __s32 value) { struct lg_drv_data *drv_data = hid_get_drvdata(hdev); if ((drv_data->quirks & LG_INVERT_HWHEEL) && usage->code == REL_HWHEEL) { input_event(field->hidinput->input, usage->type, usage->code, -value); return 1; } if (drv_data->quirks & LG_FF4) { return lg4ff_adjust_input_event(hdev, field, usage, value, drv_data); } return 0; } static int lg_probe(struct hid_device *hdev, const struct hid_device_id *id) { unsigned int connect_mask = HID_CONNECT_DEFAULT; struct lg_drv_data *drv_data; int ret; drv_data = kzalloc(sizeof(struct lg_drv_data), GFP_KERNEL); if (!drv_data) { hid_err(hdev, "Insufficient memory, cannot allocate driver data\n"); return -ENOMEM; } drv_data->quirks = id->driver_data; hid_set_drvdata(hdev, (void *)drv_data); if (drv_data->quirks & LG_NOGET) hdev->quirks |= HID_QUIRK_NOGET; ret = hid_parse(hdev); if (ret) { hid_err(hdev, "parse failed\n"); goto err_free; } if (drv_data->quirks & (LG_FF | LG_FF2 | LG_FF3 | LG_FF4)) connect_mask &= ~HID_CONNECT_FF; ret = hid_hw_start(hdev, connect_mask); if (ret) { hid_err(hdev, "hw start failed\n"); goto err_free; } /* Setup wireless link with Logitech Wii wheel */ if (hdev->product == USB_DEVICE_ID_LOGITECH_WII_WHEEL) { unsigned char buf[] = { 0x00, 0xAF, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; ret = hid_hw_raw_request(hdev, buf[0], buf, sizeof(buf), HID_FEATURE_REPORT, HID_REQ_SET_REPORT); if (ret >= 0) { /* insert a little delay of 10 jiffies ~ 40ms */ wait_queue_head_t wait; init_waitqueue_head (&wait); wait_event_interruptible_timeout(wait, 0, 10); /* Select random Address */ buf[1] = 0xB2; get_random_bytes(&buf[2], 2); ret = hid_hw_raw_request(hdev, buf[0], buf, sizeof(buf), HID_FEATURE_REPORT, HID_REQ_SET_REPORT); } } if (drv_data->quirks & LG_FF) lgff_init(hdev); if (drv_data->quirks & LG_FF2) lg2ff_init(hdev); if (drv_data->quirks & LG_FF3) lg3ff_init(hdev); if (drv_data->quirks & LG_FF4) lg4ff_init(hdev); return 0; err_free: kfree(drv_data); return ret; } static void lg_remove(struct hid_device *hdev) { struct lg_drv_data *drv_data = hid_get_drvdata(hdev); if (drv_data->quirks & LG_FF4) lg4ff_deinit(hdev); hid_hw_stop(hdev); kfree(drv_data); } static const struct hid_device_id lg_devices[] = { { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_MX3000_RECEIVER), .driver_data = LG_RDESC | LG_WIRELESS }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_S510_RECEIVER), .driver_data = LG_RDESC | LG_WIRELESS }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_S510_RECEIVER_2), .driver_data = LG_RDESC | LG_WIRELESS }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_RECEIVER), .driver_data = LG_BAD_RELATIVE_KEYS }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_DINOVO_DESKTOP), .driver_data = LG_DUPLICATE_USAGES }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_DINOVO_EDGE), .driver_data = LG_DUPLICATE_USAGES }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_DINOVO_MINI), .driver_data = LG_DUPLICATE_USAGES }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_ELITE_KBD), .driver_data = LG_IGNORE_DOUBLED_WHEEL | LG_EXPANDED_KEYMAP }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_CORDLESS_DESKTOP_LX500), .driver_data = LG_IGNORE_DOUBLED_WHEEL | LG_EXPANDED_KEYMAP }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_EXTREME_3D), .driver_data = LG_NOGET }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_DUAL_ACTION), .driver_data = LG_NOGET }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_WHEEL), .driver_data = LG_NOGET | LG_FF4 }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_RUMBLEPAD_CORD), .driver_data = LG_FF2 }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_RUMBLEPAD), .driver_data = LG_FF }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_RUMBLEPAD2_2), .driver_data = LG_FF }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_WINGMAN_F3D), .driver_data = LG_FF }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_FORCE3D_PRO), .driver_data = LG_FF }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_MOMO_WHEEL), .driver_data = LG_NOGET | LG_FF4 }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_MOMO_WHEEL2), .driver_data = LG_FF4 }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_VIBRATION_WHEEL), .driver_data = LG_FF2 }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_G25_WHEEL), .driver_data = LG_FF4 }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_DFGT_WHEEL), .driver_data = LG_FF4 }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_G27_WHEEL), .driver_data = LG_FF4 }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_DFP_WHEEL), .driver_data = LG_NOGET | LG_FF4 }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_WII_WHEEL), .driver_data = LG_FF4 }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_WINGMAN_FFG), .driver_data = LG_FF }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_RUMBLEPAD2), .driver_data = LG_FF2 }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_FLIGHT_SYSTEM_G940), .driver_data = LG_FF3 }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_SPACENAVIGATOR), .driver_data = LG_RDESC_REL_ABS }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_SPACETRAVELLER), .driver_data = LG_RDESC_REL_ABS }, { } }; MODULE_DEVICE_TABLE(hid, lg_devices); static struct hid_driver lg_driver = { .name = "logitech", .id_table = lg_devices, .report_fixup = lg_report_fixup, .input_mapping = lg_input_mapping, .input_mapped = lg_input_mapped, .event = lg_event, .probe = lg_probe, .remove = lg_remove, }; module_hid_driver(lg_driver); MODULE_LICENSE("GPL");
./CrossVul/dataset_final_sorted/CWE-119/c/bad_2131_2
crossvul-cpp_data_bad_810_0
#include "jsi.h" #include "jsvalue.h" #include "jsbuiltin.h" #if defined(_MSC_VER) && (_MSC_VER < 1700) /* VS2012 has stdint.h */ typedef unsigned __int64 uint64_t; #else #include <stdint.h> #endif static void jsB_new_Number(js_State *J) { js_newnumber(J, js_gettop(J) > 1 ? js_tonumber(J, 1) : 0); } static void jsB_Number(js_State *J) { js_pushnumber(J, js_gettop(J) > 1 ? js_tonumber(J, 1) : 0); } static void Np_valueOf(js_State *J) { js_Object *self = js_toobject(J, 0); if (self->type != JS_CNUMBER) js_typeerror(J, "not a number"); js_pushnumber(J, self->u.number); } static void Np_toString(js_State *J) { char buf[32]; js_Object *self = js_toobject(J, 0); int radix = js_isundefined(J, 1) ? 10 : js_tointeger(J, 1); if (self->type != JS_CNUMBER) js_typeerror(J, "not a number"); if (radix == 10) { js_pushstring(J, jsV_numbertostring(J, buf, self->u.number)); return; } if (radix < 2 || radix > 36) js_rangeerror(J, "invalid radix"); /* lame number to string conversion for any radix from 2 to 36 */ { static const char digits[] = "0123456789abcdefghijklmnopqrstuvwxyz"; char buf[100]; double number = self->u.number; int sign = self->u.number < 0; js_Buffer *sb = NULL; uint64_t u, limit = ((uint64_t)1<<52); int ndigits, exp, point; if (number == 0) { js_pushstring(J, "0"); return; } if (isnan(number)) { js_pushstring(J, "NaN"); return; } if (isinf(number)) { js_pushstring(J, sign ? "-Infinity" : "Infinity"); return; } if (sign) number = -number; /* fit as many digits as we want in an int */ exp = 0; while (number * pow(radix, exp) > limit) --exp; while (number * pow(radix, exp+1) < limit) ++exp; u = number * pow(radix, exp) + 0.5; /* trim trailing zeros */ while (u > 0 && (u % radix) == 0) { u /= radix; --exp; } /* serialize digits */ ndigits = 0; while (u > 0) { buf[ndigits++] = digits[u % radix]; u /= radix; } point = ndigits - exp; if (js_try(J)) { js_free(J, sb); js_throw(J); } if (sign) js_putc(J, &sb, '-'); if (point <= 0) { js_putc(J, &sb, '0'); js_putc(J, &sb, '.'); while (point++ < 0) js_putc(J, &sb, '0'); while (ndigits-- > 0) js_putc(J, &sb, buf[ndigits]); } else { while (ndigits-- > 0) { js_putc(J, &sb, buf[ndigits]); if (--point == 0 && ndigits > 0) js_putc(J, &sb, '.'); } while (point-- > 0) js_putc(J, &sb, '0'); } js_putc(J, &sb, 0); js_pushstring(J, sb->s); js_endtry(J); js_free(J, sb); } } /* Customized ToString() on a number */ static void numtostr(js_State *J, const char *fmt, int w, double n) { char buf[32], *e; sprintf(buf, fmt, w, n); e = strchr(buf, 'e'); if (e) { int exp = atoi(e+1); sprintf(e, "e%+d", exp); } js_pushstring(J, buf); } static void Np_toFixed(js_State *J) { js_Object *self = js_toobject(J, 0); int width = js_tointeger(J, 1); char buf[32]; double x; if (self->type != JS_CNUMBER) js_typeerror(J, "not a number"); if (width < 0) js_rangeerror(J, "precision %d out of range", width); if (width > 20) js_rangeerror(J, "precision %d out of range", width); x = self->u.number; if (isnan(x) || isinf(x) || x <= -1e21 || x >= 1e21) js_pushstring(J, jsV_numbertostring(J, buf, x)); else numtostr(J, "%.*f", width, x); } static void Np_toExponential(js_State *J) { js_Object *self = js_toobject(J, 0); int width = js_tointeger(J, 1); char buf[32]; double x; if (self->type != JS_CNUMBER) js_typeerror(J, "not a number"); if (width < 0) js_rangeerror(J, "precision %d out of range", width); if (width > 20) js_rangeerror(J, "precision %d out of range", width); x = self->u.number; if (isnan(x) || isinf(x)) js_pushstring(J, jsV_numbertostring(J, buf, x)); else numtostr(J, "%.*e", width, self->u.number); } static void Np_toPrecision(js_State *J) { js_Object *self = js_toobject(J, 0); int width = js_tointeger(J, 1); char buf[32]; double x; if (self->type != JS_CNUMBER) js_typeerror(J, "not a number"); if (width < 1) js_rangeerror(J, "precision %d out of range", width); if (width > 21) js_rangeerror(J, "precision %d out of range", width); x = self->u.number; if (isnan(x) || isinf(x)) js_pushstring(J, jsV_numbertostring(J, buf, x)); else numtostr(J, "%.*g", width, self->u.number); } void jsB_initnumber(js_State *J) { J->Number_prototype->u.number = 0; js_pushobject(J, J->Number_prototype); { jsB_propf(J, "Number.prototype.valueOf", Np_valueOf, 0); jsB_propf(J, "Number.prototype.toString", Np_toString, 1); jsB_propf(J, "Number.prototype.toLocaleString", Np_toString, 0); jsB_propf(J, "Number.prototype.toFixed", Np_toFixed, 1); jsB_propf(J, "Number.prototype.toExponential", Np_toExponential, 1); jsB_propf(J, "Number.prototype.toPrecision", Np_toPrecision, 1); } js_newcconstructor(J, jsB_Number, jsB_new_Number, "Number", 0); /* 1 */ { jsB_propn(J, "MAX_VALUE", 1.7976931348623157e+308); jsB_propn(J, "MIN_VALUE", 5e-324); jsB_propn(J, "NaN", NAN); jsB_propn(J, "NEGATIVE_INFINITY", -INFINITY); jsB_propn(J, "POSITIVE_INFINITY", INFINITY); } js_defglobal(J, "Number", JS_DONTENUM); }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_810_0
crossvul-cpp_data_bad_929_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % SSSSS TTTTT AAA TTTTT IIIII SSSSS TTTTT IIIII CCCC % % SS T A A T I SS T I C % % SSS T AAAAA T I SSS T I C % % SS T A A T I SS T I C % % SSSSS T A A T IIIII SSSSS T IIIII CCCC % % % % % % MagickCore Image Statistical Methods % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/accelerate-private.h" #include "MagickCore/animate.h" #include "MagickCore/artifact.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/cache-private.h" #include "MagickCore/cache-view.h" #include "MagickCore/client.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite.h" #include "MagickCore/composite-private.h" #include "MagickCore/compress.h" #include "MagickCore/constitute.h" #include "MagickCore/display.h" #include "MagickCore/draw.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/gem.h" #include "MagickCore/gem-private.h" #include "MagickCore/geometry.h" #include "MagickCore/list.h" #include "MagickCore/image-private.h" #include "MagickCore/magic.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/module.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/paint.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/profile.h" #include "MagickCore/property.h" #include "MagickCore/quantize.h" #include "MagickCore/quantum-private.h" #include "MagickCore/random_.h" #include "MagickCore/random-private.h" #include "MagickCore/resource_.h" #include "MagickCore/segment.h" #include "MagickCore/semaphore.h" #include "MagickCore/signature-private.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/thread-private.h" #include "MagickCore/timer.h" #include "MagickCore/utility.h" #include "MagickCore/version.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E v a l u a t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % EvaluateImage() applies a value to the image with an arithmetic, relational, % or logical operator to an image. Use these operations to lighten or darken % an image, to increase or decrease contrast in an image, or to produce the % "negative" of an image. % % The format of the EvaluateImage method is: % % MagickBooleanType EvaluateImage(Image *image, % const MagickEvaluateOperator op,const double value, % ExceptionInfo *exception) % MagickBooleanType EvaluateImages(Image *images, % const MagickEvaluateOperator op,const double value, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o op: A channel op. % % o value: A value value. % % o exception: return any errors or warnings in this structure. % */ typedef struct _PixelChannels { double channel[CompositePixelChannel]; } PixelChannels; static PixelChannels **DestroyPixelThreadSet(PixelChannels **pixels) { register ssize_t i; assert(pixels != (PixelChannels **) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (pixels[i] != (PixelChannels *) NULL) pixels[i]=(PixelChannels *) RelinquishMagickMemory(pixels[i]); pixels=(PixelChannels **) RelinquishMagickMemory(pixels); return(pixels); } static PixelChannels **AcquirePixelThreadSet(const Image *image) { PixelChannels **pixels; register ssize_t i; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixels=(PixelChannels **) AcquireQuantumMemory(number_threads, sizeof(*pixels)); if (pixels == (PixelChannels **) NULL) return((PixelChannels **) NULL); (void) memset(pixels,0,number_threads*sizeof(*pixels)); for (i=0; i < (ssize_t) number_threads; i++) { register ssize_t j; pixels[i]=(PixelChannels *) AcquireQuantumMemory(image->columns, sizeof(**pixels)); if (pixels[i] == (PixelChannels *) NULL) return(DestroyPixelThreadSet(pixels)); for (j=0; j < (ssize_t) image->columns; j++) { register ssize_t k; for (k=0; k < MaxPixelChannels; k++) pixels[i][j].channel[k]=0.0; } } return(pixels); } static inline double EvaluateMax(const double x,const double y) { if (x > y) return(x); return(y); } #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static int IntensityCompare(const void *x,const void *y) { const PixelChannels *color_1, *color_2; double distance; register ssize_t i; color_1=(const PixelChannels *) x; color_2=(const PixelChannels *) y; distance=0.0; for (i=0; i < MaxPixelChannels; i++) distance+=color_1->channel[i]-(double) color_2->channel[i]; return(distance < 0 ? -1 : distance > 0 ? 1 : 0); } #if defined(__cplusplus) || defined(c_plusplus) } #endif static double ApplyEvaluateOperator(RandomInfo *random_info,const Quantum pixel, const MagickEvaluateOperator op,const double value) { double result; result=0.0; switch (op) { case UndefinedEvaluateOperator: break; case AbsEvaluateOperator: { result=(double) fabs((double) (pixel+value)); break; } case AddEvaluateOperator: { result=(double) (pixel+value); break; } case AddModulusEvaluateOperator: { /* This returns a 'floored modulus' of the addition which is a positive result. It differs from % or fmod() that returns a 'truncated modulus' result, where floor() is replaced by trunc() and could return a negative result (which is clipped). */ result=pixel+value; result-=(QuantumRange+1.0)*floor((double) result/(QuantumRange+1.0)); break; } case AndEvaluateOperator: { result=(double) ((size_t) pixel & (size_t) (value+0.5)); break; } case CosineEvaluateOperator: { result=(double) (QuantumRange*(0.5*cos((double) (2.0*MagickPI* QuantumScale*pixel*value))+0.5)); break; } case DivideEvaluateOperator: { result=pixel/(value == 0.0 ? 1.0 : value); break; } case ExponentialEvaluateOperator: { result=(double) (QuantumRange*exp((double) (value*QuantumScale*pixel))); break; } case GaussianNoiseEvaluateOperator: { result=(double) GenerateDifferentialNoise(random_info,pixel, GaussianNoise,value); break; } case ImpulseNoiseEvaluateOperator: { result=(double) GenerateDifferentialNoise(random_info,pixel,ImpulseNoise, value); break; } case LaplacianNoiseEvaluateOperator: { result=(double) GenerateDifferentialNoise(random_info,pixel, LaplacianNoise,value); break; } case LeftShiftEvaluateOperator: { result=(double) ((size_t) pixel << (size_t) (value+0.5)); break; } case LogEvaluateOperator: { if ((QuantumScale*pixel) >= MagickEpsilon) result=(double) (QuantumRange*log((double) (QuantumScale*value*pixel+ 1.0))/log((double) (value+1.0))); break; } case MaxEvaluateOperator: { result=(double) EvaluateMax((double) pixel,value); break; } case MeanEvaluateOperator: { result=(double) (pixel+value); break; } case MedianEvaluateOperator: { result=(double) (pixel+value); break; } case MinEvaluateOperator: { result=(double) MagickMin((double) pixel,value); break; } case MultiplicativeNoiseEvaluateOperator: { result=(double) GenerateDifferentialNoise(random_info,pixel, MultiplicativeGaussianNoise,value); break; } case MultiplyEvaluateOperator: { result=(double) (value*pixel); break; } case OrEvaluateOperator: { result=(double) ((size_t) pixel | (size_t) (value+0.5)); break; } case PoissonNoiseEvaluateOperator: { result=(double) GenerateDifferentialNoise(random_info,pixel,PoissonNoise, value); break; } case PowEvaluateOperator: { result=(double) (QuantumRange*pow((double) (QuantumScale*pixel),(double) value)); break; } case RightShiftEvaluateOperator: { result=(double) ((size_t) pixel >> (size_t) (value+0.5)); break; } case RootMeanSquareEvaluateOperator: { result=(double) (pixel*pixel+value); break; } case SetEvaluateOperator: { result=value; break; } case SineEvaluateOperator: { result=(double) (QuantumRange*(0.5*sin((double) (2.0*MagickPI* QuantumScale*pixel*value))+0.5)); break; } case SubtractEvaluateOperator: { result=(double) (pixel-value); break; } case SumEvaluateOperator: { result=(double) (pixel+value); break; } case ThresholdEvaluateOperator: { result=(double) (((double) pixel <= value) ? 0 : QuantumRange); break; } case ThresholdBlackEvaluateOperator: { result=(double) (((double) pixel <= value) ? 0 : pixel); break; } case ThresholdWhiteEvaluateOperator: { result=(double) (((double) pixel > value) ? QuantumRange : pixel); break; } case UniformNoiseEvaluateOperator: { result=(double) GenerateDifferentialNoise(random_info,pixel,UniformNoise, value); break; } case XorEvaluateOperator: { result=(double) ((size_t) pixel ^ (size_t) (value+0.5)); break; } } return(result); } static Image *AcquireImageCanvas(const Image *images,ExceptionInfo *exception) { const Image *p, *q; size_t columns, rows; q=images; columns=images->columns; rows=images->rows; for (p=images; p != (Image *) NULL; p=p->next) { if (p->number_channels > q->number_channels) q=p; if (p->columns > columns) columns=p->columns; if (p->rows > rows) rows=p->rows; } return(CloneImage(q,columns,rows,MagickTrue,exception)); } MagickExport Image *EvaluateImages(const Image *images, const MagickEvaluateOperator op,ExceptionInfo *exception) { #define EvaluateImageTag "Evaluate/Image" CacheView *evaluate_view; Image *image; MagickBooleanType status; MagickOffsetType progress; PixelChannels **magick_restrict evaluate_pixels; RandomInfo **magick_restrict random_info; size_t number_images; ssize_t y; #if defined(MAGICKCORE_OPENMP_SUPPORT) unsigned long key; #endif assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImageCanvas(images,exception); if (image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) { image=DestroyImage(image); return((Image *) NULL); } number_images=GetImageListLength(images); evaluate_pixels=AcquirePixelThreadSet(images); if (evaluate_pixels == (PixelChannels **) NULL) { image=DestroyImage(image); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename); return((Image *) NULL); } /* Evaluate image pixels. */ status=MagickTrue; progress=0; random_info=AcquireRandomInfoThreadSet(); evaluate_view=AcquireAuthenticCacheView(image,exception); if (op == MedianEvaluateOperator) { #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,images,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { CacheView *image_view; const Image *next; const int id = GetOpenMPThreadId(); register PixelChannels *evaluate_pixel; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(evaluate_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } evaluate_pixel=evaluate_pixels[id]; for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j, k; for (j=0; j < (ssize_t) number_images; j++) for (k=0; k < MaxPixelChannels; k++) evaluate_pixel[j].channel[k]=0.0; next=images; for (j=0; j < (ssize_t) number_images; j++) { register const Quantum *p; register ssize_t i; image_view=AcquireVirtualCacheView(next,exception); p=GetCacheViewVirtualPixels(image_view,x,y,1,1,exception); if (p == (const Quantum *) NULL) { image_view=DestroyCacheView(image_view); break; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait evaluate_traits=GetPixelChannelTraits(image,channel); PixelTrait traits = GetPixelChannelTraits(next,channel); if ((traits == UndefinedPixelTrait) || (evaluate_traits == UndefinedPixelTrait)) continue; if ((traits & UpdatePixelTrait) == 0) continue; evaluate_pixel[j].channel[i]=ApplyEvaluateOperator( random_info[id],GetPixelChannel(image,channel,p),op, evaluate_pixel[j].channel[i]); } image_view=DestroyCacheView(image_view); next=GetNextImageInList(next); } qsort((void *) evaluate_pixel,number_images,sizeof(*evaluate_pixel), IntensityCompare); for (k=0; k < (ssize_t) GetPixelChannels(image); k++) q[k]=ClampToQuantum(evaluate_pixel[j/2].channel[k]); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(evaluate_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(images,EvaluateImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } } else { #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,images,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { CacheView *image_view; const Image *next; const int id = GetOpenMPThreadId(); register ssize_t i, x; register PixelChannels *evaluate_pixel; register Quantum *magick_restrict q; ssize_t j; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(evaluate_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } evaluate_pixel=evaluate_pixels[id]; for (j=0; j < (ssize_t) image->columns; j++) for (i=0; i < MaxPixelChannels; i++) evaluate_pixel[j].channel[i]=0.0; next=images; for (j=0; j < (ssize_t) number_images; j++) { register const Quantum *p; image_view=AcquireVirtualCacheView(next,exception); p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1, exception); if (p == (const Quantum *) NULL) { image_view=DestroyCacheView(image_view); break; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(next); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(next,channel); PixelTrait evaluate_traits=GetPixelChannelTraits(image,channel); if ((traits == UndefinedPixelTrait) || (evaluate_traits == UndefinedPixelTrait)) continue; if ((traits & UpdatePixelTrait) == 0) continue; evaluate_pixel[x].channel[i]=ApplyEvaluateOperator( random_info[id],GetPixelChannel(image,channel,p),j == 0 ? AddEvaluateOperator : op,evaluate_pixel[x].channel[i]); } p+=GetPixelChannels(next); } image_view=DestroyCacheView(image_view); next=GetNextImageInList(next); } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; switch (op) { case MeanEvaluateOperator: { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) evaluate_pixel[x].channel[i]/=(double) number_images; break; } case MultiplyEvaluateOperator: { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { register ssize_t j; for (j=0; j < (ssize_t) (number_images-1); j++) evaluate_pixel[x].channel[i]*=QuantumScale; } break; } case RootMeanSquareEvaluateOperator: { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) evaluate_pixel[x].channel[i]=sqrt(evaluate_pixel[x].channel[i]/ number_images); break; } default: break; } } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; if ((traits & UpdatePixelTrait) == 0) continue; q[i]=ClampToQuantum(evaluate_pixel[x].channel[i]); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(evaluate_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(images,EvaluateImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } } evaluate_view=DestroyCacheView(evaluate_view); evaluate_pixels=DestroyPixelThreadSet(evaluate_pixels); random_info=DestroyRandomInfoThreadSet(random_info); if (status == MagickFalse) image=DestroyImage(image); return(image); } MagickExport MagickBooleanType EvaluateImage(Image *image, const MagickEvaluateOperator op,const double value,ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; RandomInfo **magick_restrict random_info; ssize_t y; #if defined(MAGICKCORE_OPENMP_SUPPORT) unsigned long key; #endif assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); status=MagickTrue; progress=0; random_info=AcquireRandomInfoThreadSet(); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double result; register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; if ((traits & CopyPixelTrait) != 0) continue; if ((traits & UpdatePixelTrait) == 0) continue; result=ApplyEvaluateOperator(random_info[id],q[i],op,value); if (op == MeanEvaluateOperator) result/=2.0; q[i]=ClampToQuantum(result); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,EvaluateImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); random_info=DestroyRandomInfoThreadSet(random_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F u n c t i o n I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FunctionImage() applies a value to the image with an arithmetic, relational, % or logical operator to an image. Use these operations to lighten or darken % an image, to increase or decrease contrast in an image, or to produce the % "negative" of an image. % % The format of the FunctionImage method is: % % MagickBooleanType FunctionImage(Image *image, % const MagickFunction function,const ssize_t number_parameters, % const double *parameters,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o function: A channel function. % % o parameters: one or more parameters. % % o exception: return any errors or warnings in this structure. % */ static Quantum ApplyFunction(Quantum pixel,const MagickFunction function, const size_t number_parameters,const double *parameters, ExceptionInfo *exception) { double result; register ssize_t i; (void) exception; result=0.0; switch (function) { case PolynomialFunction: { /* Polynomial: polynomial constants, highest to lowest order (e.g. c0*x^3+ c1*x^2+c2*x+c3). */ result=0.0; for (i=0; i < (ssize_t) number_parameters; i++) result=result*QuantumScale*pixel+parameters[i]; result*=QuantumRange; break; } case SinusoidFunction: { double amplitude, bias, frequency, phase; /* Sinusoid: frequency, phase, amplitude, bias. */ frequency=(number_parameters >= 1) ? parameters[0] : 1.0; phase=(number_parameters >= 2) ? parameters[1] : 0.0; amplitude=(number_parameters >= 3) ? parameters[2] : 0.5; bias=(number_parameters >= 4) ? parameters[3] : 0.5; result=(double) (QuantumRange*(amplitude*sin((double) (2.0* MagickPI*(frequency*QuantumScale*pixel+phase/360.0)))+bias)); break; } case ArcsinFunction: { double bias, center, range, width; /* Arcsin (peged at range limits for invalid results): width, center, range, and bias. */ width=(number_parameters >= 1) ? parameters[0] : 1.0; center=(number_parameters >= 2) ? parameters[1] : 0.5; range=(number_parameters >= 3) ? parameters[2] : 1.0; bias=(number_parameters >= 4) ? parameters[3] : 0.5; result=2.0/width*(QuantumScale*pixel-center); if ( result <= -1.0 ) result=bias-range/2.0; else if (result >= 1.0) result=bias+range/2.0; else result=(double) (range/MagickPI*asin((double) result)+bias); result*=QuantumRange; break; } case ArctanFunction: { double center, bias, range, slope; /* Arctan: slope, center, range, and bias. */ slope=(number_parameters >= 1) ? parameters[0] : 1.0; center=(number_parameters >= 2) ? parameters[1] : 0.5; range=(number_parameters >= 3) ? parameters[2] : 1.0; bias=(number_parameters >= 4) ? parameters[3] : 0.5; result=(double) (MagickPI*slope*(QuantumScale*pixel-center)); result=(double) (QuantumRange*(range/MagickPI*atan((double) result)+bias)); break; } case UndefinedFunction: break; } return(ClampToQuantum(result)); } MagickExport MagickBooleanType FunctionImage(Image *image, const MagickFunction function,const size_t number_parameters, const double *parameters,ExceptionInfo *exception) { #define FunctionImageTag "Function/Image " CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); #if defined(MAGICKCORE_OPENCL_SUPPORT) if (AccelerateFunctionImage(image,function,number_parameters,parameters, exception) != MagickFalse) return(MagickTrue); #endif if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; if ((traits & UpdatePixelTrait) == 0) continue; q[i]=ApplyFunction(q[i],function,number_parameters,parameters, exception); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,FunctionImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e E n t r o p y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageEntropy() returns the entropy of one or more image channels. % % The format of the GetImageEntropy method is: % % MagickBooleanType GetImageEntropy(const Image *image,double *entropy, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o entropy: the average entropy of the selected channels. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageEntropy(const Image *image, double *entropy,ExceptionInfo *exception) { ChannelStatistics *channel_statistics; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); channel_statistics=GetImageStatistics(image,exception); if (channel_statistics == (ChannelStatistics *) NULL) return(MagickFalse); *entropy=channel_statistics[CompositePixelChannel].entropy; channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e E x t r e m a % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageExtrema() returns the extrema of one or more image channels. % % The format of the GetImageExtrema method is: % % MagickBooleanType GetImageExtrema(const Image *image,size_t *minima, % size_t *maxima,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o minima: the minimum value in the channel. % % o maxima: the maximum value in the channel. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageExtrema(const Image *image, size_t *minima,size_t *maxima,ExceptionInfo *exception) { double max, min; MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=GetImageRange(image,&min,&max,exception); *minima=(size_t) ceil(min-0.5); *maxima=(size_t) floor(max+0.5); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e K u r t o s i s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageKurtosis() returns the kurtosis and skewness of one or more image % channels. % % The format of the GetImageKurtosis method is: % % MagickBooleanType GetImageKurtosis(const Image *image,double *kurtosis, % double *skewness,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o kurtosis: the kurtosis of the channel. % % o skewness: the skewness of the channel. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageKurtosis(const Image *image, double *kurtosis,double *skewness,ExceptionInfo *exception) { ChannelStatistics *channel_statistics; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); channel_statistics=GetImageStatistics(image,exception); if (channel_statistics == (ChannelStatistics *) NULL) return(MagickFalse); *kurtosis=channel_statistics[CompositePixelChannel].kurtosis; *skewness=channel_statistics[CompositePixelChannel].skewness; channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e M e a n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageMean() returns the mean and standard deviation of one or more image % channels. % % The format of the GetImageMean method is: % % MagickBooleanType GetImageMean(const Image *image,double *mean, % double *standard_deviation,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o mean: the average value in the channel. % % o standard_deviation: the standard deviation of the channel. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageMean(const Image *image,double *mean, double *standard_deviation,ExceptionInfo *exception) { ChannelStatistics *channel_statistics; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); channel_statistics=GetImageStatistics(image,exception); if (channel_statistics == (ChannelStatistics *) NULL) return(MagickFalse); *mean=channel_statistics[CompositePixelChannel].mean; *standard_deviation= channel_statistics[CompositePixelChannel].standard_deviation; channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e M o m e n t s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageMoments() returns the normalized moments of one or more image % channels. % % The format of the GetImageMoments method is: % % ChannelMoments *GetImageMoments(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ static size_t GetImageChannels(const Image *image) { register ssize_t i; size_t channels; channels=0; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; if ((traits & UpdatePixelTrait) == 0) continue; channels++; } return((size_t) (channels == 0 ? 1 : channels)); } MagickExport ChannelMoments *GetImageMoments(const Image *image, ExceptionInfo *exception) { #define MaxNumberImageMoments 8 CacheView *image_view; ChannelMoments *channel_moments; double M00[MaxPixelChannels+1], M01[MaxPixelChannels+1], M02[MaxPixelChannels+1], M03[MaxPixelChannels+1], M10[MaxPixelChannels+1], M11[MaxPixelChannels+1], M12[MaxPixelChannels+1], M20[MaxPixelChannels+1], M21[MaxPixelChannels+1], M22[MaxPixelChannels+1], M30[MaxPixelChannels+1]; PointInfo centroid[MaxPixelChannels+1]; ssize_t channel, y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); channel_moments=(ChannelMoments *) AcquireQuantumMemory(MaxPixelChannels+1, sizeof(*channel_moments)); if (channel_moments == (ChannelMoments *) NULL) return(channel_moments); (void) memset(channel_moments,0,(MaxPixelChannels+1)* sizeof(*channel_moments)); (void) memset(centroid,0,sizeof(centroid)); (void) memset(M00,0,sizeof(M00)); (void) memset(M01,0,sizeof(M01)); (void) memset(M02,0,sizeof(M02)); (void) memset(M03,0,sizeof(M03)); (void) memset(M10,0,sizeof(M10)); (void) memset(M11,0,sizeof(M11)); (void) memset(M12,0,sizeof(M12)); (void) memset(M20,0,sizeof(M20)); (void) memset(M21,0,sizeof(M21)); (void) memset(M22,0,sizeof(M22)); (void) memset(M30,0,sizeof(M30)); image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; /* Compute center of mass (centroid). */ p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; if ((traits & UpdatePixelTrait) == 0) continue; M00[channel]+=QuantumScale*p[i]; M00[MaxPixelChannels]+=QuantumScale*p[i]; M10[channel]+=x*QuantumScale*p[i]; M10[MaxPixelChannels]+=x*QuantumScale*p[i]; M01[channel]+=y*QuantumScale*p[i]; M01[MaxPixelChannels]+=y*QuantumScale*p[i]; } p+=GetPixelChannels(image); } } for (channel=0; channel <= MaxPixelChannels; channel++) { /* Compute center of mass (centroid). */ if (M00[channel] < MagickEpsilon) { M00[channel]+=MagickEpsilon; centroid[channel].x=(double) image->columns/2.0; centroid[channel].y=(double) image->rows/2.0; continue; } M00[channel]+=MagickEpsilon; centroid[channel].x=M10[channel]/M00[channel]; centroid[channel].y=M01[channel]/M00[channel]; } for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; /* Compute the image moments. */ p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; if ((traits & UpdatePixelTrait) == 0) continue; M11[channel]+=(x-centroid[channel].x)*(y-centroid[channel].y)* QuantumScale*p[i]; M11[MaxPixelChannels]+=(x-centroid[channel].x)*(y-centroid[channel].y)* QuantumScale*p[i]; M20[channel]+=(x-centroid[channel].x)*(x-centroid[channel].x)* QuantumScale*p[i]; M20[MaxPixelChannels]+=(x-centroid[channel].x)*(x-centroid[channel].x)* QuantumScale*p[i]; M02[channel]+=(y-centroid[channel].y)*(y-centroid[channel].y)* QuantumScale*p[i]; M02[MaxPixelChannels]+=(y-centroid[channel].y)*(y-centroid[channel].y)* QuantumScale*p[i]; M21[channel]+=(x-centroid[channel].x)*(x-centroid[channel].x)* (y-centroid[channel].y)*QuantumScale*p[i]; M21[MaxPixelChannels]+=(x-centroid[channel].x)*(x-centroid[channel].x)* (y-centroid[channel].y)*QuantumScale*p[i]; M12[channel]+=(x-centroid[channel].x)*(y-centroid[channel].y)* (y-centroid[channel].y)*QuantumScale*p[i]; M12[MaxPixelChannels]+=(x-centroid[channel].x)*(y-centroid[channel].y)* (y-centroid[channel].y)*QuantumScale*p[i]; M22[channel]+=(x-centroid[channel].x)*(x-centroid[channel].x)* (y-centroid[channel].y)*(y-centroid[channel].y)*QuantumScale*p[i]; M22[MaxPixelChannels]+=(x-centroid[channel].x)*(x-centroid[channel].x)* (y-centroid[channel].y)*(y-centroid[channel].y)*QuantumScale*p[i]; M30[channel]+=(x-centroid[channel].x)*(x-centroid[channel].x)* (x-centroid[channel].x)*QuantumScale*p[i]; M30[MaxPixelChannels]+=(x-centroid[channel].x)*(x-centroid[channel].x)* (x-centroid[channel].x)*QuantumScale*p[i]; M03[channel]+=(y-centroid[channel].y)*(y-centroid[channel].y)* (y-centroid[channel].y)*QuantumScale*p[i]; M03[MaxPixelChannels]+=(y-centroid[channel].y)*(y-centroid[channel].y)* (y-centroid[channel].y)*QuantumScale*p[i]; } p+=GetPixelChannels(image); } } M00[MaxPixelChannels]/=GetImageChannels(image); M01[MaxPixelChannels]/=GetImageChannels(image); M02[MaxPixelChannels]/=GetImageChannels(image); M03[MaxPixelChannels]/=GetImageChannels(image); M10[MaxPixelChannels]/=GetImageChannels(image); M11[MaxPixelChannels]/=GetImageChannels(image); M12[MaxPixelChannels]/=GetImageChannels(image); M20[MaxPixelChannels]/=GetImageChannels(image); M21[MaxPixelChannels]/=GetImageChannels(image); M22[MaxPixelChannels]/=GetImageChannels(image); M30[MaxPixelChannels]/=GetImageChannels(image); for (channel=0; channel <= MaxPixelChannels; channel++) { /* Compute elliptical angle, major and minor axes, eccentricity, & intensity. */ channel_moments[channel].centroid=centroid[channel]; channel_moments[channel].ellipse_axis.x=sqrt((2.0/M00[channel])* ((M20[channel]+M02[channel])+sqrt(4.0*M11[channel]*M11[channel]+ (M20[channel]-M02[channel])*(M20[channel]-M02[channel])))); channel_moments[channel].ellipse_axis.y=sqrt((2.0/M00[channel])* ((M20[channel]+M02[channel])-sqrt(4.0*M11[channel]*M11[channel]+ (M20[channel]-M02[channel])*(M20[channel]-M02[channel])))); channel_moments[channel].ellipse_angle=RadiansToDegrees(0.5*atan(2.0* M11[channel]/(M20[channel]-M02[channel]+MagickEpsilon))); if (fabs(M11[channel]) < MagickEpsilon) { if (fabs(M20[channel]-M02[channel]) < MagickEpsilon) channel_moments[channel].ellipse_angle+=0.0; else if ((M20[channel]-M02[channel]) < 0.0) channel_moments[channel].ellipse_angle+=90.0; else channel_moments[channel].ellipse_angle+=0.0; } else if (M11[channel] < 0.0) { if (fabs(M20[channel]-M02[channel]) < MagickEpsilon) channel_moments[channel].ellipse_angle+=0.0; else if ((M20[channel]-M02[channel]) < 0.0) channel_moments[channel].ellipse_angle+=90.0; else channel_moments[channel].ellipse_angle+=180.0; } else { if (fabs(M20[channel]-M02[channel]) < MagickEpsilon) channel_moments[channel].ellipse_angle+=0.0; else if ((M20[channel]-M02[channel]) < 0.0) channel_moments[channel].ellipse_angle+=90.0; else channel_moments[channel].ellipse_angle+=0.0; } channel_moments[channel].ellipse_eccentricity=sqrt(1.0-( channel_moments[channel].ellipse_axis.y/ (channel_moments[channel].ellipse_axis.x+MagickEpsilon))); channel_moments[channel].ellipse_intensity=M00[channel]/ (MagickPI*channel_moments[channel].ellipse_axis.x* channel_moments[channel].ellipse_axis.y+MagickEpsilon); } for (channel=0; channel <= MaxPixelChannels; channel++) { /* Normalize image moments. */ M10[channel]=0.0; M01[channel]=0.0; M11[channel]/=pow(M00[channel],1.0+(1.0+1.0)/2.0); M20[channel]/=pow(M00[channel],1.0+(2.0+0.0)/2.0); M02[channel]/=pow(M00[channel],1.0+(0.0+2.0)/2.0); M21[channel]/=pow(M00[channel],1.0+(2.0+1.0)/2.0); M12[channel]/=pow(M00[channel],1.0+(1.0+2.0)/2.0); M22[channel]/=pow(M00[channel],1.0+(2.0+2.0)/2.0); M30[channel]/=pow(M00[channel],1.0+(3.0+0.0)/2.0); M03[channel]/=pow(M00[channel],1.0+(0.0+3.0)/2.0); M00[channel]=1.0; } image_view=DestroyCacheView(image_view); for (channel=0; channel <= MaxPixelChannels; channel++) { /* Compute Hu invariant moments. */ channel_moments[channel].invariant[0]=M20[channel]+M02[channel]; channel_moments[channel].invariant[1]=(M20[channel]-M02[channel])* (M20[channel]-M02[channel])+4.0*M11[channel]*M11[channel]; channel_moments[channel].invariant[2]=(M30[channel]-3.0*M12[channel])* (M30[channel]-3.0*M12[channel])+(3.0*M21[channel]-M03[channel])* (3.0*M21[channel]-M03[channel]); channel_moments[channel].invariant[3]=(M30[channel]+M12[channel])* (M30[channel]+M12[channel])+(M21[channel]+M03[channel])* (M21[channel]+M03[channel]); channel_moments[channel].invariant[4]=(M30[channel]-3.0*M12[channel])* (M30[channel]+M12[channel])*((M30[channel]+M12[channel])* (M30[channel]+M12[channel])-3.0*(M21[channel]+M03[channel])* (M21[channel]+M03[channel]))+(3.0*M21[channel]-M03[channel])* (M21[channel]+M03[channel])*(3.0*(M30[channel]+M12[channel])* (M30[channel]+M12[channel])-(M21[channel]+M03[channel])* (M21[channel]+M03[channel])); channel_moments[channel].invariant[5]=(M20[channel]-M02[channel])* ((M30[channel]+M12[channel])*(M30[channel]+M12[channel])- (M21[channel]+M03[channel])*(M21[channel]+M03[channel]))+ 4.0*M11[channel]*(M30[channel]+M12[channel])*(M21[channel]+M03[channel]); channel_moments[channel].invariant[6]=(3.0*M21[channel]-M03[channel])* (M30[channel]+M12[channel])*((M30[channel]+M12[channel])* (M30[channel]+M12[channel])-3.0*(M21[channel]+M03[channel])* (M21[channel]+M03[channel]))-(M30[channel]-3*M12[channel])* (M21[channel]+M03[channel])*(3.0*(M30[channel]+M12[channel])* (M30[channel]+M12[channel])-(M21[channel]+M03[channel])* (M21[channel]+M03[channel])); channel_moments[channel].invariant[7]=M11[channel]*((M30[channel]+ M12[channel])*(M30[channel]+M12[channel])-(M03[channel]+M21[channel])* (M03[channel]+M21[channel]))-(M20[channel]-M02[channel])* (M30[channel]+M12[channel])*(M03[channel]+M21[channel]); } if (y < (ssize_t) image->rows) channel_moments=(ChannelMoments *) RelinquishMagickMemory(channel_moments); return(channel_moments); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l P e r c e p t u a l H a s h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImagePerceptualHash() returns the perceptual hash of one or more % image channels. % % The format of the GetImagePerceptualHash method is: % % ChannelPerceptualHash *GetImagePerceptualHash(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ static inline double MagickLog10(const double x) { #define Log10Epsilon (1.0e-11) if (fabs(x) < Log10Epsilon) return(log10(Log10Epsilon)); return(log10(fabs(x))); } MagickExport ChannelPerceptualHash *GetImagePerceptualHash(const Image *image, ExceptionInfo *exception) { ChannelPerceptualHash *perceptual_hash; char *colorspaces, *q; const char *artifact; MagickBooleanType status; register char *p; register ssize_t i; perceptual_hash=(ChannelPerceptualHash *) AcquireQuantumMemory( MaxPixelChannels+1UL,sizeof(*perceptual_hash)); if (perceptual_hash == (ChannelPerceptualHash *) NULL) return((ChannelPerceptualHash *) NULL); artifact=GetImageArtifact(image,"phash:colorspaces"); if (artifact != NULL) colorspaces=AcquireString(artifact); else colorspaces=AcquireString("sRGB,HCLp"); perceptual_hash[0].number_colorspaces=0; perceptual_hash[0].number_channels=0; q=colorspaces; for (i=0; (p=StringToken(",",&q)) != (char *) NULL; i++) { ChannelMoments *moments; Image *hash_image; size_t j; ssize_t channel, colorspace; if (i >= MaximumNumberOfPerceptualColorspaces) break; colorspace=ParseCommandOption(MagickColorspaceOptions,MagickFalse,p); if (colorspace < 0) break; perceptual_hash[0].colorspace[i]=(ColorspaceType) colorspace; hash_image=BlurImage(image,0.0,1.0,exception); if (hash_image == (Image *) NULL) break; hash_image->depth=8; status=TransformImageColorspace(hash_image,(ColorspaceType) colorspace, exception); if (status == MagickFalse) break; moments=GetImageMoments(hash_image,exception); perceptual_hash[0].number_colorspaces++; perceptual_hash[0].number_channels+=GetImageChannels(hash_image); hash_image=DestroyImage(hash_image); if (moments == (ChannelMoments *) NULL) break; for (channel=0; channel <= MaxPixelChannels; channel++) for (j=0; j < MaximumNumberOfImageMoments; j++) perceptual_hash[channel].phash[i][j]= (-MagickLog10(moments[channel].invariant[j])); moments=(ChannelMoments *) RelinquishMagickMemory(moments); } colorspaces=DestroyString(colorspaces); return(perceptual_hash); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e R a n g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageRange() returns the range of one or more image channels. % % The format of the GetImageRange method is: % % MagickBooleanType GetImageRange(const Image *image,double *minima, % double *maxima,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o minima: the minimum value in the channel. % % o maxima: the maximum value in the channel. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageRange(const Image *image,double *minima, double *maxima,ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType initialize, status; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=MagickTrue; initialize=MagickTrue; *maxima=0.0; *minima=0.0; image_view=AcquireVirtualCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status,initialize) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { double row_maxima = 0.0, row_minima = 0.0; MagickBooleanType row_initialize; register const Quantum *magick_restrict p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } row_initialize=MagickTrue; for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; if ((traits & UpdatePixelTrait) == 0) continue; if (row_initialize != MagickFalse) { row_minima=(double) p[i]; row_maxima=(double) p[i]; row_initialize=MagickFalse; } else { if ((double) p[i] < row_minima) row_minima=(double) p[i]; if ((double) p[i] > row_maxima) row_maxima=(double) p[i]; } } p+=GetPixelChannels(image); } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_GetImageRange) #endif { if (initialize != MagickFalse) { *minima=row_minima; *maxima=row_maxima; initialize=MagickFalse; } else { if (row_minima < *minima) *minima=row_minima; if (row_maxima > *maxima) *maxima=row_maxima; } } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e S t a t i s t i c s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageStatistics() returns statistics for each channel in the image. The % statistics include the channel depth, its minima, maxima, mean, standard % deviation, kurtosis and skewness. You can access the red channel mean, for % example, like this: % % channel_statistics=GetImageStatistics(image,exception); % red_mean=channel_statistics[RedPixelChannel].mean; % % Use MagickRelinquishMemory() to free the statistics buffer. % % The format of the GetImageStatistics method is: % % ChannelStatistics *GetImageStatistics(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport ChannelStatistics *GetImageStatistics(const Image *image, ExceptionInfo *exception) { ChannelStatistics *channel_statistics; double area, *histogram, standard_deviation; MagickStatusType status; QuantumAny range; register ssize_t i; size_t depth; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,GetPixelChannels(image)* sizeof(*histogram)); channel_statistics=(ChannelStatistics *) AcquireQuantumMemory( MaxPixelChannels+1,sizeof(*channel_statistics)); if ((channel_statistics == (ChannelStatistics *) NULL) || (histogram == (double *) NULL)) { if (histogram != (double *) NULL) histogram=(double *) RelinquishMagickMemory(histogram); if (channel_statistics != (ChannelStatistics *) NULL) channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(channel_statistics); } (void) memset(channel_statistics,0,(MaxPixelChannels+1)* sizeof(*channel_statistics)); for (i=0; i <= (ssize_t) MaxPixelChannels; i++) { channel_statistics[i].depth=1; channel_statistics[i].maxima=(-MagickMaximumValue); channel_statistics[i].minima=MagickMaximumValue; } (void) memset(histogram,0,(MaxMap+1)*GetPixelChannels(image)* sizeof(*histogram)); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; /* Compute pixel statistics. */ p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; if (GetPixelReadMask(image,p) <= (QuantumRange/2)) { p+=GetPixelChannels(image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; if ((traits & UpdatePixelTrait) == 0) continue; if (channel_statistics[channel].depth != MAGICKCORE_QUANTUM_DEPTH) { depth=channel_statistics[channel].depth; range=GetQuantumRange(depth); status=p[i] != ScaleAnyToQuantum(ScaleQuantumToAny(p[i],range), range) ? MagickTrue : MagickFalse; if (status != MagickFalse) { channel_statistics[channel].depth++; i--; continue; } } if ((double) p[i] < channel_statistics[channel].minima) channel_statistics[channel].minima=(double) p[i]; if ((double) p[i] > channel_statistics[channel].maxima) channel_statistics[channel].maxima=(double) p[i]; channel_statistics[channel].sum+=p[i]; channel_statistics[channel].sum_squared+=(double) p[i]*p[i]; channel_statistics[channel].sum_cubed+=(double) p[i]*p[i]*p[i]; channel_statistics[channel].sum_fourth_power+=(double) p[i]*p[i]*p[i]* p[i]; channel_statistics[channel].area++; if ((double) p[i] < channel_statistics[CompositePixelChannel].minima) channel_statistics[CompositePixelChannel].minima=(double) p[i]; if ((double) p[i] > channel_statistics[CompositePixelChannel].maxima) channel_statistics[CompositePixelChannel].maxima=(double) p[i]; histogram[GetPixelChannels(image)*ScaleQuantumToMap( ClampToQuantum((double) p[i]))+i]++; channel_statistics[CompositePixelChannel].sum+=(double) p[i]; channel_statistics[CompositePixelChannel].sum_squared+=(double) p[i]*p[i]; channel_statistics[CompositePixelChannel].sum_cubed+=(double) p[i]*p[i]*p[i]; channel_statistics[CompositePixelChannel].sum_fourth_power+=(double) p[i]*p[i]*p[i]*p[i]; channel_statistics[CompositePixelChannel].area++; } p+=GetPixelChannels(image); } } for (i=0; i <= (ssize_t) MaxPixelChannels; i++) { /* Normalize pixel statistics. */ area=PerceptibleReciprocal(channel_statistics[i].area); channel_statistics[i].sum*=area; channel_statistics[i].sum_squared*=area; channel_statistics[i].sum_cubed*=area; channel_statistics[i].sum_fourth_power*=area; channel_statistics[i].mean=channel_statistics[i].sum; channel_statistics[i].variance=channel_statistics[i].sum_squared; standard_deviation=sqrt(channel_statistics[i].variance- (channel_statistics[i].mean*channel_statistics[i].mean)); standard_deviation=sqrt(PerceptibleReciprocal(channel_statistics[i].area- 1.0)*channel_statistics[i].area*standard_deviation*standard_deviation); channel_statistics[i].standard_deviation=standard_deviation; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double number_bins; register ssize_t j; /* Compute pixel entropy. */ PixelChannel channel = GetPixelChannelChannel(image,i); number_bins=0.0; for (j=0; j <= (ssize_t) MaxMap; j++) if (histogram[GetPixelChannels(image)*j+i] > 0.0) number_bins++; area=PerceptibleReciprocal(channel_statistics[channel].area); for (j=0; j <= (ssize_t) MaxMap; j++) { double count; count=area*histogram[GetPixelChannels(image)*j+i]; channel_statistics[channel].entropy+=-count*MagickLog10(count)* PerceptibleReciprocal(MagickLog10(number_bins)); channel_statistics[CompositePixelChannel].entropy+=-count* MagickLog10(count)*PerceptibleReciprocal(MagickLog10(number_bins))/ GetPixelChannels(image); } } histogram=(double *) RelinquishMagickMemory(histogram); for (i=0; i <= (ssize_t) MaxPixelChannels; i++) { /* Compute kurtosis & skewness statistics. */ standard_deviation=PerceptibleReciprocal( channel_statistics[i].standard_deviation); channel_statistics[i].skewness=(channel_statistics[i].sum_cubed-3.0* channel_statistics[i].mean*channel_statistics[i].sum_squared+2.0* channel_statistics[i].mean*channel_statistics[i].mean* channel_statistics[i].mean)*(standard_deviation*standard_deviation* standard_deviation); channel_statistics[i].kurtosis=(channel_statistics[i].sum_fourth_power-4.0* channel_statistics[i].mean*channel_statistics[i].sum_cubed+6.0* channel_statistics[i].mean*channel_statistics[i].mean* channel_statistics[i].sum_squared-3.0*channel_statistics[i].mean* channel_statistics[i].mean*1.0*channel_statistics[i].mean* channel_statistics[i].mean)*(standard_deviation*standard_deviation* standard_deviation*standard_deviation)-3.0; } channel_statistics[CompositePixelChannel].mean=0.0; channel_statistics[CompositePixelChannel].standard_deviation=0.0; channel_statistics[CompositePixelChannel].entropy=0.0; for (i=0; i < (ssize_t) MaxPixelChannels; i++) { channel_statistics[CompositePixelChannel].mean+= channel_statistics[i].mean; channel_statistics[CompositePixelChannel].standard_deviation+= channel_statistics[i].standard_deviation; channel_statistics[CompositePixelChannel].entropy+= channel_statistics[i].entropy; } channel_statistics[CompositePixelChannel].mean/=(double) GetImageChannels(image); channel_statistics[CompositePixelChannel].standard_deviation/=(double) GetImageChannels(image); channel_statistics[CompositePixelChannel].entropy/=(double) GetImageChannels(image); if (y < (ssize_t) image->rows) channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(channel_statistics); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P o l y n o m i a l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PolynomialImage() returns a new image where each pixel is the sum of the % pixels in the image sequence after applying its corresponding terms % (coefficient and degree pairs). % % The format of the PolynomialImage method is: % % Image *PolynomialImage(const Image *images,const size_t number_terms, % const double *terms,ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image sequence. % % o number_terms: the number of terms in the list. The actual list length % is 2 x number_terms + 1 (the constant). % % o terms: the list of polynomial coefficients and degree pairs and a % constant. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *PolynomialImage(const Image *images, const size_t number_terms,const double *terms,ExceptionInfo *exception) { #define PolynomialImageTag "Polynomial/Image" CacheView *polynomial_view; Image *image; MagickBooleanType status; MagickOffsetType progress; PixelChannels **magick_restrict polynomial_pixels; size_t number_images; ssize_t y; assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImageCanvas(images,exception); if (image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) { image=DestroyImage(image); return((Image *) NULL); } number_images=GetImageListLength(images); polynomial_pixels=AcquirePixelThreadSet(images); if (polynomial_pixels == (PixelChannels **) NULL) { image=DestroyImage(image); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename); return((Image *) NULL); } /* Polynomial image pixels. */ status=MagickTrue; progress=0; polynomial_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { CacheView *image_view; const Image *next; const int id = GetOpenMPThreadId(); register ssize_t i, x; register PixelChannels *polynomial_pixel; register Quantum *magick_restrict q; ssize_t j; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(polynomial_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } polynomial_pixel=polynomial_pixels[id]; for (j=0; j < (ssize_t) image->columns; j++) for (i=0; i < MaxPixelChannels; i++) polynomial_pixel[j].channel[i]=0.0; next=images; for (j=0; j < (ssize_t) number_images; j++) { register const Quantum *p; if (j >= (ssize_t) number_terms) continue; image_view=AcquireVirtualCacheView(next,exception); p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { image_view=DestroyCacheView(image_view); break; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(next); i++) { MagickRealType coefficient, degree; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(next,channel); PixelTrait polynomial_traits=GetPixelChannelTraits(image,channel); if ((traits == UndefinedPixelTrait) || (polynomial_traits == UndefinedPixelTrait)) continue; if ((traits & UpdatePixelTrait) == 0) continue; coefficient=(MagickRealType) terms[2*j]; degree=(MagickRealType) terms[(j << 1)+1]; polynomial_pixel[x].channel[i]+=coefficient* pow(QuantumScale*GetPixelChannel(image,channel,p),degree); } p+=GetPixelChannels(next); } image_view=DestroyCacheView(image_view); next=GetNextImageInList(next); } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; if ((traits & UpdatePixelTrait) == 0) continue; q[i]=ClampToQuantum(QuantumRange*polynomial_pixel[x].channel[i]); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(polynomial_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(images,PolynomialImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } polynomial_view=DestroyCacheView(polynomial_view); polynomial_pixels=DestroyPixelThreadSet(polynomial_pixels); if (status == MagickFalse) image=DestroyImage(image); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S t a t i s t i c I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % StatisticImage() makes each pixel the min / max / median / mode / etc. of % the neighborhood of the specified width and height. % % The format of the StatisticImage method is: % % Image *StatisticImage(const Image *image,const StatisticType type, % const size_t width,const size_t height,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o type: the statistic type (median, mode, etc.). % % o width: the width of the pixel neighborhood. % % o height: the height of the pixel neighborhood. % % o exception: return any errors or warnings in this structure. % */ typedef struct _SkipNode { size_t next[9], count, signature; } SkipNode; typedef struct _SkipList { ssize_t level; SkipNode *nodes; } SkipList; typedef struct _PixelList { size_t length, seed; SkipList skip_list; size_t signature; } PixelList; static PixelList *DestroyPixelList(PixelList *pixel_list) { if (pixel_list == (PixelList *) NULL) return((PixelList *) NULL); if (pixel_list->skip_list.nodes != (SkipNode *) NULL) pixel_list->skip_list.nodes=(SkipNode *) RelinquishAlignedMemory( pixel_list->skip_list.nodes); pixel_list=(PixelList *) RelinquishMagickMemory(pixel_list); return(pixel_list); } static PixelList **DestroyPixelListThreadSet(PixelList **pixel_list) { register ssize_t i; assert(pixel_list != (PixelList **) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (pixel_list[i] != (PixelList *) NULL) pixel_list[i]=DestroyPixelList(pixel_list[i]); pixel_list=(PixelList **) RelinquishMagickMemory(pixel_list); return(pixel_list); } static PixelList *AcquirePixelList(const size_t width,const size_t height) { PixelList *pixel_list; pixel_list=(PixelList *) AcquireMagickMemory(sizeof(*pixel_list)); if (pixel_list == (PixelList *) NULL) return(pixel_list); (void) memset((void *) pixel_list,0,sizeof(*pixel_list)); pixel_list->length=width*height; pixel_list->skip_list.nodes=(SkipNode *) AcquireAlignedMemory(65537UL, sizeof(*pixel_list->skip_list.nodes)); if (pixel_list->skip_list.nodes == (SkipNode *) NULL) return(DestroyPixelList(pixel_list)); (void) memset(pixel_list->skip_list.nodes,0,65537UL* sizeof(*pixel_list->skip_list.nodes)); pixel_list->signature=MagickCoreSignature; return(pixel_list); } static PixelList **AcquirePixelListThreadSet(const size_t width, const size_t height) { PixelList **pixel_list; register ssize_t i; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixel_list=(PixelList **) AcquireQuantumMemory(number_threads, sizeof(*pixel_list)); if (pixel_list == (PixelList **) NULL) return((PixelList **) NULL); (void) memset(pixel_list,0,number_threads*sizeof(*pixel_list)); for (i=0; i < (ssize_t) number_threads; i++) { pixel_list[i]=AcquirePixelList(width,height); if (pixel_list[i] == (PixelList *) NULL) return(DestroyPixelListThreadSet(pixel_list)); } return(pixel_list); } static void AddNodePixelList(PixelList *pixel_list,const size_t color) { register SkipList *p; register ssize_t level; size_t search, update[9]; /* Initialize the node. */ p=(&pixel_list->skip_list); p->nodes[color].signature=pixel_list->signature; p->nodes[color].count=1; /* Determine where it belongs in the list. */ search=65536UL; for (level=p->level; level >= 0; level--) { while (p->nodes[search].next[level] < color) search=p->nodes[search].next[level]; update[level]=search; } /* Generate a pseudo-random level for this node. */ for (level=0; ; level++) { pixel_list->seed=(pixel_list->seed*42893621L)+1L; if ((pixel_list->seed & 0x300) != 0x300) break; } if (level > 8) level=8; if (level > (p->level+2)) level=p->level+2; /* If we're raising the list's level, link back to the root node. */ while (level > p->level) { p->level++; update[p->level]=65536UL; } /* Link the node into the skip-list. */ do { p->nodes[color].next[level]=p->nodes[update[level]].next[level]; p->nodes[update[level]].next[level]=color; } while (level-- > 0); } static inline void GetMaximumPixelList(PixelList *pixel_list,Quantum *pixel) { register SkipList *p; size_t color, maximum; ssize_t count; /* Find the maximum value for each of the color. */ p=(&pixel_list->skip_list); color=65536L; count=0; maximum=p->nodes[color].next[0]; do { color=p->nodes[color].next[0]; if (color > maximum) maximum=color; count+=p->nodes[color].count; } while (count < (ssize_t) pixel_list->length); *pixel=ScaleShortToQuantum((unsigned short) maximum); } static inline void GetMeanPixelList(PixelList *pixel_list,Quantum *pixel) { double sum; register SkipList *p; size_t color; ssize_t count; /* Find the mean value for each of the color. */ p=(&pixel_list->skip_list); color=65536L; count=0; sum=0.0; do { color=p->nodes[color].next[0]; sum+=(double) p->nodes[color].count*color; count+=p->nodes[color].count; } while (count < (ssize_t) pixel_list->length); sum/=pixel_list->length; *pixel=ScaleShortToQuantum((unsigned short) sum); } static inline void GetMedianPixelList(PixelList *pixel_list,Quantum *pixel) { register SkipList *p; size_t color; ssize_t count; /* Find the median value for each of the color. */ p=(&pixel_list->skip_list); color=65536L; count=0; do { color=p->nodes[color].next[0]; count+=p->nodes[color].count; } while (count <= (ssize_t) (pixel_list->length >> 1)); *pixel=ScaleShortToQuantum((unsigned short) color); } static inline void GetMinimumPixelList(PixelList *pixel_list,Quantum *pixel) { register SkipList *p; size_t color, minimum; ssize_t count; /* Find the minimum value for each of the color. */ p=(&pixel_list->skip_list); count=0; color=65536UL; minimum=p->nodes[color].next[0]; do { color=p->nodes[color].next[0]; if (color < minimum) minimum=color; count+=p->nodes[color].count; } while (count < (ssize_t) pixel_list->length); *pixel=ScaleShortToQuantum((unsigned short) minimum); } static inline void GetModePixelList(PixelList *pixel_list,Quantum *pixel) { register SkipList *p; size_t color, max_count, mode; ssize_t count; /* Make each pixel the 'predominant color' of the specified neighborhood. */ p=(&pixel_list->skip_list); color=65536L; mode=color; max_count=p->nodes[mode].count; count=0; do { color=p->nodes[color].next[0]; if (p->nodes[color].count > max_count) { mode=color; max_count=p->nodes[mode].count; } count+=p->nodes[color].count; } while (count < (ssize_t) pixel_list->length); *pixel=ScaleShortToQuantum((unsigned short) mode); } static inline void GetNonpeakPixelList(PixelList *pixel_list,Quantum *pixel) { register SkipList *p; size_t color, next, previous; ssize_t count; /* Finds the non peak value for each of the colors. */ p=(&pixel_list->skip_list); color=65536L; next=p->nodes[color].next[0]; count=0; do { previous=color; color=next; next=p->nodes[color].next[0]; count+=p->nodes[color].count; } while (count <= (ssize_t) (pixel_list->length >> 1)); if ((previous == 65536UL) && (next != 65536UL)) color=next; else if ((previous != 65536UL) && (next == 65536UL)) color=previous; *pixel=ScaleShortToQuantum((unsigned short) color); } static inline void GetRootMeanSquarePixelList(PixelList *pixel_list, Quantum *pixel) { double sum; register SkipList *p; size_t color; ssize_t count; /* Find the root mean square value for each of the color. */ p=(&pixel_list->skip_list); color=65536L; count=0; sum=0.0; do { color=p->nodes[color].next[0]; sum+=(double) (p->nodes[color].count*color*color); count+=p->nodes[color].count; } while (count < (ssize_t) pixel_list->length); sum/=pixel_list->length; *pixel=ScaleShortToQuantum((unsigned short) sqrt(sum)); } static inline void GetStandardDeviationPixelList(PixelList *pixel_list, Quantum *pixel) { double sum, sum_squared; register SkipList *p; size_t color; ssize_t count; /* Find the standard-deviation value for each of the color. */ p=(&pixel_list->skip_list); color=65536L; count=0; sum=0.0; sum_squared=0.0; do { register ssize_t i; color=p->nodes[color].next[0]; sum+=(double) p->nodes[color].count*color; for (i=0; i < (ssize_t) p->nodes[color].count; i++) sum_squared+=((double) color)*((double) color); count+=p->nodes[color].count; } while (count < (ssize_t) pixel_list->length); sum/=pixel_list->length; sum_squared/=pixel_list->length; *pixel=ScaleShortToQuantum((unsigned short) sqrt(sum_squared-(sum*sum))); } static inline void InsertPixelList(const Quantum pixel,PixelList *pixel_list) { size_t signature; unsigned short index; index=ScaleQuantumToShort(pixel); signature=pixel_list->skip_list.nodes[index].signature; if (signature == pixel_list->signature) { pixel_list->skip_list.nodes[index].count++; return; } AddNodePixelList(pixel_list,index); } static void ResetPixelList(PixelList *pixel_list) { int level; register SkipNode *root; register SkipList *p; /* Reset the skip-list. */ p=(&pixel_list->skip_list); root=p->nodes+65536UL; p->level=0; for (level=0; level < 9; level++) root->next[level]=65536UL; pixel_list->seed=pixel_list->signature++; } MagickExport Image *StatisticImage(const Image *image,const StatisticType type, const size_t width,const size_t height,ExceptionInfo *exception) { #define StatisticImageTag "Statistic/Image" CacheView *image_view, *statistic_view; Image *statistic_image; MagickBooleanType status; MagickOffsetType progress; PixelList **magick_restrict pixel_list; ssize_t center, y; /* Initialize statistics image attributes. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); statistic_image=CloneImage(image,0,0,MagickTrue, exception); if (statistic_image == (Image *) NULL) return((Image *) NULL); status=SetImageStorageClass(statistic_image,DirectClass,exception); if (status == MagickFalse) { statistic_image=DestroyImage(statistic_image); return((Image *) NULL); } pixel_list=AcquirePixelListThreadSet(MagickMax(width,1),MagickMax(height,1)); if (pixel_list == (PixelList **) NULL) { statistic_image=DestroyImage(statistic_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } /* Make each pixel the min / max / median / mode / etc. of the neighborhood. */ center=(ssize_t) GetPixelChannels(image)*(image->columns+MagickMax(width,1))* (MagickMax(height,1)/2L)+GetPixelChannels(image)*(MagickMax(width,1)/2L); status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); statistic_view=AcquireAuthenticCacheView(statistic_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,statistic_image,statistic_image->rows,1) #endif for (y=0; y < (ssize_t) statistic_image->rows; y++) { const int id = GetOpenMPThreadId(); register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-((ssize_t) MagickMax(width,1)/2L),y- (ssize_t) (MagickMax(height,1)/2L),image->columns+MagickMax(width,1), MagickMax(height,1),exception); q=QueueCacheViewAuthenticPixels(statistic_view,0,y,statistic_image->columns, 1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) statistic_image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { Quantum pixel; register const Quantum *magick_restrict pixels; register ssize_t u; ssize_t v; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait statistic_traits=GetPixelChannelTraits(statistic_image, channel); if ((traits == UndefinedPixelTrait) || (statistic_traits == UndefinedPixelTrait)) continue; if (((statistic_traits & CopyPixelTrait) != 0) || (GetPixelWriteMask(image,p) <= (QuantumRange/2))) { SetPixelChannel(statistic_image,channel,p[center+i],q); continue; } if ((statistic_traits & UpdatePixelTrait) == 0) continue; pixels=p; ResetPixelList(pixel_list[id]); for (v=0; v < (ssize_t) MagickMax(height,1); v++) { for (u=0; u < (ssize_t) MagickMax(width,1); u++) { InsertPixelList(pixels[i],pixel_list[id]); pixels+=GetPixelChannels(image); } pixels+=GetPixelChannels(image)*image->columns; } switch (type) { case GradientStatistic: { double maximum, minimum; GetMinimumPixelList(pixel_list[id],&pixel); minimum=(double) pixel; GetMaximumPixelList(pixel_list[id],&pixel); maximum=(double) pixel; pixel=ClampToQuantum(MagickAbsoluteValue(maximum-minimum)); break; } case MaximumStatistic: { GetMaximumPixelList(pixel_list[id],&pixel); break; } case MeanStatistic: { GetMeanPixelList(pixel_list[id],&pixel); break; } case MedianStatistic: default: { GetMedianPixelList(pixel_list[id],&pixel); break; } case MinimumStatistic: { GetMinimumPixelList(pixel_list[id],&pixel); break; } case ModeStatistic: { GetModePixelList(pixel_list[id],&pixel); break; } case NonpeakStatistic: { GetNonpeakPixelList(pixel_list[id],&pixel); break; } case RootMeanSquareStatistic: { GetRootMeanSquarePixelList(pixel_list[id],&pixel); break; } case StandardDeviationStatistic: { GetStandardDeviationPixelList(pixel_list[id],&pixel); break; } } SetPixelChannel(statistic_image,channel,pixel,q); } p+=GetPixelChannels(image); q+=GetPixelChannels(statistic_image); } if (SyncCacheViewAuthenticPixels(statistic_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,StatisticImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } statistic_view=DestroyCacheView(statistic_view); image_view=DestroyCacheView(image_view); pixel_list=DestroyPixelListThreadSet(pixel_list); if (status == MagickFalse) statistic_image=DestroyImage(statistic_image); return(statistic_image); }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_929_0